惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
A
About on SuperTechFans
NISL@THU
NISL@THU
V
Visual Studio Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
B
Blog RSS Feed
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
美团技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
小众软件
小众软件
博客园 - Franky
罗磊的独立博客
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
Hugging Face - Blog
Hugging Face - Blog
云风的 BLOG
云风的 BLOG
MongoDB | Blog
MongoDB | Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
The GitHub Blog
The GitHub Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
有赞技术团队
有赞技术团队
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cyberwarzone
Cyberwarzone
C
CXSECURITY Database RSS Feed - CXSecurity.com
Project Zero
Project Zero
Security Latest
Security Latest
L
Lohrmann on Cybersecurity
AWS News Blog
AWS News Blog
The Hacker News
The Hacker News
I
Intezer
J
Java Code Geeks
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Privacy International News Feed
月光博客
月光博客
A
Arctic Wolf
Apple Machine Learning Research
Apple Machine Learning Research
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园_首页
WordPress大学
WordPress大学
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tor Project blog
博客园 - 三生石上(FineUI控件)
The Last Watchdog
The Last Watchdog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org

Hacker News: Show HN

PurrrrrFocus: Pomodoro Timer App - App Store Workflow Engine — Multi-Step Orchestration for Bun RapidPhoto: Pro Photo Editor App - App Store GitHub - DheerG/swarms: Achieve extraordinary results with claude code across a variety of tasks SPICE simulation → oscilloscope → verification with Claude Code — Lucas Gerads Show HN: VCoding – A 5 MB native Windows IDE with no dynamic dependencies Show HN: LLMs don't hallucinate because they're bad at math, it's the format GitHub - Agent-FM/agentfm-core: AgentFM is a peer-to-peer network that turns everyday computers into a decentralized AI supercomputer. AgentFM lets you run massive AI workloads directly across a global mesh of idle CPUs and GPUs. Show HN: Tracking Top US Science Olympiad Alumni over Last 25 Years GitHub - Potarix/agent-hub: One place to talk to all your agents Show HN: Runtime security for AI agents(injection,tool abuse, data exfiltration) GitHub - dubeyKartikay/lazyspotify: Terminal Spotify client for macOS and Linux GitHub - the-banana-tool/king-louie: Easy to use GUI Personal AI Assistant. Win/Linux/Mac. Show HN I made my vacation rental bookable by AI agents–no Airbnb, 0% commission GitHub - basteez/jsf-autoreload: maven plugin to enable hot reload on jsf projects uvm32/hosts/host-gdbstub at main · ringtailsoftware/uvm32 GitHub - labsai/EDDI: Config-driven engine that turns JSON into production-grade AI agents. Multi-agent orchestration, 12+ LLM providers, MCP/A2A protocols, RAG, persistent memory, and enterprise compliance (EU AI Act, GDPR, HIPAA). Built on Quarkus. GitHub - glitchnsec/fortyone-oss: AI Executive Assistant Platform Quickstart | Alien GitHub - muxshed/shed: One stream in, or many. Every destination, simultaneously. No cloud middleman, no per-channel fees, no limits. GitHub - ocrbase-hq/ocrbase: 📄 PDF/IMG ->.MD/JSON Document OCR API for PaddleOCR and GLMOCR. Self-hostable. GitHub - impactjo/home-memory: MCP server that lets your AI assistant remember everything about your home. GitHub - Sets88/dbcls: DbCls is a powerful terminal database client that supports various databases GitHub - neptun2000/heor-agent-mcp GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh RollQuation: Math Puzzles - Apps on Google Play GitHub - dropbox/witchcraft Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis GitHub - opentalon/opentalon: OpenTalon is an open-source platform built from the ground up in Go as a robust alternative to OpenClaw LinkedIn™ 职位抓取工具 - Chrome 应用商店 GitHub - EdoardoBambini/Agent-Armor-Iaga: AI agents are getting tool access — shell, file system, databases, APIs, secrets. But **nobody is governing what they actually do with it**. Frameworks like LangChain, CrewAI, AutoGen, and Claude Code give agents the power to execute. Agent Armor gives you the power to control, audit, and approve every single action before it happens. HN Vibes — Week 15, Apr 7–13 2026 GitHub - chojs23/ec: Easy terminal-native 3-way git mergetool vim-like workflow GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - JakOb-dotcom/cloud-sandbox-security-analysis: Technical analysis and Proof of Concept (PoC) regarding environment variable exfiltration in containerized cloud sandboxes via side-channel data leaks. Springboards - Flint Alpha Show HN: A simpler coding agent harness GitHub - audiodude/sudomake-friends GitHub - 256thFission/mini-mythos: OSS clone of Anthropic’s Mythos harness to locate C/C++ memory vulnerabilities Show HN: OpenParallax: OS-level privilege separation for AI agent execution Hacker News Sorted - Chrome 应用商店 Show HN: How to Install Docker on Ubuntu 24.04 LTS: Complete 2026 Guide GitHub - himanshudongre/smriti GitHub - sverrirsig/claude-control: macOS desktop dashboard for monitoring and managing multiple Claude Code sessions GitHub - ory/dockertest: Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work. Chiral - Chrome 应用商店 Show HN: Two Claudes collaborating through shared memory on a $100 mini-PC GitHub - pmichaillat/latex-cv: Minimalist LaTeX template for academic CVs GitHub - oguzbilgic/posse: A web UI for Anthropic Managed Agents. GitHub - sshiraz/depsly: Dependency risk analysis tool for npm packages ABI Add safari/agent-harness — Safari browser automation via safari-mcp by achiya-automation · Pull Request #212 · HKUDS/CLI-Anything GitHub - Halfblood-Prince/trustcheck: Verify PyPI package attestations and improve Python supply-chain security GitHub - oguzbilgic/kern-ai: Agents that do the work and show it. GitHub - bruits/satteri: High-performance Markdown and MDX processing for the JavaScript ecosystem GitHub - tylergibbs1/feedstock: High-performance web crawler and scraper for TypeScript, powered by Bun and Playwright GitHub - Grimm67123/grimmbot: The self-improving sandboxed and open-source AI agent. With persistent memory and scheduling. GitHub - whitevanillaskies/whitebloom: Local whiteboard that blooms. GitHub - hwdsl2/docker-whisper: Docker image for a self-hosted Whisper speech-to-text server with speaker diarization and OpenAI-compatible transcription and translation APIs. Powered by faster-whisper. Supports all Whisper models, NVIDIA GPU (CUDA) acceleration, JSON/SRT/VTT output, SSE streaming, offline mode, and multi-arch (amd64, arm64). GitHub - yisding/reviewwiggum GitHub - MarwanAlsoltany/serrors: Structured errors for Go: sentinel hierarchies, typed data, custom formatting, and slog integration. GitHub - soatok/age-php GitHub - Luthiraa/markitme GitHub - stagas/rtdiff: realtime git diff gui and AI-assisted commits GitHub - tombedor/excalicharts GitHub - wh1le/excalidraw-edit: Open and edit .excalidraw files from the terminal. Offline, auto-saves to disk. MalExt Sentry - Malicious Extension Scanner - Chrome 应用商店 GitHub - syi0808/asciianimesvg: Generate animated ASCII art SVGs from text. CLI, Rust library, WASM, and web editor. GitHub - zaina-ml/ml_forge: A visual-based graph node editor for training computer vision models. GitHub - anakin87/llm-rl-environments-lil-course: 🌱 A little course on Reinforcement Learning Environments for evaluating and training Language Models GitHub - takaakit/superpowers-uml: Superpowers-UML modifies Superpowers to ensure a software development workflow in which AI agents design through UML modeling. AdriByte Studio - Sviluppo Web e Soluzioni Digitali GitHub - chouligi/angel-copilot: Your personalized Angel Investment Advisor Show HN: MoodSense AI (ML and FastAPI and Gradio, Deployed on Hugging Face) Moodsense Ai - a Hugging Face Space by aman179102 GitHub - agenteractai/lodmem: Level Of Detail Context Management for Agents GitHub - ostefani/subnetlens: A fast, concurrent network scanner with a TUI and plain-text CLI, built in Go. It discovers live hosts on your network, scans their open ports, resolves hostnames, and fingerprints operating systems—delivered. Cyber Pulse: Agentic Intel - Apps on Google Play Whisper API: Self-Hostable Speech to Text Transcription The Agent-Web Protocol Stack: A Research Thesis GitHub - msmarkgu/RelayFreeLLM: A restful API designed to route user prompts to various AI model providers. Show HN: Provepy – A Python decorator that proves your code using Lean and LLMs Show HN: Pardonned.com – A searchable database of US Pardons GitHub - patrickdappollonio/dux: Dux is a terminal UI that lets you run multiple AI coding agents side by side, each in its own git worktree, with full companion terminals, macros, commit generation, and a command palette that knows more tricks than you do. kMC Crystal Simulator Show HN: HyperFlow – A self-improving agent framework built on LangGraph GitHub - stef41/vibescore: 🎵 Grade your vibe-coded project. One command, instant letter grade across security, quality, dependencies, and testing. GitHub - stef41/lmscan: 🔍 Detect AI-generated text and fingerprint which LLM wrote it. Open-source GPTZero alternative. Zero dependencies, works offline. imgur.com GitHub - visionscaper/collabmem: Enabling long-term collaboration with Agentic AI - building up episodic and world model memory over time with in-context awareness 在 Steam 上购买 FriedrichAI: Offline AI 立省 10% GitHub - atripati/ark: AI Runtime Kernel — a context operating system for AI agents. Eliminates tool bloat, loads only what’s needed, and gives LLMs their reasoning space back. GitHub - nowork-studio/toprank: Open-source Claude Code skills for SEO, SEM, Google Ads GitHub - tacomanator/sash: Lightweight macOS menu bar app for reliably cycling through windows of the current application. Appents | Social Media Management for Product-First Teams GitHub - pnhoang/youtube-spam-blocker: Automatically detects and hides spam messages in YouTube Live chat. Set rate limits, keyword filters, and block repeat offenders. GitHub - decisionnode/DecisionNode: CLI + Local MCP - A shared structured memory store across Claude Code, Cursor, Windsurf, Antigravity, and every MCP client. Semantically queryable. GitHub - AvaCodeSolutions/django-email-learning: An open source Django app for creating email-based learning platforms with IMAP integration and React frontend components. The $100K Gap in Kubernetes Security Tooling Function Calling Harness: From 6.75% to 100%
GitHub - yuvhaim-gif/LLM_InSight: This my home rig testing process for creating evaluation metric, testing models, automating prompt creation in accordance to the evaluation results of last run and reviewing logs. its local first, independent of any specific tool and logs locally.
yuvalhaim · 2026-05-04 · via Hacker News: Show HN

LLM InSights

A local-first testing and optimization harness for iterative content creation — run multi-model A/B tests, refine prompts automatically with rubric-based grading, calibrate the grader to your own taste, and export training-ready datasets. Built for brand content workflows, prompt engineering, LLM evaluation, and dataset curation on your own hardware.

Python 3.10+ License: MIT

Walkthrough Walkthrough (~1.5 min)


What It Does

You write a prompt — a piece of brand copy, a product description, a creative brief, or any content task. The tool sends it to two competing LLM models, grades both answers against a configurable rubric, optionally rewrites the prompt using grader feedback, and repeats the cycle — keeping the best answer each round. Every variable is controlled from the UI: which models compete, what the rubric measures, how categories are weighted, and when the loop stops.

The pipeline runs locally by default using Ollama, with optional cloud API support (Mistral, Google Gemini) for hybrid setups. No data leaves your machine unless you choose a cloud provider.

Each run produces a structured record of prompts, answers, scores, token counts, and model metadata — useful as refined synthetic data, prompt optimization logs, or content quality benchmarks.

When you want the grader to match your judgment, Preference Studio closes the loop: you judge answer pairs head-to-head, watch live alignment metrics (pairwise accuracy, Cohen's κ, Spearman) on the calibration panel, re-fit weights or re-grade until the grader agrees with you, and then export curated, training-ready JSONL datasets — for either the production model (SFT / DPO / KTO) or a trainable pass/fail judge.


Key Capabilities

  • Custom Grading Rubrics — Define up to 8 grading categories, each with its own free-text rubric description, dedicated grader model, and weight. The default rubric covers accuracy, clarity, conciseness, creativity, and structure. Save named configurations and switch between them at any time.
  • Automatic Prompt Optimization — The system rewrites your prompt after each iteration using grader feedback, category weights, and best answers as context. Techniques are applied automatically while preserving the original intent, including Zero-Shot Prompting, Few-Shot Prompting, Chain-of-Thought (CoT), Self-Consistency, Least-to-Most Prompting, Tree of Thoughts (ToT), Directional Stimulus Prompting, Role Prompting, Generated Knowledge Prompting, Chain-of-Verification (CoVe), and Skeleton-of-Thought.
  • Multi-Model A/B Testing — Assign different models to each answering slot and compare their outputs head-to-head. The Advanced panel supports per-iteration model assignments for systematic cross-model comparisons.
  • Parallel Multi-Category Grading — Layer 3 grades each category in parallel using a thread pool, grouped by grader model. Failed graders fall back to a default score without stopping the pipeline. Retries with backoff are built in.
  • Synthetic Data Generation — Every run produces structured (prompt, answer, multi-dimensional scores) tuples and (original prompt, improved prompt) pairs. The JSONL ledger records prompts, replies, models, scores, and token counts. Multi-prompt sessions chain the best answer from the previous prompt as context into the next.
  • Token Tracking — Input, output, and total token counts are recorded per model per layer per iteration and aggregated by provider. Token usage is visible in the deeper analysis charts.
  • Tie Detection — When multiple iterations produce the same best score, the system identifies tied answers, deduplicates by text similarity, and reports alternatives.
  • Session Review and Analysis — Browse, load, and analyze past runs with per-prompt iteration stats, score grids, and an in-depth analysis modal featuring average grade bar charts, radar overlays, per-category score breakdowns, token usage charts, runtime comparisons, and adjustable weight sliders for live what-if recalculation.
  • Preference Studio (Human-in-the-Loop) — A unified /arena + /dataset page to judge answer pairs (which is better, a tie, or both bad), give your own 1–100 grades, pin ground truth, write gold answers, and blacklist bad answers. An active-learning queue surfaces the hardest / most-uncertain pairs first.
  • Grader Calibration — A calibration panel (on Config Graders) measures, live, how well the current grader reproduces your judgments (pairwise accuracy, Cohen's κ, Spearman, per-attribute alignment). Re-fit weights instantly (no model calls) or run a full re-grade with a candidate config, then apply and save.
  • Conflicts Report — A per-chat reconciliation (opened from each source row in Preference Studio) that lists exactly where your decisive judgments disagree with the grader's picks, with pairwise accuracy and Cohen's κ for the chat. A grading-version selector switches between the Original grading and later re-grade runs (newest auto-selected), and your chosen version is persisted per chat.
  • Training-Dataset Export — Build curated pools from exactly the sources you pick and export training-ready JSONL for a production model (sft, preference/DPO, kto) or a trainable pass/fail judge (preference/reward, judge_cls, judge_gen), each with a provenance sidecar and a summary card. All state is isolated from the live session.
  • REST API — All UI actions are backed by JSON endpoints — analysis (/iteration, /is-processing, /get_backup_data, /update_weights, /save_advanced_models, /grader_settings, /grader_setting/<name>) and Preference Studio (/api/arena/*, /api/calibrate/*, /api/dataset/*). Programmatic access to model selection, weight management, grader configuration, session backup, judging, calibration, and dataset export is available out of the box.

How the Pipeline Works

flowchart LR
    L0["Layer 0\n(brainstorm, optional)"] --> loop
    subgraph loop ["Repeat × N iterations"]
        direction LR
        L1A["Layer 1A\n(answer)"] --> G1["Layer 3\n(grade)"]
        G1 --> L2["Layer 2\n(rewrite prompt)"]
        L2 --> L1B["Layer 1B\n(answer)"]
        L1B --> G2["Layer 3\n(grade)"]
        G2 --> W["Pick winner"]
    end
Loading
Layer Role
Layer 0 Optional brainstorming step. Generates concise alternative ideas or directions before the loop begins.
Layer 1A / 1B Two competing answer models. Each produces a full response to the prompt (or improved prompt).
Layer 2 Prompt improver. Rewrites the prompt using grader feedback, best answers, and micro-replies as context.
Layer 3 Multi-category grader. Each category is evaluated independently by its own small LLM in parallel, scores are weighted and combined. Failed categories receive a default score so the pipeline continues.

Stop Conditions

The loop ends when the first of these is met:

  1. The best score reaches the target grade (default: 100).
  2. Degradation break is enabled and the score drops from the previous iteration.
  3. The maximum number of iterations is reached (default: 5).

Pages

Page Path Purpose
Login /login Simple authentication with an animated background
Main Analysis / Run experiments, configure models and toggles, view live results and charts
Config Graders /config_graders Create and edit grading rubrics — categories, rubric text, grader models, weights. Also hosts the Calibration panel (see Preference Studio)
Review History /review_chats Browse saved runs, load or delete past sessions, open the deeper analysis modal
Preference Studio /arena, /dataset Unified human-in-the-loop page with two tabs — Judge (pairwise judging to calibrate the grader and gather ground truth) and Build & Export (turn judgments, blacklist, and machine grades into training-ready JSONL). Both URLs open the same page on the matching tab

Preference Studio

A human-in-the-loop layer that calibrates the grader to your judgment and exports training-ready datasets. It is a single page — Preference Studio — with two tabs (a shared source rail spans both). See docs/preference_studio.md for the full operator + developer guide.

The loop: judge answer pairs in the Judge tab → watch alignment metrics on the Calibration panel (on Config Graders) and re-fit weights or re-grade → assemble curated pools in the Build & Export tab and export. The on-page How it works banner restates these steps.

Two training targets (pick on the Build & Export tab):

  • Production model — the model that performs the task. Formats: sft (good answers), preference (DPO/reward, chosen vs rejected), kto (good + bad).
  • Pass/Fail judge — a trainable Layer-3 grader. Formats: preference (reward model), judge_cls (binary classifier), judge_gen (generative PASS/FAIL).

Each source row in the shared rail also has a ⚠️ Report button that opens the Conflicts Report for that chat — a per-chat view of every pair where your decisive pick differs from the grader's, with the chat's pairwise accuracy and Cohen's κ. A grading-version selector lets you compare the Original grading against later re-grade runs (newest auto-selected), and your choice is saved per chat.

All Preference Studio state lives in an isolated preferences.db plus separate export/regrade directories; the live ledger is read-only here and never modified by re-grading.


Frontend Controls

Main Page — Sidebar (Model Selection)

Control Purpose
Layer 0 Model (Ideas) Selects the brainstorming model that runs before the loop
Answer Model 1 (Layer 1A) First answer model in each iteration
Answer Model 2 (Layer 1B) Second answer model in each iteration
Prompt Improver (Layer 2) Model that rewrites prompts using grader feedback
Advanced Panel Per-iteration model assignment for Layers 1A, 1B, and 2. Locks main selectors when saved
System Profile Filters model dropdowns by hardware tier (Simple / Medium / Powerful) — browser-side only, groups models by parameter size

Main Page — Controls Area

Control Purpose
Advise Models by Domain Filters model dropdowns to show only models suited to a task domain: Coding, Creative, Science, Experimental, or Balanced
Weight Preset Applies a predefined weight profile across grading categories (Balanced, Accuracy, Creativity, Conciseness)
Break Target Grade Stop the loop when this score is reached (1--100)
Iterations Maximum refinement rounds per prompt (1--5)
Degradation Break Stop if the score drops from the previous iteration
Change Prompt Enable or disable Layer 2 prompt rewriting
Give Ideas Enable or disable Layer 0 brainstorming
Last Best Answer Retention Feed the best answer from the previous iteration as context into the next
Grade vs. Current / First Prompt Choose whether graders judge the answer against the current or the first prompt in the session

Main Page — Weights and Grader Settings

Control Purpose
Weight Inputs Adjust category weights (auto-normalized). Apply and Reset buttons
Grader Setting Selector Switch between saved grading rubrics
Config Graders Link Opens the rubric editor page

Main Page — Action Buttons

Button Purpose
START ANALYSIS Runs the iterative analysis loop
Clear Chat Backs up and resets all runtime state
Upload Chat Imports a previously exported JSON backup
Download Chat Exports the session as a human-readable text log or a full restorable JSON backup
Review History Opens the Review page

Config Graders Page

Control Purpose
Load Setting Select and load an existing grading rubric
Edit / Cancel Toggle edit mode for the grading keys table
Key Name Category name (auto-lowercased, spaces converted to underscores)
Rubric Free-text description of scoring criteria
Grader Model Select which small LLM evaluates this category
Weight % How much this category counts toward the overall score
Add / Remove Keys Add a row (max 8) or remove an existing one
Weight Total Indicator Live sum — green at 100%, red otherwise
Save Setting Persist the configuration (blocked if incomplete or named default)

Review Page

Control Purpose
Chat List Browse all saved backups, newest first
Prompt Summary Scores, categories, models, and iterations for each prompt
Iteration Cards Layer 1A vs. 1B detail with winner, model, and runtime
Analyze Deeper Modal with average grade bar chart, radar overlay, per-category score breakdowns, token usage breakdown by provider, runtime comparison chart, adjustable weight sliders with live score recalculation for what-if analysis, weight reset, and the grader setting name from the original run
Load This Chat Restore a backup into the active session
Delete Chat Remove a backup file permanently
Upload Import and restore a JSON backup

Models and Providers

Calls are routed automatically based on the model name:

Provider Models Transport
Ollama All models not listed below (local inference) ollama.chat(), threaded with timeout
Mistral API mistral-small-2506, voxtral-mini-2507, open-mistral-nemo-2407 REST with retry, exponential backoff, and rate-limit handling
Google Gemini API gemini-2.5-flash, gemini-2.5-pro REST with retry, constant backoff, and rate-limit handling
GLM-4 (HuggingFace) glm-4-9b, glm-4-9b-chat Local transformers, cached, preloaded at startup

28 preconfigured models are available across layers, including gemma, granite, llama, qwen, deepseek-r1, deepseek-coder-v2, falcon3, phi4, devstral, solar, codellama, dolphin3, olmo2, starcoder2, and gpt-oss. All API calls are routed automatically based on the model name and include timeout handling; failures in any layer are caught gracefully so the pipeline continues.


Getting Started

Prerequisites

  • Python 3.10+
  • Ollama installed and running (required for local model inference unless you configure cloud-only providers)
  • A .env file with your credentials (see below)

Installation

git clone https://github.com/yuvhaim-gif/LLM_InSight.git
cd LLM_InSight
python -m venv venv
source venv/bin/activate   # Linux / macOS
venv\Scripts\activate      # Windows
pip install -r requirements.txt
cp .env.example .env       # then edit .env with your credentials

Environment Variables

Copy .env.example to .env and fill in your values.

Variable Required Purpose
APP_USER Yes Login username
APP_PASS Yes Login password
FLASK_SECRET Yes Flask session secret (any random string)
MISTRAL_API_KEY No Enables Mistral models. If omitted, those models return errors when called
GOOGLE_API_KEY No Enables Google Gemini models. If omitted, those models return errors when called
LANGCHAIN_API_KEY No Enables LangSmith tracing. If omitted, tracing is disabled
LANGCHAIN_PROJECT No LangSmith project name (defaults to llminsight)
PORT No Server port (defaults to 5000)
SSL_CERT_PATH / SSL_KEY_PATH No Paths to SSL certificate and key for HTTPS

Minimal .env (Ollama-only, no cloud APIs):

APP_USER=admin
APP_PASS=changeme
FLASK_SECRET=changeme

The app runs with just these three variables. Missing optional keys are noted at startup; models routed to a provider without a key return error responses, but the app itself continues to work normally.

Important: The default Layer 2 (prompt improver) model is open-mistral-nemo-2407, which requires MISTRAL_API_KEY. If you are running Ollama-only without a Mistral key, either disable the Change Prompt toggle in the UI or change DEFAULT_LAYER2_MODEL in config/settings.py to an Ollama model (e.g., gemma2:9b).

Pull Ollama Models

Pull the default models used by each layer (skip any you don't plan to use):

ollama pull gemma:7b-instruct-q4_K_M   # Layer 1A default
ollama pull granite4:latest              # Layer 1B default
ollama pull gemma2:9b                    # Layer 0 default
ollama pull phi3:mini                    # Layer 3 grader (accuracy)
ollama pull gemma2:2b                    # Layer 3 grader (clarity)
ollama pull qwen2.5:1.5b                # Layer 3 grader (conciseness, structure)
ollama pull llama3.2:3b                  # Layer 3 grader (creativity)

The full list of preconfigured models is in config/settings.py.

Run

Open http://localhost:5000 and sign in with the credentials from your .env file.


Disabling Providers You Don't Need

If you only want to use a subset of providers, leave the corresponding API key out of .env:

  • No Mistral: omit MISTRAL_API_KEY. Avoid selecting Mistral models in the UI and update DEFAULT_LAYER2_MODEL in config/settings.py to an Ollama or Gemini model.
  • No Google Gemini: omit GOOGLE_API_KEY. Avoid selecting Gemini models in the UI.
  • No LangSmith: omit LANGCHAIN_API_KEY. Tracing fails silently; the app works normally.
  • No GLM-4: remove glm-4-9b and glm-4-9b-chat from the model lists in config/settings.py. Optionally remove transformers and torch from requirements.txt to save disk space.
  • No Ollama: remove Ollama-only models from the model lists in config/settings.py, remove ollama from requirements.txt, and update the default model constants (DEFAULT_LAYER1A_MODEL, DEFAULT_LAYER1B_MODEL, DEFAULT_LAYER0_MODEL, LAYER3_GRADER_MODELS).

Adding Your Own Models

New Ollama model

  1. Pull it: ollama pull your-model-name
  2. Add the model name to the appropriate list(s) in config/settings.py
  3. It appears in the UI dropdowns immediately

New cloud API provider

  1. Add your API key to .env and load it in config/secrets.py
  2. Add a routing check and call function in ai/api_calls.py (follow the existing Gemini/Mistral pattern)
  3. Add the model names to the lists in config/settings.py

New grader model

Add the model name to AVAILABLE_GRADER_MODELS in config/settings.py. The model must be available via Ollama. It will appear in the grader model dropdown on the Config Graders page.

Changing defaults

Edit the DEFAULT_* constants in config/settings.py (DEFAULT_LAYER1A_MODEL, DEFAULT_LAYER1B_MODEL, DEFAULT_LAYER0_MODEL, DEFAULT_LAYER2_MODEL, LAYER3_GRADER_MODELS).


Running Tests

pip install -r requirements-dev.txt
pytest tests/ -v --tb=short

The contract tests validate backup schema, restore behavior, advanced model map compatibility, auth matrix, provider routing, and the full Preference Studio package (test_pref_*: store, extraction, active-learning queue, calibration, dataset pools/examples, export, routes, and wiring). Tests use monkeypatched temp directories and an isolated SQLite database — no production files are touched, no AI models are called, and no .env file is required.


Persistence and Backup

  • Session state: authentication, selected models, weights, toggles, prompt history, advanced model maps, and the active grader setting name are stored in the server-side session and a SQLite database.
  • Runtime files: data/ledger.jsonl (append-only event log), data/iteration_history.json, data/best_best_layer1.json, data/console_output.txt, and graderdata/ (JSONL grader settings).
  • Preference Studio (isolated): data/preferences.db (judgments, queue, blacklist, calibration runs) plus data/preferences_export/ and data/preferences_regrade/. These are never touched by the live session's clear/backup, and re-grading never writes to the ledger.
  • Browser storage: localStorage (domain filter, weight preset, system type) and sessionStorage (review-to-main handoff).
  • Lifecycle: startup, login, clear-chat, logout, exit, window close, and process signals each trigger backups of runtime files before clearing them.
  • JSON export (version 2.0): captures console output, prompt history, iteration history, best-best cache, ledger entries, and full session state. Restorable via upload or the Review page.

Observability

LangSmith/LangChain tracing is available on the orchestrating iterative loop and every individual AI layer (Layer 0, Layer 1, Layer 2, Layer 3) via @traceable decorators. Set LANGCHAIN_API_KEY in .env to enable it. If the key is missing or invalid, tracing is disabled and the app continues to function normally.


Project Structure

Path Purpose
main.py Application entry point
config/ settings.py (models, paths, default weights), secrets.py (credentials via .env)
core/ db.py (SQLite state), models.py (Pydantic schemas), state.py (hybrid state management)
data/ Runtime working files (ledger, cache, history, console output, state DB, and the isolated preferences.db + preferences_export/ / preferences_regrade/ dirs). Auto-created on first run; git-ignored except a .gitkeep placeholder
graderdata/ JSONL grader setting files
routes/ web_routes.py, api_routes.py, review_routes.py
preference/ Isolated Preference Studio package: store.py, extract.py, active_learning.py, calibrate.py, dataset.py, export.py, routes.py
ai/ iterative_loop.py, iteration_summary.py, layer0.py, layer1.py, layer2.py, layer3.py, api_calls.py
utils/ session.py, session_keys.py, file_io.py, common.py, text_processing.py, validation.py, grader_settings.py
scripts/ Developer utility scripts (check_syntax.py, check_modified.py, create_graderdata.py)
templates/ Jinja2 templates (login, main, review, config_graders, studio) with shared partials
static/ CSS, JavaScript, and assets (incl. js/studio/, js/arena/, js/dataset/, js/calibrate/)
tests/ Pytest contract tests (incl. test_pref_*.py)

Dependencies

Package Purpose
Flask Web framework, routing, sessions, template rendering
Pydantic Data validation for Layer 2 response schemas
ollama Python client for Ollama local inference
requests HTTP client for Mistral and Gemini REST APIs
python-dotenv Load .env into environment variables
transformers HuggingFace model loading for GLM-4 (optional)
torch PyTorch backend for GLM-4 inference (optional)
Chart.js + chartjs-plugin-datalabels Bar, radar, and per-category charts in the analysis modal (loaded from CDN)
langsmith Tracing and observability (optional)
pytest Test suite (dev dependency)

Further Documentation


Contributing

Contributions are welcome. If you'd like to help improve LLM InSights, please open an issue to discuss your idea before submitting a pull request. Bug reports, feature suggestions, and documentation improvements are all appreciated.


License

This project is released under the MIT License.