Metadata-Version: 2.4
Name: modelsaar
Version: 0.2.0
Summary: ModelSaar - intelligent routing for local AI models. One OpenAI-compatible endpoint that picks the most suitable local deployment per request.
Author-email: Gopala Subramanium <gopalasubramanium@gmail.com>
License: Apache-2.0
Project-URL: Homepage, https://modelsaar.com
Project-URL: Repository, https://github.com/gopalasubramanium/modelsaar
Project-URL: Creator, https://me.sgopala.com
Keywords: llm,router,gateway,ollama,openai-compatible,local-first
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: starlette<2,>=0.40
Requires-Dist: uvicorn<1,>=0.30
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic<3,>=2.6
Requires-Dist: pyyaml<7,>=6
Provides-Extra: ocr-layout
Requires-Dist: pillow>=10; extra == "ocr-layout"
Provides-Extra: dev
Requires-Dist: pillow>=10; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: anyio>=4; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: pip-audit>=2.7; extra == "dev"
Dynamic: license-file

# ModelSaar

**Status: public alpha** — pinned candidate commits; no stable release, no PyPI package or container image. The GitHub-only **release candidates** `v0.1.0-rc.1` and `v0.1.0-rc.2` (pre-releases for testing the opt-in decision-model features; rc.2 adds the `continuation` probe) are described below; see `docs/verification-report.md` for what has and has not been executed and `docs/roadmap.md` for scope.

[![ci](https://github.com/gopalasubramanium/modelsaar/actions/workflows/ci.yml/badge.svg)](https://github.com/gopalasubramanium/modelsaar/actions/workflows/ci.yml)

**Intelligent routing for local AI models.** One endpoint. Intelligent model selection.

ModelSaar is a small, local-first, OpenAI-compatible gateway. Your applications (Open WebUI,
OpenClaw, OpenCode, Hermes Agent, anything that speaks Chat Completions) connect once and ask for a
virtual model such as `auto`. ModelSaar inspects each request, keeps only the deployments that can
*actually* satisfy it (tools, images, strict JSON schemas, context size, locality, health, capacity),
ranks the rest on evidence, routes the request to the winner (the body passes through except documented
client-compatibility translations), and records a decision you can inspect.

```
client ──/v1/chat/completions (model: auto)──▶ ModelSaar ──▶ ollama/qwen3.8:27b
                                                  │            ollama/gemma4:e4b
                                                  │            vllm/...
                                                  └─ X-ModelSaar-Deployment, /admin/explain
```

Status: **0.1.0 — first release candidate.** Core routing, streaming, embeddings, probes, CLI,
client config generation, evaluation harness and a fault-injection test suite are implemented and
tested against controlled backends, and exercised live against a real Ollama server with eight models
(discovery, probes, routing, streaming, tool calls, evaluation). Read the
[verification report](docs/verification-report.md) before relying on any specific compatibility.

## Why

* **Connect once.** Clients keep their own agent loops, tools, memory and UI; ModelSaar only selects
  and forwards inference requests.
* **Never silently degrade.** No truncated history, dropped images, weakened schemas, stripped
  tools, or hidden cloud fallback. If nothing qualifies you get a structured error with blockers and
  remedies.
* **Evidence over marketing.** Capabilities are three-state (`supported | unsupported | unknown`)
  with provenance (runtime metadata, probe, operator). Quality estimates are labelled *measured*,
  *prior* or *uncalibrated*. Unknown required capabilities never qualify.
* **Local and private by default.** Loopback bind, generated keys, no prompt logging, cloud-forwarded
  models excluded unless you opt in, backends only reachable at their configured hosts.
* **Small.** Five runtime dependencies (Starlette, uvicorn, httpx, pydantic, PyYAML). No Docker,
  Envoy, Redis, Postgres, GPU toolkit or mandatory classifier model.

## Release 0.2.0

`v0.2.0` is the first stable version tag (the package remains alpha-classified; see the support matrix for
what is fixture-tested and what has run on real hardware). Ways to install it:

```bash
# 1. From the tag (always available)
git clone https://github.com/gopalasubramanium/modelsaar.git && cd modelsaar && git checkout v0.2.0
python3 -m venv .venv && . .venv/bin/activate && pip install .

# 2. From PyPI / as a container image — published by the release workflow for the tag; check that the
#    version exists before relying on it (https://pypi.org/project/modelsaar/, ghcr.io/gopalasubramanium/modelsaar)
pip install modelsaar==0.2.0
docker run -v modelsaar-data:/data -v ./config.yaml:/data/config.yaml:ro -p 127.0.0.1:8484:8484 ghcr.io/gopalasubramanium/modelsaar:v0.2.0
```

The one-line installer on modelsaar.com installs the commit it pins (shown on the site), in its own
environment, and upgrades or rolls back an existing installation ([installation](docs/installation.md)).

New in 0.2: `POST /v1/responses`, `POST /v1/messages` and the opt-in response store
([protocols](docs/protocols.md)); `POST /v1/guardrails`, `POST /v1/ocr`, `POST /v1/vote`, audio/video input,
multimodal embedding items ([pipelines](docs/pipelines.md)); exact token counts and served-context detection
per runtime ([routing](docs/routing.md)); `modelsaar lifecycle` ([lifecycle](docs/lifecycle.md)); cascades,
replica scheduling and `modelsaar learn` ([cascades and learning](docs/cascades-and-learning.md));
`modelsaar judge` ([evaluation](docs/evaluation.md)). All of it is additive or opt-in: a 0.1 configuration
runs unchanged. One table gives the evidence level of every item: [docs/roadmap-matrix.md](docs/roadmap-matrix.md).

## Release candidate: decision models (`v0.1.0-rc.2`; opt-in, experimental — not a stable release)

`POST /v1/decisions` (typed questions answered by a decision model such as Ollama's `nimble`, `clef` or
`laya` through its native `/v1/systemone` API) and the routing classifier's `mode: decision` were merged on
`main` at commit `6075cdcf3b0952d4213a7899438f5fe546e95d19` and are available as the GitHub pre-releases
**`v0.1.0-rc.2`** (https://github.com/gopalasubramanium/modelsaar/releases/tag/v0.1.0-rc.2 — rc.1 plus the
`continuation` capability probe, `modelsaar probe <id> --which continuation`, and a corrected `422` remedy)
and `v0.1.0-rc.1` (unchanged). They are fixture-tested in CI and were exercised once live with three
requests (`docs/live-runs/2026-10-28-decision-preview-smoke/`); nothing about answer quality or routing
benefit is claimed. The continuation probe establishes protocol acceptance of `reasoning_content` in the
assistant history, not semantic continuity; it was run live once from `v0.1.0-rc.2` against `ollama/qwen3.8:latest`
(Ollama 0.40.5) and reported `supported` (`docs/live-runs/2026-10-29-rc2-continuation-probe/`; one deployment,
no override, nothing about other models or a real client's follow-up turn). A candidate is GitHub-only: no PyPI package, no container image, and the package
version stays `0.1.0` (`docs/release.md`, "GitHub-only pre-releases"). The one-line installer still pins
an earlier commit and is unchanged — do not point it at the candidate, that would replace a stable
installation. To try the candidate side by side with a stable install, use the ordinary source install
at the tag with its own home:

```bash
git clone https://github.com/gopalasubramanium/modelsaar.git modelsaar-preview && cd modelsaar-preview
git checkout v0.1.0-rc.2
python3 -m venv .venv && . .venv/bin/activate && pip install -e .
export MODELSAAR_HOME=~/.modelsaar-preview        # separate config, keys and state
modelsaar init --port 8485                         # or --endpoint http://host:11434 --type ollama
modelsaar discover                                 # a decision model shows role "decision"
modelsaar serve
```

Contract and limits: `docs/routing.md` ("Decisions"); classifier configuration: `docs/extending.md`;
the web page with the tester instructions and the smoke-test record: https://modelsaar.com/preview/decision-models/.

## Quickest working setup

Prerequisites: Python 3.10+, and a running local inference server with at least one model
(Ollama is the first-class path; any OpenAI-compatible server works with declared models).

```bash
# 1. install from source (no PyPI package is published yet)
git clone https://github.com/gopalasubramanium/modelsaar.git && cd modelsaar
python3 -m venv .venv && . .venv/bin/activate      # or: uv venv && . .venv/bin/activate
pip install -e .                                   # or: uv pip install -e .

# 2. initialise: finds Ollama on 127.0.0.1:11434 (or pass --endpoint), writes config + keys, discovers models
modelsaar init

# 3. check and verify
modelsaar doctor            # reachability, context assumptions, unknown capabilities, cloud aliases
modelsaar probe --all       # live checks: streaming, tools, JSON schema, vision, continuation, latency (uses local compute)

# 4. run
modelsaar serve             # http://127.0.0.1:8484/v1 ; keys in ~/.modelsaar/keys/

# 5. first request (in another shell)
modelsaar test              # identifies the gateway (GET /healthz), GET /v1/models, one routed completion through `auto`
```

Example request:

```bash
curl -s http://127.0.0.1:8484/v1/chat/completions \
  -H "Authorization: Bearer $(head -1 ~/.modelsaar/keys/api_keys)" \
  -H "Content-Type: application/json" \
  -d '{"model":"auto","messages":[{"role":"user","content":"Write a Python function that parses ISO dates"}]}' \
  -D - | grep -i x-modelsaar      # X-ModelSaar-Deployment tells you what was selected
```

Then connect a client. One command per client (pick yours; these are separate commands, not a
pipeline): `modelsaar client-config open-webui`, `modelsaar client-config openclaw`,
`modelsaar client-config opencode` (or `opencode-v2`), `modelsaar client-config hermes`. Each prints
verified configuration; `--apply` merges file-based configs with a backup. For a GUI field that asks
for an API key, print the key in a terminal with `head -1 ~/.modelsaar/keys/api_keys` and paste the
value it prints (a line starting with `msk_`) — the `$(...)` form above is shell syntax, not a key. See
[docs/clients/](docs/clients/).

No models yet? `modelsaar demo` starts a clearly labelled **simulated** backend so you can try the
CLI, the status page and route explanations without downloading anything.

## Virtual models (aliases)

| alias | profile | notes |
|---|---|---|
| `auto` | quality | default: best expected quality within limits; effectively tied candidates resolve to the lower-overhead one |
| `auto-quality` | quality | same as `auto` |
| `auto-balanced` | balanced | more weight on latency and residency |
| `auto-fast` | fast | prefer resident, low-latency deployments |
| `auto-code` | quality | only deployments tagged `code` |
| `auto-vision` | quality | only deployments with verified image input |

Aliases are advertised in `GET /v1/models` **only** when at least one usable deployment backs them,
with a truthful contract (`context_length_min`, tools/vision/json_schema = supported/partial/unsupported).
Any concrete deployment id (e.g. `ollama/qwen3.8:27b`) can be requested directly; it still passes
the same hard checks.

## How a route is chosen

1. **Requirements** – structural analysis of the whole request: roles, images/audio, tools and
   `tool_choice`, `response_format`, outstanding tool-call ids, `reasoning_content`, conservative
   token accounting (input + output allowance + reasoning budget for thinking models).
2. **Hard filters** – role, health, locality policy, capability tri-state, effective context,
   backend field support, admission feasibility. A score can never override a failed filter.
3. **Classification** – deterministic multi-label task signals; an *optional* local classifier is
   consulted only for ambiguous cases, under a strict contract with timeout and fallback — either a
   small chat model answering JSON or, with `routing.classifier.mode: decision`, a decision model
   (Ollama `/v1/systemone`: nimble, clef, laya) answering one choice question with probabilities.
4. **Ranking** – transparent score per profile: evidence-based quality (measured > prior >
   uncalibrated, with uncertainty) minus latency, residency/load and overhead costs, plus a
   switching penalty for session affinity.
5. **Decision record** – request id, config hash, inferred task, requirements, exclusions with
   reasons, candidate breakdown, chosen deployment, evidence level, overhead. No prompt content.

Inspect: `modelsaar explain -m "..." [--tools --image --json-schema]`, `modelsaar decisions`,
`GET /admin/decisions/<id>`, or the status page at `/admin/ui`. Details: [docs/routing.md](docs/routing.md).

## Tested support matrix

Legend: **F** fixture-tested over real HTTP with a controlled fake backend (CI); **L** executed live
against real models (owner's GX10 via Tailscale, 2026-10-11); **D** documented from primary sources
(config keys verified 2026-10-11); **NOT RUN** needs your hardware/client.

| area | status |
|---|---|
| `GET /v1/models`, `POST /v1/chat/completions` (non-stream + SSE), `POST /v1/embeddings`, `/healthz`, `/readyz` | F |
| `POST /v1/decisions` — typed questions answered by a decision model (Ollama `/v1/systemone`); contract in `docs/routing.md` | F (fixture), **NOT RUN** against a live decision model |
| Ollama adapter: `/api/tags`, `/api/show`, `/api/ps`, `/api/version`, OpenAI-compat forwarding, cloud-alias detection | F + **L** (Ollama 0.32.13 on an ASUS GX10, 8 models, 2026-10-11) |
| Generic OpenAI-compatible adapter (`/models`, `/chat/completions`, `/embeddings`, vLLM `/tokenize`) | F (fixture), **NOT RUN** against vLLM/llama.cpp |
| Tool round trips, streaming tool deltas, strict schema routing, image routing | F |
| Failover before commitment / termination after commitment | F |
| Admission limits, queue rejection, uncertain occupancy on disconnect | F |
| Probes, fingerprint invalidation (endpoint + identity), embedding contracts (verified identity, output validation), local-only policy | F |
| Privacy before payload operations (no `/tokenize`/classifier traffic to policy-excluded deployments), continuity (no failover inside tool round trips / pinned sessions), timeout holds, pool memory budgets, probes under gateway admission | F (`tests/test_hardening_2026_10_11.py`) |
| Open WebUI / OpenClaw / OpenCode V1+V2 / Hermes configuration | D; live tool round trip **NOT RUN** |
| Several real deployments routed by `auto` (chat → qwen3.6, code/tools → qwen3-coder, vision → qwen3.6, agent → gemma4) | **L** — see [docs/verification-report.md](docs/verification-report.md) |
| Live evaluation vs fixed/rules/random/oracle baselines (3-deployment subset) | **L** (2026-10-11, pre-hardening evaluator: auto 0.875 vs fixed-strong 0.906, overlapping CIs, 0 capability violations — historical; a rerun with the repaired evaluator is recorded in docs/verification-report.md when complete) |
| `POST /v1/responses` (stateless subset) and `POST /v1/messages` (Anthropic Messages), fail-closed translations onto the chat path — `docs/protocols.md` | F; **S**: official `openai` and `anthropic` Python SDKs against the installed `modelsaar serve` with simulated models (`scripts/protocol_sdk_check.py`); real model / agent client **NOT RUN** |
| Stateful Responses via the opt-in local response store; `POST /v1/vote` and guardrail ensembles (closed choices); optional OCR layout stage; inline video input; replica scheduling across hosts — `docs/protocols.md`, `docs/pipelines.md`, `docs/cascades-and-learning.md` | F; nothing run on real models, a real layout service or two real hosts |
| `POST /v1/guardrails`, `POST /v1/ocr`, audio input (`audio_in` probe), multimodal embedding items — `docs/pipelines.md` | F (scripted fixture models); real Granite Guardian / GLM-OCR / audio / multimodal-embedding model **NOT RUN**; multimodal embeddings through Ollama are refused (its embed API is text-only) |
| Exact chat-template token counts and served context for vLLM / llama.cpp; Ollama served-context options — `docs/routing.md` | F (fixture servers emulating the documented endpoints); real vLLM / llama.cpp **NOT RUN** |
| Managed lifecycle (opt-in), llama-swap composition — `docs/lifecycle.md` | F; real Ollama / llama-swap **NOT RUN** |
| Cascades, adaptive learning (both opt-in) — `docs/cascades-and-learning.md`; LLM judge (separate report) — `docs/evaluation.md` | F; no benefit claim on real traffic |

## Limitations (0.1)

* Served context length for Ollama models is **assumed 4096** unless the Modelfile sets `num_ctx`,
  the model is currently loaded (`/api/ps`), or you add an override; `doctor` warns about it.
* Token counts are conservative estimates (chars/3 for Latin text, one token per CJK/other wide character, plus overheads); when a backend exposes `/tokenize` (vLLM) the gateway asks it for text counts only in borderline cases (estimate within ±50 % of a deployment's context), only for deployments that already passed every policy filter, and still adds estimated template/image overhead.
* Pool `memory_gb` budgets use weights-only estimates plus a margin; they prevent clearly oversized dispatches, not every OOM.
* Ollama's OpenAI layer does not support `tool_choice=required/named`, remote image URLs,
  `logit_bias`, `n`, `logprobs`; such requests are rejected with blockers rather than altered.
* The 0.2 candidate adds Responses/Messages translations, guardrail and OCR pipelines, audio input,
  multimodal embedding items, video input on the vLLM-documented form, an optional OCR layout stage,
  an opt-in response store for stateful Responses, managed lifecycle, cascades, closed-choice ensembles,
  replica scheduling and opt-in learning — all **fixture-tested only** so far (see the matrix above and
  [docs/roadmap-matrix.md](docs/roadmap-matrix.md)). Out of scope: hosted tools, the Conversations API,
  running a layout model in the gateway, free-text ensembles, a cluster scheduler, automatic model eviction
  or downloads; multimodal embeddings and video through Ollama are blocked by Ollama's own API.
* The evaluation harness executes model-written code only under bubblewrap / `sandbox-exec` / Docker; without one of those, code tasks are skipped (reported), never run on the host.
* Quality priors from the catalogue are hypotheses; run `modelsaar eval --mode live --save-measurements`
  to replace them with measurements on your hardware.

## Documentation

* [Installation](docs/installation.md) · [Troubleshooting](docs/troubleshooting.md) · [Privacy & security](docs/privacy.md)
* [Architecture](docs/architecture.md) · [Routing](docs/routing.md) · [ADR-001 build vs adapt](docs/decisions/ADR-001-build-vs-adapt.md)
* [Model catalogue evidence](docs/catalogue.md) · [Adding a deployment or adapter](docs/extending.md)
* Client guides: [Open WebUI](docs/clients/open-webui.md) · [OpenClaw](docs/clients/openclaw.md) · [OpenCode](docs/clients/opencode.md) · [Hermes Agent](docs/clients/hermes.md) · [SDKs and Responses/Messages clients](docs/clients/sdk-protocols.md)
* [Protocols](docs/protocols.md) · [Pipelines](docs/pipelines.md) · [Lifecycle](docs/lifecycle.md) · [Cascades and learning](docs/cascades-and-learning.md) · [Acceptance and roadmap matrix](docs/roadmap-matrix.md)
* [Evaluation](docs/evaluation.md) · [Verification report](docs/verification-report.md) · [Release process](docs/release.md) · [Roadmap](docs/roadmap.md)
* [Progress & decision log](docs/progress.md)

## Creator

Created by [Gopala Subramanium](https://me.sgopala.com). An independent open-source project.
[Say thanks](https://modelsaar.com/thanks/) if ModelSaar has been useful to you.

## Licence

Apache-2.0 for the gateway code (see `LICENSE`, `NOTICE`). Model weights are licensed by their
publishers; ModelSaar neither bundles weights nor accepts any model terms on your behalf.
