Metadata-Version: 2.5
Name: modelsure
Version: 0.1.0a1
Summary: Find out whether a cheaper or newer model is safe to switch to, tested on your own LLM traffic.
Project-URL: Homepage, https://modelsure.dev
Project-URL: Repository, https://github.com/modelsure/modelsure
Project-URL: Issues, https://github.com/modelsure/modelsure/issues
Project-URL: Changelog, https://github.com/modelsure/modelsure/blob/main/CHANGELOG.md
Author-email: ModelSure <hello@modelsure.dev>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: benchmark,evaluation,litellm,llm,model-migration,opentelemetry
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: click>=8.1
Requires-Dist: cryptography>=43
Requires-Dist: fastapi>=0.115
Requires-Dist: httpx>=0.27
Requires-Dist: opentelemetry-proto>=1.27
Requires-Dist: pydantic>=2.7
Requires-Dist: pyyaml>=6.0
Requires-Dist: sqlalchemy>=2.0
Requires-Dist: uvicorn>=0.30
Provides-Extra: gcs
Requires-Dist: google-cloud-storage>=2.16; extra == 'gcs'
Provides-Extra: otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.27; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.27; extra == 'otel'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.2; extra == 'postgres'
Provides-Extra: s3
Requires-Dist: boto3>=1.34; extra == 's3'
Description-Content-Type: text/markdown

# ModelSure engine

ModelSure tells you whether a cheaper or newer model is safe to switch to, using your own production traffic as the test. This folder is the Python package: it receives traffic, groups it into workloads, freezes benchmarks from it, runs candidate models against them and gives a plain answer: switch, don't switch, or not enough evidence yet.

> Status: early alpha (`0.1.0a1`). Licensed under Apache-2.0.

## Quick start

You need [uv](https://docs.astral.sh/uv/) and Python 3.11 or newer. From the repository root:

```bash
cd engine
uv sync --all-extras                      # the package, every extra and the development tools
uv run modelsure --help                   # every command, in one list
```

The commands below work as they are. The web app that `modelsure serve` and `modelsure demo` show is built separately, once, from the repository root: `pnpm install && node scripts/build-app.mjs` (the [root README](../README.md#quick-start) has the details).

Bring in past traffic. `modelsure import` takes a file, a folder, a glob (`'logs/*.jsonl.gz'`) or a bucket prefix (`s3://bucket/litellm/`, `gs://bucket/logs/`, with the `s3` or `gcs` extra), reads JSON, JSON Lines and CSV (gzipped or not) and works out the format itself. Formats: `native`, `openai`, `litellm` (bucket and `generic_api` logs), `litellm-spend-logs` (a `LiteLLM_SpendLogs` export), `bedrock` (model invocation logs), and in beta `azure-apim`, `vertex`, `langfuse` and `langsmith`; `--format` picks one. Importing the same file twice stores nothing new, and an import that keeps nothing testable exits with status 1 and says why:

```bash
uv run modelsure import traffic.jsonl
uv run modelsure workloads                # what it found, with volume and spend
uv run modelsure bench build <workload>   # freeze a benchmark from that workload's traffic
```

Tell ModelSure where to call models. Any OpenAI-compatible endpoint works, including a LiteLLM proxy. Put this in `modelsure.yaml` next to where you run the commands. There is no built-in default: with no endpoint configured, commands that call models stop and say what to add. The first endpoint listed is the default unless one is named `default`; a model listed under another endpoint's `models:` is called there.

```yaml
endpoints:
  - name: gateway
    base_url: http://localhost:4000/v1
    api_key_env: LITELLM_API_KEY          # the key is read from this environment variable
  - name: gpu
    base_url: http://gpu-box:8000/v1
    kind: vllm                            # your own servers: unpriced until you say what they cost
    models: [gemma4:31b]
    self_hosting: {gpu_usd_per_hour: 4.0, tokens_per_second: 2500}
budget:
  max_run_usd: 25                         # one comparison never spends more than this
```

A self-hosted model costs `gpu_usd_per_hour × 1,000,000 / (3,600 × tokens_per_second)` dollars per million tokens, the same for input and output. Without `self_hosting:` or a price under `prices:` its cost shows as unknown and it is never ranked as cheaper.

Then compare and act on the answer:

```bash
uv run modelsure run <workload> --model gpt-5-mini
uv run modelsure results                  # one line per model tested
uv run modelsure sign-off <workload> --model gpt-5-mini --by "Head of support" --note "Same answers"
uv run modelsure export --config litellm/config.yaml   # the config change, as a diff
```

`export` changes only the workloads whose answer is Switch: from recorded decisions when there are any, otherwise from the latest answers (and it says so). When two workloads share a model and only one passes, the shared entry stays and the passing workload gets its own entry.

To receive live traffic instead, create a key and start the server:

```bash
uv run modelsure keys create --name my-service
uv run modelsure serve                    # app and API on :4000, ingest on :4000 and :4318
```

Send requests to `/ingest/v1/requests` (the ModelSure SDKs do this for you), OpenTelemetry traces to `/ingest/v1/traces` (also answered at `/v1/traces` and `/otlp/v1/traces`, so an OTLP/HTTP exporter pointed at `http://localhost:4318` works unchanged; JSON or protobuf, gzip is fine), or LiteLLM logs to `/ingest/v1/litellm`. Every answer says what happened in its JSON body (`accepted`, `kept_in_full`, `skipped` with a reason for each; OpenTelemetry replies keep the OTLP body and put the counts under `"modelsure"`), and in `X-ModelSure-Accepted`, `X-ModelSure-Kept-In-Full`, `X-ModelSure-Skipped` and `X-ModelSure-Rejected` headers. ModelSure's own test calls carry an `x-modelsure-run` header, `"user": "modelsure-test"` and, through a LiteLLM proxy, the request tag `modelsure-test`; when a gateway's logs send them back they are dropped, counted as "ModelSure's own test call". When self-hosted, requests from the same machine need no key (`ingest.allow_keyless_localhost: false` turns this off); Cloud always needs one.

Only a small share of prompts and answers is kept (5%, at most 200 per workload per day), secrets and personal data are masked before anything is stored, and every request still counts towards volume and spend. Kept text is deleted after `ingest.retention_days`, counted from when ModelSure received the request, not from the time in the log, so imported history keeps its text for the full retention. Text of test cases in a workload's current benchmark is kept while that benchmark is current (except at retention 0), so it can be tested again. A request already received is skipped on import whatever file it comes from. Image, audio and video calls are counted but never kept in full; their workloads say "not supported yet". Workloads are named by `modelsure.workload`, LangChain and LangGraph runs (`traceloop.workflow.name` and the node), LiteLLM `metadata.workload` or tags, or otherwise by a fingerprint of the system prompt and tools; `workloads.group_by: ["tags.tenant_id"]` splits them further.

### What is masked

The same rules run in both SDKs and on the server (`src/modelsure/sdk/scrub.py` lists them; `sdk/test-vectors/scrub.json` proves they agree). The server writes numbered placeholders such as `<EMAIL_1>`, so a conversation still reads coherently.

| Category (`ingest.mask`) | Default | What is masked |
| --- | --- | --- |
| `secrets` | always | Private key blocks, JSON web tokens, `Bearer` tokens, `sk-…` provider keys, payment keys (`sk_live_…`, `rzp_live_…`, `whsec_…`), AWS access key ids, GitHub, Slack, Google API and Hugging Face tokens, ModelSure keys, the value in `password=…` / `"api_key": "…"` / `client_secret: …`, and one-time codes after "OTP" or "verification code" |
| `payment` | on | Card numbers that pass the Luhn check, CVV and expiry after their labels, bank account numbers after "account number", IBANs that pass their check, UPI ids, IFSC codes |
| `government_ids` | on | Aadhaar numbers that pass the Verhoeff check, PAN, US social security numbers written `123-45-6789` |
| `contact` | on | Email addresses; phone numbers with a `+` country code, Indian mobiles, US numbers with separators |
| `network` | off | IPv4 addresses |

Not masked: names, postal addresses, dates of birth, passport, driving licence and voter ids, other national ids, and anything the table does not describe. Add your own patterns under `ingest.mask_patterns` (for example `employee_id: "EMP-[0-9]{6}"`, written as `<EMPLOYEE_ID_1>`). The SDKs take the same categories: `modelsure.init(scrub_categories=["payment", "contact"])` in Python, `scrubCategories` in TypeScript.

`modelsure migrate` and `modelsure audit` answer the wider question of which models your code uses and when each is retired. Without `--input`, `migrate` uses the traffic already stored and the workloads' current benchmarks, and says so; any benchmark it builds is named with the one it replaces. For example `modelsure migrate --from gemma4:31b --input traffic.jsonl --only open-weight --host self_hosted --price qwen4-35b-a3b=0.1/0.4`, or `--to qwen4-35b-a3b@gpu` to name the endpoint. `modelsure audit --host azure` uses Azure's retirement dates.

The model feed (models, prices and retirement dates) is bundled and refreshed from `modelsure.dev` when the copy in use is over six hours old. `MODELSURE_FEED=off` makes no network call; `MODELSURE_FEED=https://…` uses a mirror. On a machine without internet, copy a signed `models.json` and `models.json.sig` across and run `modelsure feed import models.json` (it is used even with the feed off, when newer than the bundled copy), or set `MODELSURE_FEED=file:///path/to/models.json`; `modelsure feed status` shows which copy is in use. Prices belong to the host that bills a model: the feed's price for that host, `prices:`, or `self_hosting:`, never another host's. Through a LiteLLM proxy the model's provider prefix names the host (map plain names under the endpoint's `deployments:`); a closed model costs its maker's list price anywhere. Otherwise the cost is unknown, with what to add. A model too slow for a workload's speed limit is never recommended, planned, exported or signed off. `modelsure sources` lists where requests came from; `modelsure purge <workload>` and `modelsure org purge` delete data after asking.

## Settings

Defaults suit one machine. Change them in `modelsure.yaml` or with environment variables, and any nested setting as `MODELSURE_SECTION__KEY` (for example `MODELSURE_INGEST__BODY_SAMPLE_RATE=0.02`). The ones a deployment usually sets:

| Variable | Default | What it does |
| --- | --- | --- |
| `MODELSURE_DATA_DIR` | `~/.modelsure` | The only folder ModelSure writes to |
| `MODELSURE_DATABASE_URL` | SQLite in the data folder | `postgresql://user:pass@host/db?sslmode=require`, or for a Cloud SQL socket `postgresql://user:pass@/db?host=/cloudsql/<instance>` (needs the `postgres` extra) |
| `MODELSURE_BLOB_URL` | `blobs/` in the data folder | Where request text and benchmarks live: a folder, `s3://bucket/prefix` (the `s3` extra; `AWS_ENDPOINT_URL_S3` for S3-compatible stores) or `gs://bucket/prefix` (the `gcs` extra) |
| `MODELSURE_MODE` | `all` | What `modelsure serve` runs: `all`, `api`, `ingest` or `worker` |
| `MODELSURE_SERVER__HOST`, `__PORT`, `__INGEST_PORT` | `127.0.0.1`, `4000`, `4318` | Where to listen |
| `MODELSURE_INGEST__RETENTION_DAYS` | `30` | Days request text is kept after ModelSure receives it (1, 7, 14, 30, 60 or 90; 0 deletes it once a benchmark is built) |
| `MODELSURE_WORKER__SHUTDOWN_GRACE_S` | `8` | How long running jobs and requests get to finish on shutdown; an unfinished job goes back to the queue and starts again |

Extras: `postgres`, `s3`, `gcs` and `otel` (`uv sync --all-extras` installs them all; a deployment picks what it needs, for example `pip install 'modelsure[postgres,gcs]'`). Run `modelsure db upgrade` before starting a new version; it is safe to run repeatedly and from several places at once. Every server answers `GET /healthz`, and every mode stops cleanly on SIGTERM. See `src/modelsure/config.py` for the full list.

## Folder map

| Path | What it does |
| --- | --- |
| `src/modelsure/cli.py` | The `modelsure` command |
| `src/modelsure/config.py` | Settings: defaults, YAML, environment |
| `src/modelsure/store/` | Database tables, migrations, blob storage and every query |
| `src/modelsure/ingest/` | The ingest endpoints, wire formats, masking, sampling and workload grouping |
| `src/modelsure/importers/` | Importing traffic from files |
| `src/modelsure/providers/` | Calling OpenAI-compatible endpoints, and model prices |
| `src/modelsure/eval/` | The engine interface and the built-in `baseline` engine: benchmarks, checks, judging, statistics |
| `src/modelsure/worker/` | The job queue, testing budget and the worker loop |
| `src/modelsure/sdk/` | The Python SDK that sends traffic to ModelSure |
| `tests/fakes/` | A fake OpenAI-compatible server and synthetic traffic, for tests that never touch a real provider |

## Development

```bash
uv sync --all-extras
uv run ruff check . && uv run ruff format --check .
uv run mypy
uv run pytest
```

Tests run offline against the fake server in `tests/fakes/`; no provider keys are needed.

Engines and importers are plug-ins: [`docs/ARCHITECTURE.md`](../docs/ARCHITECTURE.md) shows how to add either, with examples that run.
