Repository navigation
Conversation
…alize API base URL handling
… `nadirclaw` project, which appears to be an API server built using FastAPI. The main focus of this code is to add a new endpoint `/v1/setup/webhook` that allows clients to update environment variables and fetch models from a provider (in this case, "ollama"). Here's a breakdown of the key components: ### 1. **SetupWebhookRequest Model** - This Pydantic model defines the structure of the request payload for the `/v1/setup/webhook` endpoint. - It includes two fields: - `env`: A dictionary where keys are environment variable names and values are their corresponding values. - `ollama_api_base`: A string representing the base URL for the Ollama API. ### 2. **_normalize_ollama_api_base Function** - This helper function ensures that the provided Ollama API base URL is properly formatted (e.g., adding a scheme if missing). - It takes an optional `base` parameter, which defaults to the value from the settings (`settings.OLLAMA_API_BASE`). ### 3. **_upsert_nadirclaw_env_var Function** - This function updates or inserts environment variables into a `.env` file located in the user's home directory under `.nadirclaw`. - It reads the existing content of the `.env` file, updates or appends the new key-value pair, and writes it back to the file. ### 4. **setup_webhook Endpoint** - This FastAPI endpoint handles POST requests to `/v1/setup/webhook`. - It processes the request payload, validates environment variables, normalizes the Ollama API base URL, updates environment variables both in memory and on disk, and optionally fetches models from the provider. - The response includes: - `status`: A string indicating the success of the operation. - `ollama_api_base`: The normalized Ollama API base URL. - `env_file`: The path to the `.env` file where environment variables are stored. - `updated`: A dictionary of updated environment variables. - `ignored`: A list of keys that were ignored because they are not recognized. - `models`: A list of models fetched from the provider (if requested). - `model_count`: The number of models fetched. ### 5. **Tests for setup_webhook Endpoint** - The tests use `pytest` and `unittest.mock` to verify the functionality of the `/v1/setup/webhook` endpoint. - They cover various scenarios, such as updating environment variables, fetching models, skipping model fetches, and handling unknown keys. ### 6. **Dependencies and Imports** - The code imports necessary modules from FastAPI, Pydantic, and other libraries to handle request validation, response building, and file operations. - It also imports settings and utility functions from the `nadirclaw` package. This endpoint is designed to be flexible and secure, allowing authorized users to update configuration settings dynamically while ensuring that only recognized environment variables are processed.
…o be a FastAPI-based web application with an admin interface for managing settings and configurations. The `render_admin_settings` function generates an HTML page for the admin settings UI. It takes two parameters: `result`, which contains the result of applying updates (if any), and `settings_obj`, which is an object containing the current settings. The function constructs an HTML string with various input fields for different configuration options, such as API base URLs, log directories, and other environment variables. It also includes a form submission button to save changes. The `admin_settings_page` route in the FastAPI app serves this admin settings page. If the user is not authenticated, it redirects them to the login page; otherwise, it renders the settings page with the current settings. The `admin_login`, `admin_logout`, and `admin_update_settings` routes handle user authentication, logout, and updating settings respectively. The `admin_login` route checks the provided password against a configured admin password and sets an authentication cookie if successful. The `admin_logout` route clears the authentication cookie. The `admin_update_settings` route processes form data submitted from the settings page, applies updates using the `_apply_setup_updates` function, and then renders the settings page again with the updated results. The tests in `test_server.py` verify various aspects of the admin UI functionality, including login behavior, session management, and updating settings.
…fidence threshold settings
6 tasks
7 tasks done
doramirdor
added a commit
that referenced
this pull request
May 29, 2026
#59) * feat(cascade): verifier-gated cascade + heuristic verifier + rule engine Ports the verifier-gated cascade architecture from Nadir Pro to the NadirClaw open-source core, plus the generic data-driven rule engine that sits in front of it. Cascade dispatch (nadirclaw/cascade.py): * Cheap-first dispatch with post-hoc verification. * Fail-open on verifier exceptions; kill switch after 3 consecutive errors so a misbehaving verifier never blocks request flow. * Default acceptance threshold tau=0.80, calibrated against the held-out RouterBench test split (n=11,420). At tau=0.80 the composed system preserves 98.3% of always-Opus quality with a 1.7% catastrophic-downgrade rate. Full tau-sweep documented inline. Heuristic verifier (nadirclaw/heuristic_verifier.py): * Rule-based, dependency-light (regex + stdlib only), ~1 ms / call. * Detects refusals, uncertainty, hard-min length, prompt/response ratio failures, and JSON parse failures. * Same scoring interface as the Nadir Pro DeBERTa verifier; ~0.60 AUROC vs ~0.96 for the trained version. Rule engine (nadirclaw/cascade_rules/): * Declarative YAML rules: substring / regex / prompt-length / classifier-confidence conditions, ORed inside `match.any_of`. * Four action types: force_escalate, force_cheap, set_threshold, set_max_tokens. Set-threshold rules stack (max wins); set_max_tokens rules stack (max wins, safer routing-side default). * TTL + mtime hot-reload cache so operators can edit a profile YAML on disk and see the new policy take effect without a restart. * PyYAML is optional (load_inline works without it); ships under a new `cascade-rules` extra in pyproject.toml. * Bundled `default.yaml` profile encodes the legacy force-escalate patterns and domain thresholds for code / summarisation — domains where post-hoc verifiers are known to be unreliable (AUROC 0.65 on mbpp, 0.77 on consensus_summary). Tests: 64 new test cases across rule parsing, priority ordering, applies_when gating, set_threshold stacking, set_max_tokens composition, malformed-rule rejection, hot-reload, and cascade integration. Existing 678-test suite remains green. * chore(verifier): contamination audit utility for benchmark reproducibility Adds `verifier/contamination_audit.py`, the standalone script that reproduces Nadir's "no held-out leakage" check across RouterBench and RouterArena. Given any benchmark prompt file(s) and any training-corpus file(s), the script: 1. NFC-normalises, strips, casefolds, and SHA-256s every prompt (same recipe used internally for the Nadir verifier corpus, so hashes are portable across the audit boundary). 2. Reports overlap count and up to N (default 50) overlap examples in a JSON report. 3. Exits 0 on zero overlap, 2 on any overlap, 1 on missing inputs -- so the audit can be wired straight into a CI gate. Stdlib-only (no third-party deps). Supports .jsonl, .json (list of objects or list of strings), and .txt. Per-file prompt key auto- detection (`prompt`, `input`, `question`, `query`, `text`) with `--prompt-key` override. The internal Nadir audit results that the public benchmark claims hang on: * RouterBench 0shot: 0 of 36,481 overlap (audit 2026-05-24) * RouterArena sub_10: 0 of 809 overlap (audit 2026-05-27) * RouterArena full: 0 of 8,399 overlap (audit 2026-05-27) Tests: 9 new test cases cover the hashing convention, the three supported file formats, the prompt-key override, the report shape, and the CLI exit codes. * docs: MODEL_CARD for wide_deep_asym_v3 + README benchmarks section MODEL_CARD.md documents the pre-generation classifier architecture that backs Nadir's RouterBench and RouterArena numbers: * Wide-and-deep asymmetric architecture, BGE embedding deep branch, lambda=3 downgrade penalty. * Training corpus, intended use, limitations, and the per-domain verifier AUROC variance that motivates the default cascade-rule profile (force-escalate on code / summarisation). * Held-out numbers: RouterBench AUROC 0.961, ECE 0.016, 98.3% quality preserved at tau=0.80; RouterArena sub_10 composite 0.7118 (projected #5 on the public leaderboard). * Contamination audit table (RouterBench 0/36,481; RouterArena sub_10 0/809; RouterArena full 0/8,399). * Explicit note that the trained `wide_deep_asym_v3.pt` artifact is proprietary to Nadir Pro; NadirClaw users get the same routing topology with the simpler binary centroid or DistilBERT classifier, and the same rule engine on top. README.md additions: * New "Benchmarks" section directly under "Why NadirClaw" with the held-out RouterBench, RouterArena, and contamination-audit numbers. Links to the live RouterArena submission PR (RouteWorks/RouterArena#112). * New "Verifier-gated cascade" and "Cascade rule engine" bullets in the Features section. * feat(classifier): bundle trained wide_deep_asym_v3 checkpoint + loader Ship the actual trained pre-generation classifier in the open-source package so NadirClaw users get the same Wide&Deep ternary classifier described in MODEL_CARD.md, not just the architecture description. Why bundle (Option A from the audit): - The asym + sym checkpoints together are ~1.8 MB. Adding them as package data is friction-free for users and avoids a HuggingFace download dependency or a training-recipe re-run on first use. - The MODEL_CARD already documented the architecture in detail; shipping the weights closes the loop so the documented benchmark numbers are reproducible from the package. - The MIT license already covers code in this repo; we relicense the weights under the same MIT terms (they were derived only from Nadir's internal labeled batches, which are ours to license). What ships: - nadirclaw/models/wide_deep_asym_v3.pt (905 KB, λ=3 asym CE loss) - nadirclaw/models/wide_deep_sym_v3.pt (905 KB, plain CE loss, recovers correct simple-class behaviour under argmax decoding) - nadirclaw/wide_deep_classifier.py — singleton-cached loader with argmax + cost-sensitive decoders, lazy BGE-base-en-v1.5 encoder, 33-d structural feature extractor. - nadirclaw/structural_features.py — 33-d feature extractor (length buckets, code fences, math symbols, tool calls, question words). Pure regex, no ML deps. - pyproject.toml — `models/*.pt` added to package-data so the checkpoints ship in the wheel. - tests/test_wide_deep_classifier.py — 10 integration tests that load the actual bundled weights, run a real forward pass, and assert the singleton + decoder hot-swap contract. MODEL_CARD updated to reflect that the weights now ship in NadirClaw (was previously documented as Pro-only). README "OSS vs Pro" table updated to mention the bundled trained classifier alongside the existing binary centroid and DistilBERT options. Usage: from nadirclaw.wide_deep_classifier import get_wide_deep_classifier clf = get_wide_deep_classifier( checkpoint_variant="asym", decision_rule="cost_sensitive", cost_lambda=20.0, ) result = clf.classify("Your prompt") print(result.tier, result.confidence) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(cascade-rules): multi-provider routing profile + reproducibility doc Cross-vendor cascades (Gemini-cheap + OpenAI/Anthropic-mid + Opus-class top + Llama fallback) expose failure modes that the default single-vendor profile does not model: refusal-style drift between vendors, chain-of-thought ability gaps on the cheap tier, structured- output wrapping inconsistency, and length-control drift on summarisation. These were the patterns we observed when expanding Nadir's RouterArena submission from a single-provider menu to a four- provider menu. Adds: - nadirclaw/cascade_rules/profiles/multi_provider.yaml — 12-rule profile encoding the cross-provider mitigations: force_escalate on CoT / math-proof / jailbreak / code triggers, set_threshold bumps on JSON / summarise / long-prompt patterns, force_cheap short-circuits for trivial greetings and acknowledgements. - docs/multi-provider-routing.md — learnings writeup plus a reproducibility recipe for running NadirClaw's classifier + rule engine over cached benchmark responses (e.g. RouterArena's ./cached_results/) without making any live API calls. Cross-links to the RouterArena PR. - tests/test_cascade_rule_engine.py — 4 new tests asserting the profile loads cleanly and triggers the expected actions on CoT, greeting, and structured-output prompts. Loaded with: from nadirclaw.cascade_rules import load_profile engine = load_profile("multi_provider") cascade = Cascade(cheap_call, expensive_call, rule_engine=engine) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Nadir Research <[email protected]> Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR Description
This PR improves the FastAPI router server with stronger reliability, better routing behavior, and runtime configuration support.
What changed
/v1/chat/completions.stream=true).auto)eco,premium,free,reasoning)POST /v1/classifyPOST /v1/classify/batchPOST /v1/setup/webhookto apply env updates and optionally fetch Ollama models/admin, login/logout, settings update)~/.nadirclaw/.envImpact