Switch AI models without breaking your product: find model calls, turn real usage into tests, compare models, fix prompts and watch for drift.
pip install llmshift==0.1.0 Copy PIP instructions
Providers now retire models roughly every six months. When a model's behaviour changes, outputs can look fine and still be wrong, and nothing raises an error. LLMShift is built around the moment of switching models, from finding the calls to proving the new model works:
AI coding assistants can use all of this as tools: llmshift mcp is an MCP server for Claude Code, Cursor and VS Code.
LLMShift is a single pure-Python package with no compiled code: its only dependency is tomli on Python 3.9 and 3.10 (to read pyproject.toml), and a copy of PyYAML's pure-Python YAML parser is included. It talks to OpenAI, Azure OpenAI, Anthropic, Gemini and any OpenAI-compatible endpoint over plain HTTPS, so there are no SDK version conflicts. You can also run it as a GitHub Action.
pip install llmshift llmshift demo # 1-minute offline walkthrough with simulated models (no API key) It runs on Python 3.9 to 3.15 on Linux, macOS and Windows, and installs without a compiler on any of them.
# 1. Which models does the code use, and when do they retire? llmshift scan # 2. Turn real traffic into tests (OpenAI/Anthropic/Gemini logs, LangSmith/Langfuse exports, CSV, ...) llmshift snapshot logs/ --model "gpt-4o*" --since 2026-09-01 # 3. What changes on the new model? Or: which cheaper model would do? export OPENAI_API_KEY=... llmshift compare --to openai:gpt-5.6-sol llmshift pick --models openai:gpt-6-luna,anthropic:claude-haiku-5-5 --volume 100k # 4. Get prompt changes that close the gaps, then open the upgrade pull request llmshift fix --to openai:gpt-5.6-sol llmshift upgrade --from gpt-4o-2024-05-13 --apply --compare --pr # 5. After switching, watch the live model every night llmshift watch --model openai:gpt-5.6-sol --alert slack:$SLACK_WEBHOOK_URL llmshift init --github writes a llmshift.yaml and two workflows: PR checks and a nightly watch. More workflows are in examples/workflows/.
$ llmshift scan LLMShift scan 5 files, 6 model references, 4 distinct models (lifecycle data: 2026-10-21) ✗ RETIRED claude-3-5-haiku-20241022 anthropic retired on 2026-02-19; replacement: claude-haiku-4-5-20251001 app/summaries.py:10 model="claude-3-5-haiku-20241022", ! 2 DAYS LEFT gpt-4o-2024-05-13 openai retires 2026-10-23 (2 days left); replacement: gpt-5.6-sol app/triage.py:7 TRIAGE_MODEL = "gpt-4o-2024-05-13" app/triage.py:17 model=TRIAGE_MODEL, (via TRIAGE_MODEL, line 7) app/replies.py:15 model=os.getenv("REPLY_MODEL", "gpt-4o-2024-05-13"), Python is analysed with the AST. It finds model=-style arguments and models passed to known constructors (GenerativeModel, init_chat_model, pydantic-ai Agent, LiteLLM, ...). It also handles {"model": ...} dicts, constants used elsewhere (MODEL = "..." then model=MODEL) and os.getenv("X", "default") fallbacks. Docstrings and comments are ignored. Other code (JS/TS, Go, Java, Kotlin, C#, Ruby, PHP, Rust, Swift, ...): string literals that are model IDs, and values of model-like keys. Config: YAML, JSON, TOML, .env, INI, Terraform and Dockerfiles. Notebooks: code cells, reported with cell numbers. ID formats are normalised. Bedrock (us.anthropic.claude-...-v1:0, full ARNs), Vertex (claude-...@20241022, projects/.../models/...), OpenRouter/LiteLLM prefixes (openai/gpt-4o), dotted spellings (claude-3.5-sonnet) and fine-tunes (ft:gpt-4o-mini-..., which follow their base model's schedule) all map to their base model. In a git repository, files git ignores are skipped unless you name them, and so is LLMShift's own .llmshift/ folder. --exclude takes globs: a bare name (legacy) matches at any depth, and paths may be relative to the scanned directory or the current one. Lifecycle data covers 617 models from OpenAI, Anthropic, Google (Gemini API and Vertex AI), Mistral, Cohere, xAI and DeepSeek. It was built from the providers' official deprecation pages on 2026-10-21. Status is computed from dates at run time, so a model turns "retired" on its shutdown day. llmshift update downloads newer data (below); add or override entries with --registry extra.json; llmshift models gpt-4o searches the data. In CI, use --fail-on retired|retiring|deprecated|unknown|never (default retired). Output formats: --format table|json|markdown|sarif. Inside GitHub Actions, findings appear as annotations on the diff and in the job summary. snapshot: real usage logs become a test set llmshift snapshot logs/ -o .llmshift/tests.jsonl snapshot reads JSONL, JSON and CSV files (optionally .gz) and detects the format of each record:
Embedding, moderation, image and audio calls are skipped, and every skipped record is counted with its reason. --append adds only cases that are not already in the test file. Logs of any size are read as a stream: beyond --max-records calls (default 100,000) a fair sample is kept for every prompt template.
Logs without outputs? Pass --baseline-model openai:gpt-4o-2024-08-06 to generate them.
No logs yet? Record them from your app with one line:
from llmshift.record import wrap client = wrap(OpenAI(), path="logs/llm.jsonl") # works with OpenAI, AsyncOpenAI, Anthropic, AsyncAnthropic, streaming Streamed responses, including the SDKs' stream helpers (with client.messages.stream(...), client.chat.completions.stream(...)), are logged whole once the stream ends, with tool calls and token usage. Pydantic response formats (parse(response_format=Model) and friends) are logged as the JSON schema the SDK sends, so the cases replay with the same structured output. Several threads or processes can log to the same file.
The test file is plain JSON Lines that you can read, edit and commit:
{"id": "c_bc05e87da4", "group": "acme-customer-support-assistant-8a772a", "input": {"messages": [{"role": "system", "content": "You are Acme's customer support assistant..."}, {"role": "user", "content": "Hi, my order #4521 hasn't arrived yet..."}], "params": {"temperature": 0.3}}, "baseline": {"output": "Thank you for contacting Acme support. ...", "model": "gpt-4o-2024-05-13"}, "checks": [{"type": "facts", "facts": [{"kind": "id", "text": "#4521"}, {"kind": "date", "text": "March 14", "value": "--03-14"}]}, {"type": "tone"}, {"type": "length", "min_words": 15, "max_words": 95, "baseline_words": 40}]} You can also write cases by hand in YAML (prompt:, system:, baseline:, checks:).
Run each task inside agent_run so its model calls and tool results are recorded as one run:
from llmshift.record import agent_run, wrap client = wrap(OpenAI(), path="logs/agent.jsonl") with agent_run("refund-flow"): run_my_agent(client, task) Logs without run ids are linked too, when each request continues the previous one with its tool results. snapshot turns each run into one test case. compare replays it on the new model: the model starts from the run's first request, and whenever it calls a tool it gets the result recorded for that call. Both models see the same world and no real tool runs. The agent check reports missing, extra or changed tool calls, tools called in a different order, loops (the same call 3 or more times, more often than recorded) and runs that hit the step limit; the usual checks compare the final answer. Reports show both step traces and the cost per task (here with simulated models):
✗ FAIL c_ef9ea0976f acme-support-agent-look-dfa329-agent Input: What is happening with order #9001? Steps (old): lookup_order(order_id=9001) → answer Steps (new): lookup_order(order_id=9001) → lookup_order(order_id=9001) → lookup_order(order_… ✗ tools looped: called lookup_order(order_id=9001) 6 times; stopped after 6 steps w… Notes • Agent tasks (3): 2 -> 4 steps on average; cost per task $0.00035 -> $0.00062 (+76%); 1 task(s) looped; 1 ran out of steps. A call that was never recorded gets the recorded result of the same tool with other arguments if there is one, else a placeholder saying nothing was recorded; the report counts these. The step limit is twice the recorded steps plus two (at least 6); set "max_steps" in a case's agent object to change it.
$ llmshift compare --to openai:gpt-5.6-sol ✓ 0 unchanged ! 6 changed ✗ 12 failed pass rate ███████░░░░░░░░░░░░░ 33.3% ✗ below the 95% threshold 95% range 10.9%-56.2% over 18 cases What changed Broken format 8 failed JSON is wrapped in a markdown code fence (8) Wrong or missing facts 6 failed, 6 changed facts missing (6), e.g. no mention of "Acme" numbers changed (4), e.g. "12.5%" -> "12%"; "$4.2 million" -> "$4 million"; "3.1%" -> "3%" $.urgency changed (2), e.g. $.urgency: "medium" -> "high" Different tone / style 6 changed adds emoji (6) · more exclamatory (6) · more casual (6) · less polite (6) ✗ FAIL c_0d9f963af7 support-ticket-triage-assistant-f98626 Input: The tracking link for order #8812 doesn't work. ✗ format JSON is wrapped in a markdown code fence (```json ... ```) Old: {"category": "shipping", "urgency": "low", "summary": "The tracking link for order #8812 doesn't work."} New: ```json { "category": "shipping", ... } ``` Each case is failed (an error-level check broke: format, facts, tool calls, refusal, language) or changed (a warning-level difference: tone, length, structure, similarity). Change a check's level with --severity tone=error. --baseline-model also runs the old model live. A check that the old model fails as well is counted as noise, not a regression, and the two models are compared case by case (McNemar), so "worse" means significantly worse. --judge openai:gpt-5.6-terra adds an LLM equivalence judge to free-text answers (JSON, labels and numbers are already checked exactly), and grades imported model graders. judge: in llmshift.yaml does the same for every run. Reports: a self-contained HTML report with filters and word-level diffs, plus JSON, in .llmshift/reports/. Add --markdown summary.md for PR comments and --junit junit.xml for CI test views; without a file name they are written to .llmshift/reports/ too. llmshift report results.json --html re-renders a saved run. Model quirks are handled automatically and listed in the report: parameters a model rejects (temperature, max_tokens vs max_completion_tokens, Claude's deprecated sampling parameters), Responses-only models, and the developer role. You'll also see notes such as "reasoning models count thinking tokens toward the output limit". Responses are cached in .llmshift/cache, so re-runs are free. Turn this off with --no-cache. Confidence: ranges, repeated runs and a calibrated judge Every pass rate comes with a 95% range, so 18 test cases don't pass for proof. When the range is wide, the report says how many cases would pin the rate down to ±5 points. --repeat N runs each case N times (each run cached separately). A case's result is its most common outcome, the worse one on a tie, and cases that pass in some runs but not others are marked flaky in every report, so one unlucky sample doesn't decide a switch. The pass rate becomes the share of passing runs. The judge is asked only when the rules can't decide. With --judge, cases that already failed a rule-based check, and answers identical or near-identical to the old one (ROUGE-L ≥ 0.9), are settled without a judge call. The report counts the calls saved; --judge-mode always asks every time. Check the judge against yourself. llmshift judge label walks you through about 20 old/new answer pairs from the last compare run and saves each answer at once. llmshift judge calibrate asks the judge about the same pairs and reports how often it agrees with you (with Cohen's kappa), and whether it errs on the lenient or the strict side. Every later compare with that judge quotes the agreement. pick: the cheapest model that still passes llmshift pick --models openai:gpt-6-luna,anthropic:claude-haiku-5-5,gemini:gemini-3.8-flash --volume 100k pick runs your real-traffic tests on several candidate models at once, with the same checks as compare, and recommends the cheapest one that keeps quality. From the offline demo:
LLMShift pick 18 test case(s), 2 candidate(s), quality bar 95% Today: mock:legacy $1.43 per 1,000 requests Model Pass rate 95% range Cost / 1k req vs today p50 latency ─ ──────────── ──────────── ───────── ───────────── ──────── ─────────── ✓ mock:frugal 100% (18/18) 82%-100% $0.028 -98% 0 ms ✗ mock:nextgen 33% (6/18) 11%-56% $0.37 -74% 0 ms Switch to mock:frugal: same quality (all 18 cases unchanged), 98% cheaper - about $141 a month saved at 100,000 requests a month. Costs come from the token usage each provider reports (estimated from the text when it reports none, marked ~). Prices come from a bundled snapshot of LiteLLM's price list (llmshift update --prices refreshes it); set your own in USD per 1M tokens with --price azure:prod=2.5/10 or under pricing: in llmshift.yaml. Today's cost uses the usage recorded with your baseline answers and the price of --baseline (default: baseline in llmshift.yaml, else the recorded model). The quality bar is --min-pass-rate (default min_pass_rate, 0.95). If nothing passes, pick names the closest candidate and what broke; llmshift fix --to can often close the gap. --format json|markdown, --json [FILE], --markdown [FILE]. Inside GitHub Actions the result goes to the job summary and the action's recommended output. Exit code 0 when a model is recommended, 1 when none passes. safety: is the new model riskier? llmshift safety --to openai:gpt-5.6-sol --baseline-model openai:gpt-4o-2024-08-06 Both models get the same probes, built from your own test cases:
Category Probes Old New Change p Verdict ──────────────── ────── ─── ──── ──────── ────── ─────── Refusals 28 0% 36% +36 pts <0.001 RISKIER Prompt injection 20 0% 100% +100 pts <0.001 RISKIER PII leakage 20 0% 100% +100 pts <0.001 RISKIER A category counts as riskier only when it is more than --max-increase worse (default 5 points) and the paired difference is significant (McNemar). The exit code is then 1, so CI can block the switch. Use --probes N per category (default 20), --categories injection,pii, and --format json|markdown (also --json / --markdown files).
llmshift embeddings --from openai:text-embedding-3-small --to openai:text-embedding-3-large --corpus docs/ --queries-from logs/ Your documents (.txt .md .rst .html .json .jsonl) are chunked and a sample is embedded with both models. For each real query (from --queries FILE, or from the embedding requests in your logs) the top-k results are compared: how many survive, whether the old top result is still found, and rank-biased overlap. You also get the cost and time of re-embedding the whole corpus with the new model, and a warning when the vector size changes (the index schema must change). Exits 1 when fewer than --min-overlap (default 60%) of results are kept.
$ llmshift fix --to openai:gpt-5.6-sol support-ticket-triage-assistant-f98626 (prompt at app/triage.py:10) before: 0 of 7 match (7 failing) after: 5 of 7 match (2 failing) via rules Add to the system prompt: + Return only the raw JSON object. Do not wrap it in markdown code fences (```) and do not add any text before or after it. + For "urgency", use exactly one of: low, medium, high. still different: facts: $.urgency: "medium" -> "high" Overall pass rate: 33% → 89% with the suggested prompts For each prompt template with regressions, LLMShift builds candidate prompts and tests each one on the new model, keeping the best. The candidates come from:
Your code is never changed. You get the new prompt, a diff, and where the prompt lives in your repository. --write-tests fixed.jsonl writes a patched test set so you can re-check it with compare.
llmshift upgrade --from gpt-4o-2024-05-13 # dry run: shows the diff llmshift upgrade --auto --apply --compare --pr # every retiring model with a replacement LLMShift upgrade gpt-4o-2024-05-13 -> gpt-5.6-sol (retiring on 2026-10-23): 2 place(s) note: app/replies.py:16: gpt-5.6-sol may only accept the default temperature; check the temperature setting note: app/triage.py:18: gpt-5.6-sol may only accept the default temperature; check the temperature setting --- a/app/triage.py +++ b/app/triage.py @@ -4,7 +4,7 @@ from openai import OpenAI client = OpenAI() -TRIAGE_MODEL = "gpt-4o-2024-05-13" +TRIAGE_MODEL = "gpt-5.6-sol" TRIAGE_PROMPT = ( "You are a support ticket triage assistant for Acme. Classify the customer's message and return JSON with the keys " ... Dry run: nothing was changed. Re-run with --apply to write these edits, or --pr to open a pull request. upgrade swaps the model id exactly where scan found it. It handles constants, os.getenv defaults, configs and notebooks, and keeps provider prefixes such as openai/. For OpenAI's o-series and GPT-5+ it renames max_tokens to max_completion_tokens in the calls that use the swapped model. It flags settings to check by hand, such as temperature and fine-tuned or Bedrock ids. Everything else in each file stays byte-for-byte the same (encoding, BOM, line endings). --fix appends llmshift fix suggestions to prompts written as plain literals. --compare tests the replacement on your recorded traffic. --pr pushes a llmshift/upgrade-... branch and opens, or updates, a pull request with the diff and results. See examples/workflows/llmshift-upgrade.yml for a weekly run. In GitHub Actions, turn on Settings > Actions > General > "Allow GitHub Actions to create and approve pull requests" once (new repositories have it off); checks on the pull request it opens then wait for your approval unless you pass a personal access token.
llmshift check # in CI: runs only the tests for prompts this change edits llmshift check --model openai:gpt-5.6-sol --base origin/main --markdown LLMShift check model openai:gpt-5.6-sol base origin/main ✗ support-ticket-triage-assistant-f98626 app/triage.py 8 case(s) pass rate 75% (below 95%) facts: $.urgency changed (2) check looks up each test group's recorded system prompt in the files the change touches: Python strings (including implicit concatenation and f-strings), string literals in other languages, YAML/JSON values and prompt files (.txt, .md, .prompt, .j2). When the base version held the prompt and the change edits it, that group's tests run with the edited text on the model in production (baseline in llmshift.yaml). The result shows whether the model still answers the way it did before the edit. It also notices prompts that moved or were removed. In a pull request it posts one comment and updates it on every push. Check out with fetch-depth: 0 so the base branch is available. See examples/workflows/llmshift-check.yml.
llmshift shadow report checks the shadow answers against the real ones with the same checks as compare (exit 1 below min_pass_rate; --html for the full report). For more control, pass a llmshift.shadow.Shadow("openai:gpt-5.6-sol", rate=0.05, max_workers=2, max_pending=100); its flush() waits for the copies in flight, which helps in short scripts.
llmshift watch --model openai:gpt-5.6-sol --alert slack:$SLACK_WEBHOOK_URL --alert github llmshift watch --model openai:gpt-5.6-sol --at 02:00 # keep running, once a day Each run calls the live model (no cache) and appends to .llmshift/watch/ /history.jsonl. It alerts on:
When the test set changes, the next run becomes the new reference. Destinations: slack: , teams: , discord: , webhook: , github (opens or updates an issue), email: (SMTP) and file: . slack, teams and discord alone read the URL from SLACK_WEBHOOK_URL, TEAMS_WEBHOOK_URL or DISCORD_WEBHOOK_URL. --alert-on sets the lowest severity that is sent (default warning). The exit code is 1 when drift reaches --fail-on (default warning), so a scheduled CI job turns red.
OpenAI's hosted Evals become read-only on 2026-10-31, and the dashboard and API shut down on 2026-11-30. OpenAI provides no export feature, so the API is the way out:
export OPENAI_API_KEY=... llmshift import openai-evals --api --all --split .llmshift/evals/ llmshift compare --tests .llmshift/evals/ --to openai:gpt-5.6-sol --judge openai:gpt-5.6-terra For each eval, LLMShift reads the testing criteria, the latest run's data source, and the run's output items. Those hold the exact inputs sent and the outputs the model gave, which become recorded baselines. Graders map one-to-one: string_check (eq/ne/like/ilike) → equals / not_equals / contains text_similarity → similarity, with the same metric and threshold label_model → llm_label and score_model → llm_score, graded by --judge or the grader's own model python → python, which runs locally only with --allow-python multi → multi After import, a fidelity check re-grades the recorded outputs and reports how often the converted graders reproduce OpenAI's recorded verdicts. import does not replace an existing test file unless you pass --force (or choose another file with -o). You are warned when grader models are themselves retiring (o3-mini, o4-mini, gpt-4.1-nano and others shut down on 2026-10-23). Also supported: exported eval JSON (llmshift import openai-evals eval.json --data items.jsonl) and the open-source openai/evals registry (llmshift import openai-evals path/to/evals/registry). The registry covers Match, Includes, FuzzyMatch, JsonMatch and ModelBasedClassify (fact, closedqa, custom specs). Use it from AI coding assistants (MCP) llmshift mcp runs a Model Context Protocol server, so an AI coding assistant can migrate a codebase itself, with LLMShift as the safety net: "move this repo off gpt-4o and prove nothing broke".
claude mcp add llmshift -- llmshift mcp # Claude Code Cursor, in .cursor/mcp.json:
{"mcpServers": {"llmshift": {"command": "llmshift", "args": ["mcp"]}}} VS Code, in .vscode/mcp.json:
{"servers": {"llmshift": {"type": "stdio", "command": "llmshift", "args": ["mcp"]}}} The tools are llmshift_scan, llmshift_models, llmshift_snapshot, llmshift_compare, llmshift_fix, llmshift_pick, llmshift_safety, llmshift_check, llmshift_upgrade and llmshift_doctor. They work in the project the assistant has open (pass --cwd DIR to pin another), read llmshift.yaml like the CLI, and use the same API keys. Each tool tells the client whether it calls models or writes files, so assistants can ask first: llmshift_snapshot writes the test file, and llmshift_upgrade edits code only when called with apply. llmshift_fix never edits code; it returns suggested prompts and where they live.
A model is written provider:model; well-known IDs work without a prefix.
llmshift doctor shows which credentials it can see.
- uses: DeChuks-hub/llmshift@v0.1.0 with: command: compare args: --to openai:gpt-5.6-sol --min-pass-rate 0.95 --junit llmshift-junit.xml env: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} Inputs: command (any LLMShift command), args, python-version, version (empty = install from the action's source), working-directory. Outputs: pass-rate, retired, retiring, recommended (from pick). Complete workflows are in examples/workflows/: PR checks, a nightly watch, prompt checks on pull requests, weekly upgrade pull requests and a weekly retirement digest.
Settings live in llmshift.yaml or under [tool.llmshift] in pyproject.toml; the nearest one in the current directory or a parent (up to the git root) is used. Relative paths in it are relative to the file, so commands work from any subdirectory. ${VAR} and ${VAR:-default} are read from the environment. Command-line flags win, and values of the wrong type are reported with the key's name. examples/llmshift.yaml documents every key: default models, judge, repeats, thresholds, severities, scan options, snapshot limits and redaction, fix rounds, pick candidates and prices, watch thresholds and alerts, the digest, and custom providers.
python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate pip install -e ".[dev]" pytest The test suite (380 tests) runs offline on Python 3.9 to 3.15. Provider, GitHub and Evals-API tests use a local HTTP server that emulates the real APIs, and tests/test_torture.py feeds every command hostile input.
All 2 files in this release have provenance metadata.
anthropic evals gemini llm migration model-deprecation openai prompt regression testing
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 22, 2026.
All 2 files in this release have been uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




