AI

How to Migrate Prompts Between LLM Providers

Switching AI vendors? Learn how to migrate prompts between LLM providers in eight steps, with eval sets, shadow traffic, and safe rollback plans.
How to Migrate Prompts Between LLM Providers

Introduction

Learning how to migrate prompts between LLM providers has become a core engineering skill, because almost every production AI team eventually switches vendors or adds a second one. The market makes switching easy at the API level, since OpenRouter lists more than 400 models and LiteLLM covers more than 100 behind a single interface. Easy calls hide hard behavior, because a prompt tuned for one model carries assumptions about formatting, verbosity, refusals, and tool use that the next model does not share. Teams that swap only the model string often see passable demos and then discover regressions in long-tail traffic weeks after launch. This guide walks through what changes between providers, how to measure those changes, and how to roll out a new model without surprising your users. It combines vendor documentation, engineering postmortems, and open tooling into one eight-step workflow you can run against your own prompts. By the end you will know how to migrate prompts between LLM providers with evidence instead of hope.

Quick Answers on Moving Prompts Between LLM Providers

How do you migrate prompts between LLM providers?

Inventory every prompt, build an eval set from real traffic, adapt formatting and parameters, then compare both models on identical tests. Roll the new prompts out through shadow traffic and a small canary with rollback triggers.

Why do prompts behave differently on another LLM?

Each model family has different formatting preferences, system prompt handling, tokenizers, and refusal habits, so identical prompts produce different length, structure, and accuracy. Prompts encode assumptions about one model that rarely transfer unchanged between providers.

Can a gateway or optimizer migrate prompts for you?

Gateways standardize the API call and optimizers can rewrite prompts automatically, but neither proves quality. You still need an eval set, shadow testing, and human review before moving production prompts between LLM providers.

Key Takeaways

  • Knowing how to migrate prompts between LLM providers means treating a swap as a behavior change, so every prompt needs adaptation and testing.
  • An eval set of 50 to 200 representative inputs, scored with the same rubric on both models, is the single most valuable migration asset.
  • Shadow traffic and a canary rollout with automated rollback triggers catch the regressions that offline tests miss.
  • Gateways and optimizers reduce effort but never replace human review of the prompts that carry real business risk.

Table of contents

Understanding Prompt Migration Between LLM Providers

Knowing how to migrate prompts between LLM providers means adapting, testing, and gradually rolling out prompt text, parameters, and tool definitions so a new model matches the old model’s quality, format, cost, and safety behavior instead of merely swapping the endpoint.

An Interactive From AIplusInfo

How Big Is Your Prompt Migration?

Adjust the number of prompts, the size of your eval set, and the rollout style to see a planning estimate built from published migration ranges.

8

1 prompt40 prompts

60

10 cases250 cases

Standard

fastersafer

Prompt engineering effort

16 to 40 days

2 to 5 days per major prompt

Estimated calendar time

5 to 11 weeks

One engineer, adaptation plus rollout

Model calls per eval pass

960

Prompts times cases times two models

Shadow-run extra spend

+46%

Of one month of inference, while shadowing

Dark: prompt adaptation (upper estimate). Blue: shadow run. Gold: canary.

Your eval set sits inside the 50 to 200 case range that published playbooks suggest.

Ranges come from a model migration playbook and a deprecation analysis. Treat the output as a planning estimate, not a quote.

Why Teams Move Prompts to a New Provider

Building on that definition, the first question is why teams migrate at all, because the motive shapes how much risk you can accept. Cost is the most common trigger, since per-token prices and caching discounts differ enough to change a monthly bill by a meaningful fraction. Quality is the second trigger, because a newer model may handle long documents, structured extraction, or multi-step tool use better than the one you shipped on. Reliability and capacity matter too, as rate limits, regional availability, and outages push teams toward a second vendor. Every one of these motives is legitimate, yet each carries a different tolerance for regression, so write down the motive before you touch a single prompt.

Pricing pressure deserves a closer look because the headline numbers rarely tell the whole story. One migration guide lists GPT-4o at $2.50 input and $10.00 output per million tokens. Claude Sonnet 4.6 is listed at $3.00 and $15.00, yet cached Sonnet input drops to $0.30 per million tokens. A cheaper list price can lose to a pricier model once caching, retries, and tokenizer differences are counted. For a deeper view of how those economics move over time, see our analysis of generative AI cost per token trends and budgeting. Treat any savings estimate as a hypothesis that your own eval and shadow runs must confirm.

Vendor change also arrives without your consent, which is the third force behind migration. Providers retire models on published schedules, and one analysis reports that Anthropic commits to at least 60 days of notice while OpenAI once retired 33 models in a single wave. Average model lifespans of 12 to 18 months mean that even teams happy with their vendor will migrate prompts regularly. A team that treats migration as a one-off project will rebuild the same machinery every year. A team that treats it as a routine capability, with versioned prompts and a standing eval set, pays the cost once.

What Breaks When a Prompt Crosses a Provider Boundary

Stepping back from motives, the practical problem is that prompts fail in ways that tests written for the old model rarely detect. Researchers have reported that small formatting changes can move few-shot accuracy by up to 76 points, which shows how much a prompt depends on the model it was tuned against. A prompt is therefore less like portable text and more like a configuration file for one model’s habits. When the habits change, the same words produce longer answers, different refusals, or subtly different structure. The failure is usually quiet, because the output still looks plausible to a casual reader.

Breakage falls into a few repeatable families that are worth naming before you test. Format drift happens when the new model wraps JSON in prose, adds markdown headings, or changes list styles that downstream parsers expected. Behavior drift shows up as new caveats, over-eager refusals, or a different willingness to ask clarifying questions. Capability drift appears when tool calls run in parallel on one model and sequentially on another, changing both latency and correctness. Naming each family up front lets you write a targeted test for it instead of hoping a generic benchmark catches the problem.

Cost and length drift are the next family and the one finance teams notice first. Tokenizers split the same text differently, so one analysis observed tokenizer drift of up to 112 percent, meaning a 500-token prompt could cost over 1,000 tokens elsewhere. A model that is 30 percent more verbose multiplies output spend even when the list price falls. Latency changes follow, because longer answers and different reasoning defaults move both median and tail response times. If you want a practical way to think about these hidden costs, our guide on prompt-like-a-pro LLM tactics shows how prompt structure influences output length.

Finally, there is data and process drift, which no model card will warn you about. Labeled examples, traces, and eval results live in whichever tool your team adopted first, and they may not export cleanly to the next one. Few-shot examples chosen for the old model may mislead the new one, and system prompts that relied on provider-added defaults may need to be written out explicitly. Reviewers also carry expectations about tone and format that were calibrated on the old outputs. Capturing those expectations in a written rubric before the migration turns arguments about taste into measurable criteria.

Message Formats and API Shape Differences

Beyond behavior, the mechanical differences between provider APIs are the first thing every migration must handle. OpenAI’s chat completions place the system prompt as a message with a system role, while Anthropic’s messages endpoint takes it as a separate top-level parameter. Anthropic also requires a max tokens value on every request, supports only user and assistant roles, and returns one completion per call without an n parameter. Responses differ as well, since OpenAI returns a string at the first choice while Anthropic returns an array of typed content blocks. These details are well documented, and a migration guide from Rene Zander lays out the full mapping field by field.

Stepping through the response and usage fields shows why an adapter layer pays for itself. Token usage appears as prompt and completion tokens on one API and as input and output tokens on the other. Streaming also differs, since one API sends delta tokens while the other emits typed events such as message start, content block delta, and message stop. Error classes and rate limit semantics vary too, with Anthropic exposing separate input token, output token, and request limits. Wrapping all of this behind a small provider interface keeps application code stable while each provider class handles its own formatting. Our comparison of ChatGPT and Claude key differences gives the product-level context behind those API choices.

An adapter layer should translate shapes, but it should never hide behavior that you need to test. Capability negotiation, such as whether a model supports a given structured output mode, belongs in configuration that fails loudly at startup. Prompt text should stay outside the adapter and live in versioned files per model. Mixing the two produces an abstraction that makes every model slightly worse, a failure mode that has been described in practitioner writing on gateway design. Keep the adapter thin, keep the prompts explicit, and keep the tests close to both.

Formatting Conventions: Markdown, XML, and Delimiters

Turning to prompt text itself, the most common adaptation is the way you separate instructions from data. OpenAI models tend to respond well to markdown headers, emphasis, and lists, while Anthropic models tend to respond well to XML tags that wrap each input section. Neither preference is a rule, yet changing delimiters is cheap and often yields a measurable improvement in instruction following. A typical conversion wraps documents, examples, and instructions in descriptively named tags and refers to those tags by name in the task description. The reverse conversion strips the tags and uses headers and fenced blocks, which is why a team prompt library should store the structure separately from the wording.

Test delimiter changes in isolation, because formatting alone can swing accuracy more than any wording edit. Change only the delimiters on a copy of the prompt, run the eval set, and record the difference before touching instructions. Tone words matter as well, since one practitioner guide suggests softening hard prohibitions for Claude and restoring directness for GPT-4o. Treat those suggestions as hypotheses, because real prompts need careful rewriting rather than string replacement. Document what worked for each model family so the next migration starts from evidence.

Sampling Parameters and Hidden System Behavior

Shifting from text to settings, sampling parameters and invisible defaults explain many surprising differences. Closed providers add system instructions that users never see, so a prompt may silently depend on politeness, safety framing, or formatting rules supplied by the vendor. Groq’s migration documentation advises writing a thorough system message that makes those hidden rules explicit, covering persona, tone, hedging, disclaimers, and policy limits. It also recommends matching the source model’s temperature first, often 1.0, then adjusting after measurement. Many Llama deployments reportedly perform better between 0.2 and 0.4, which shows how much the right value depends on the model.

Reasoning behavior is the other invisible default that is worth checking before any test run. Some models think before answering and expose settings such as reasoning effort or a thinking budget that counts against the output limit. Models without that behavior need the reasoning spelled out in the prompt through step-by-step instructions, a verification pass, or sampled votes. When you move to or from a reasoning model, preserve the old reasoning setting for the first test pass and change one variable at a time. Our explainer on how reasoning models think covers why simpler instructions often work better for them. Record every parameter in the prompt’s version metadata so results stay reproducible.

Seeds and determinism deserve a final note because teams often rely on them in tests. Some providers do not expose a seed parameter or log probabilities, which removes tools you may have used to stabilize comparisons. Without them you need larger eval sets and repeated runs to separate real regressions from sampling noise. Plan for at least three runs on borderline prompts and compare score distributions rather than single numbers. This extra rigor costs little and prevents false alarms during canary analysis.

Structured Output and Tool Calling Differences

Moving on to machine-readable output, structured formats are where migrations fail most expensively. OpenAI offers a strict JSON schema mode with constrained decoding, while Anthropic historically recommended forcing a tool choice to obtain schema-shaped output. One analysis notes that Anthropic’s structured outputs reached general availability in early 2026 but rely on instruction following, so conformance should be measured rather than assumed. Constrained decoding guarantees syntax, but it does not guarantee that field values are correct. Either way, your parser should validate every response and your eval set should score schema conformance as its own metric.

Tool definitions differ in shape as well as in the semantics that models attach to them. OpenAI nests a function object with a parameters schema, while Anthropic uses a flat definition with an input schema field. Tool arguments arrive as a JSON string on one API and as a parsed object on the other. Tool results return as a tool role message on one and as a typed block inside a user message on the other. These are mechanical changes, yet each one is a place where a silent bug can hide. Our guides on function calling in LLMs and on how to design tool schemas that models use correctly explain the underlying patterns.

Behavior differs even when schemas match, which is why tool use needs its own tests. Some models call tools in parallel while others call them one at a time, which changes latency and the order of side effects. Models also differ in how often they call a tool unnecessarily, how they recover from an error result, and whether they ask for missing arguments. Measure tool-call accuracy, call count, and recovery behavior separately from answer quality, because a model can improve one while regressing the other. Include cases with missing arguments, ambiguous requests, and failing tools in your eval set.

For new systems, standard protocols reduce the integration half of the problem. The Model Context Protocol turns an N by M connector problem into a shared standard for tool access. The protocol is best understood as a transport for tools rather than a guide to prompting. A shared protocol still does not make prompts portable, because the model’s decision about when and how to call a tool remains a behavior. Keep tool descriptions concise and concrete, and test each one separately for every model you support. Treat descriptions as part of the prompt, because the model reads them that way.

Tokenizers, Context Windows, and Cost Math

Looking at the numbers, tokenizers and context behavior quietly change both cost and quality during a migration. Anthropic’s tokenizer is reported to split the same text into more tokens than OpenAI’s, so per-token prices cannot be compared without measuring real prompts. Our primer on tokenization in LLMs explains byte pair encoding and why the same sentence costs different amounts on different models. Context windows differ as well, with a 2024 comparison putting flagship models near 128,000 tokens, Sonnet 3.5 at 200,000, and Gemini models at 1 million or more. Advertised context limits are ceilings, and a model can degrade well before it reaches them. One comparison found GPT-4 strongest up to about 32,000 tokens while an older Sonnet degraded beyond 8,000 to 16,000, though those figures describe older models and must be re-measured today.

The practical rule is to use the lower of the advertised limit and the limit you measure on your own documents. Build a long-context test that places a fact at the start, middle, and end of inputs near your real maximum length. Run it on both models and record where retrieval accuracy falls. Set alerts below that threshold so production traffic never drifts into the degraded zone unnoticed. Recompute cost from observed token counts on a sample of real requests rather than from list prices alone.

How to Build an Eval Set Before You Touch a Prompt

Building on the cost picture, the eval set is the asset that turns a migration from opinion into evidence. A practical migration guide recommends comparing outputs side by side on at least 20 test cases. A regression harness guide suggests a golden dataset of about 50 to 200 representative inputs. MLflow’s prompt rewriting documentation recommends at least 20 to 50 diverse examples, including edge cases and mixed inputs. Sample from real production traffic, stratify by use case, language, and input length, and include the ugly cases that support tickets mention. Have someone outside the prompt authoring team review the set, because authors unconsciously test what they already know works.

Scoring needs the same care as sampling, and it should be defined before you see any results. Write per-case criteria that combine deterministic checks, such as schema validity and required fields, with semantic checks that a human or a judge model applies. Define thresholds for accuracy, format compliance, latency, cost, safety, and tool use up front, so nobody argues about acceptable regressions after the fact. Decide the pass bar before the first comparison run, because a threshold chosen after seeing the numbers is a rationalization. Our guide on evaluating outputs with an LLM as judge covers judge biases and calibration.

Finally, keep the eval set alive after the migration ends. Add every production failure, escalated ticket, and surprising output as a new case, so the set grows with your traffic. Version it alongside prompts and record which prompt version passed on which model version. One analysis found a model scoring 94 percent on evals but 78 percent on long-tail production traffic, a gap that only continuous additions can close. Treat that gap as the true measure of how representative your set is. A set that never grows will eventually certify prompts that real users have already outgrown.

Automated Prompt Rewriting and Optimizer Tools

From there, automation can shorten the adaptation step, provided you treat its output as a draft. OpenAI’s prompt optimizer cookbook describes pasting a baseline prompt into a playground, running the optimizer, reviewing the explained changes, and saving the result as a versioned prompt object. MLflow offers an experimental optimize prompts API that uses the GEPA optimizer to rewrite prompts so a new model reproduces the original model’s outputs. Groq documents llama-prompt-ops, which rewrites prompts written for GPT or Claude into Llama-friendly phrasing and offers a regression mode against a baseline. Each of these tools needs example inputs, and each works best when your eval set already exists.

These optimizers have real limits that you should plan around. Matching the old model’s outputs preserves its quirks and mistakes, so a prompt optimized for equivalence cannot be better than the original. Optimization also consumes extra model calls for reflection and scoring, which adds cost and requires access to several endpoints. Run optimizer output through the same eval gate as a hand-edited prompt, and read the diff like a code review. Our walkthrough of evaluating Bedrock agents with RAGAS shows one way to score such rewrites automatically, and the MLflow rewrite prompts guide documents the workflow.

How to Run Shadow Traffic, Canaries, and Rollback Plans

Stepping back from offline testing, production traffic is the only test that includes real users, so migrations need a staged rollout. In shadow mode you duplicate live requests to the candidate model, log its answers without showing them to users, and compare offline. One playbook estimates that one to two weeks of shadowing roughly doubles inference spend, which is a cost worth budgeting rather than avoiding. Watch structured output conformance, refusal rates, verbosity, and tail latency, because a 2 percent drop in conformance can mean hundreds of failed requests daily at scale. Shadow runs also reveal input shapes that your eval set never contained.

After shadowing comes a canary, which exposes a small slice of real traffic to the new model. Start with internal users, then 1 to 5 percent of a low-risk segment, and ramp over days to 25, 50, and finally 100 percent. Resist the urge to move quickly, because ramping over hours hides slow-moving problems such as support ticket spikes. One analysis argues that a two-week canary can still miss effects that only appear over longer soak windows. Hold each canary stage long enough for rare inputs, weekend traffic patterns, and downstream business metrics to show up.

Rollback criteria should be written down before the canary starts. Examples from published playbooks include structured output conformance below 97 percent, or p99 latency above 800 milliseconds for 15 minutes. Pair each trigger with an automatic action, such as a feature flag that routes requests back to the old model without a deployment. Keep the old model’s configuration warm and the old prompts in version control until the new model has been stable through at least one business cycle. A rollback you have never rehearsed is a rollback you cannot trust.

Instrumentation makes all of this possible, and it should exist before the migration begins. Dashboard refusal rate by prompt category, token usage per request, schema validation failures, and downstream accuracy for the new and old models side by side. Our guides on benchmarking LLM latency and throughput and on tracing give the measurement foundations. Continue monitoring for at least 30 days after the cutover, because behavioral drift often surfaces slowly. Keep the shadow harness available so the next model upgrade starts from working infrastructure.

Gateways and Abstraction Layers: What They Solve and What They Hide

Despite the appeal of a single endpoint, gateways solve only part of the migration problem. Braintrust’s gateway, OpenRouter, and LiteLLM let you call many providers through one interface. The Braintrust analysis notes that a shared API confirms requests succeed but not that output quality holds. Routing, retries, authentication, cost tracking, and failover are exactly the concerns an abstraction should own. They are also the concerns that change least between models, which is why centralizing them is safe. A gateway lets you switch the model identifier in one place and run the same eval suite against both models.

The real risks come from the provider-specific details that gateways flatten away. Provider-specific services such as file APIs, vector stores, fine-tuning, batch processing, prompt caching, multimodal formats, and proprietary tool features are not covered by a generic interface. A lowest-common-denominator abstraction can also leave capabilities unused, because the interface cannot express the best feature of each model. Abstract the plumbing, not the prompt strategy, and keep capability differences visible in configuration. Our analysis of vendor lock-in for agentic AI platforms shows how dependencies accumulate above the model layer.

Fallbacks deserve a specific warning because they look like free insurance. A gateway can retry the same model through another provider after an outage, which is safe because the model is unchanged. Falling back to a different model is a behavior change, so the replacement must be mapped in advance and must have passed the same evals. Otherwise your failover path silently serves lower-quality answers during the incident when you can least afford it. Test the fallback model on the same eval set and review its prompts like any other migration target.

Where Prompt Migrations Fall Short: Risks and Failure Modes

Given the many moving parts, it helps to catalog how migrations actually fail so you can test for each mode. The most common failure is false confidence, where a team swaps the model, runs a quick smoke test, and ships. One illustrative scenario in the deprecation literature describes a triage assistant that began offering unsolicited diagnostic opinions three weeks after a rushed swap. Token usage rose fivefold and JSON parsing failed in the same scenario. Other failures include refusal spikes, verbosity growth, broken few-shot patterns, and parser errors when output structure shifts. Most migration failures are detected by users and finance teams rather than by tests, which means your test design is the control that matters.

Hidden costs are the second category, and they surprise executives more than engineers. One analysis reports migration costs ranging from $30,000 to $250,000 or more, driven by duplicate inference, human review, prompt adaptation, and data export. Timelines also slip, since teams typically estimate one to two weeks while most migrations take four to eight. Budget two to five days of prompt engineering per major prompt and start with the highest-traffic ones. When schedules are forced by a retirement date, begin early enough that you can still roll back. Our guide to AI agent failure modes offers a debugging vocabulary for the incidents that slip through.

Ethics, Governance, and Vendor Dependence

Rounding out the technical picture, migrations raise governance questions that engineering checklists tend to skip. A prompt carries policy, because it encodes how the system treats users, what it refuses, and what disclaimers it adds. When the model changes, that policy can change without any code review, so migrations should pass through the same approval path as other policy changes. Safety guardrails placed in system prompts need adversarial testing on every new model, since some models weight the system prompt more heavily than user instructions. Document who approved the behavioral changes and why, so the decision can be audited later.

Ethical duties extend to the people affected by the outputs. If a model feeds hiring, lending, healthcare, or education decisions, a quiet shift in refusal rates or tone can change outcomes for specific groups. Compare outputs across demographic and language segments, not just in aggregate, before and after the move. A migration that improves the average score while degrading one group’s results is a regression, not a win. Keep human review in the loop for sensitive categories until the new model has a track record. Share the results with the governance body that owns AI risk, using the same format every time.

Vendor dependence is the structural issue behind all of this. A handful of providers supply most production models, and a policy change, price change, or retirement at one of them can force migration on every customer at once. Keeping prompts, evals, and traces in portable formats under your control is the main defense. Our explainer on AI observability and tracing for LLM applications describes how to keep that evidence in open formats. Contracts also matter, so ask providers about deprecation notice periods, data retention, and export rights before depending on them. Dependence cannot be eliminated, but it can be priced and planned.

The Future of Prompt Portability

Looking ahead, the cost of moving prompts will shrink but will not reach zero. Automated optimizers, shared evaluation tooling, and standard protocols for tools are already removing the mechanical work, and more of it will be automated each year. Many providers now expose OpenAI-compatible endpoints, which narrows the mechanical differences between APIs. Models are also getting better at following instructions that were written for a different model. The remaining portability tax is behavioral, and behavior can only be verified by measurement. Our work on context engineering for LLM agents suggests the discipline is shifting from wording prompts to managing everything a model sees.

Teams should therefore invest in capabilities rather than one-off conversions. A standing eval set, versioned prompts, a compatibility matrix of which prompt version passed on which model, and a rehearsed rollout path make every future migration cheaper. Continuous drift monitoring turns provider-side model updates, which can change behavior without notice, into routine events. The organizations that migrate well will be those that treat prompts as versioned, tested software artifacts with owners. In that world, knowing how to migrate prompts between LLM providers becomes a routine maintenance skill rather than a crisis response.

Chart From AIplusInfo

Where the weeks go in an eight-week prompt migration

Weeks allotted to each stage of the plan, one engineer, ten to twenty production prompts.

Source: stage durations follow the model migration playbook and the deprecation analysis. Daily cost assumes 1M input and 200K output tokens at published list prices, with the GPT-4o and Sonnet figures taken from René Zander, and varies by contract.

Putting It Into Practice: How to Migrate Prompts Between LLM Providers in Eight Steps

With that groundwork in place, the following eight steps turn the concepts above into a repeatable workflow. The sequence for how to migrate prompts between LLM providers follows the order used by published playbooks, which start with an inventory and end with monitoring and documentation. Each step produces an artifact that you can store in version control, so the migration leaves behind assets instead of tribal knowledge. Do not skip the early steps to reach the rollout sooner, because every later decision depends on the inventory, criteria, and eval set. Budget a few days per major prompt, and expect the whole effort to take weeks rather than days for a multi-prompt system. The code samples are deliberately small so you can adapt them to your own stack.

Step 1 – Inventory every prompt and model call

Start by listing every place your codebase calls a model, because migrations fail most often on prompts nobody remembered. Search for client calls, model name strings, and files that store prompt templates, then record the model, parameters, owner, and traffic volume for each. OpenAI’s upgrade guidance for its newer models recommends this same inventory and asks you to pair each model usage with its closest prompt, flagging any link you are unsure about. Classify each usage as a model string change only, a light prompt rewrite, or blocked by API differences. The classification tells you where the work is concentrated and which prompts deserve eval attention first. Sort the inventory by traffic and revenue impact, and migrate the highest-risk prompts last, after the first 2 or 3 low-risk prompts have proven the process.

grep -rnE "chat\.completions\.create|messages\.create|generateContent" src/ \
  | sort > model_call_inventory.txt
wc -l model_call_inventory.txt

Step 2 – Write acceptance criteria before testing

Decide what good looks like before you see any numbers from the new model. Define thresholds for accuracy, schema conformance, refusal rate, latency, cost per task, safety, and tool-call accuracy, and store them in a file that reviewers can read. Playbooks suggest example rollback triggers such as structured output conformance below 97 percent or p99 latency above 800 milliseconds for 15 minutes. Set the pass bar per prompt, since a customer-facing summarizer and an internal classifier deserve different tolerances. Writing the criteria first protects the team from the common temptation to lower the bar after a disappointing result.

{
  "prompt_id": "support-summary-v3",
  "min_accuracy": 0.92,
  "min_schema_conformance": 0.97,
  "max_refusal_rate": 0.03,
  "max_p99_latency_ms": 800,
  "max_cost_per_task_usd": 0.01
}

Step 3 – Build the eval set from real traffic

Sample real requests, strip or mask personal data, and label the expected behavior for each case. Aim for at least 50 cases per important prompt, stratified by use case, language, and input length, and add edge cases from support tickets. Pair deterministic checks with a rubric, and use a judge model only where human labels would be too slow, then calibrate the judge against a small human-labeled slice. The MLflow guidance suggests 20 to 50 diverse examples as a floor for optimizer workflows. Store the set in a plain file format so it survives tool changes.

import json
import random

def sample_cases(path, n=100, seed=7):
    rows = [json.loads(line) for line in open(path)]
    random.Random(seed).shuffle(rows)
    return rows[:n]

Step 4 – Adapt message format and prompt structure

Translate the API shape first, then adapt the prompt text. Move the system prompt to the top-level field when targeting Anthropic, set the required maximum output tokens, and convert tool definitions and results into the target format. Then restructure the prompt text itself for the new model family. For example, wrap documents and instructions in named XML tags when moving to Claude, or convert them to headers when moving the other way. Change one thing at a time and rerun the eval after each of the 4 or 5 edits, because it is the only way to know which edit helped. Keep the new prompt in a separate versioned file for each provider.

def to_anthropic(messages, max_tokens=2000):
    system = [m["content"] for m in messages if m["role"] == "system"]
    chat = [m for m in messages if m["role"] != "system"]
    return {
        "system": "\n\n".join(system),
        "messages": chat,
        "max_tokens": max_tokens,
    }

Step 5 – Match parameters and make hidden rules explicit

Copy the source model’s sampling settings first, then tune them with measurements rather than intuition. Groq’s guidance advises matching temperature to the source model, leaving top p at 1.0 initially, and noting that many Llama deployments perform better between 0.2 and 0.4. Write out any behavior the old provider supplied invisibly, such as persona, tone, refusal templates, and disclaimers, inside an explicit system message. If you are moving to or from a reasoning model, keep the reasoning effort or thinking budget the same for the first run. Record every setting in a configuration file next to the prompt so a future migration can reproduce the result.

prompt_id: support-summary-v3
provider: anthropic
model: example-model-name
temperature: 0.3
top_p: 1.0
max_tokens: 2000
system_prompt_file: prompts/support-summary-v3.claude.xml.txt

Step 6 – Run both models on the eval set and compare

Execute the same eval set against the old and new models using identical scoring code, and keep every raw output for review. The Braintrust migration steps recommend reviewing each scorer separately, since a candidate may gain accuracy while losing format compliance or tool-call reliability. Run borderline prompts several times to separate regressions from sampling noise. Read at least 50 to 100 paired outputs by hand for customer-facing prompts, because averages hide the odd failures that users remember. Iterate on the prompt until the new model meets every threshold, or decide that this workload should stay where it is.

def run_eval(call_model, cases, score):
    results = []
    for case in cases:
        output = call_model(case["input"])
        results.append({"id": case["id"], "output": output, "score": score(case, output)})
    return results

Step 7 – Shadow, canary, and roll out with rollback triggers

Send duplicated production requests to the new model without showing its answers, then compare offline for one to two weeks. Move on to a canary of 1 to 5 percent of a low-risk segment, and ramp to 25, 50, and 100 percent over days rather than hours. Tie each stage to the rollback triggers from step 2, and automate the switch back through a feature flag so nobody has to deploy code during an incident. Keep the old model warm and the old prompts in version control until the new model has survived a full business cycle. A LiteLLM style gateway can make the traffic split a configuration change rather than a code change.

rollout:
  stages: [1, 5, 25, 50, 100]
  hold_hours_per_stage: 48
  rollback_if:
    schema_conformance_below: 0.97
    p99_latency_ms_above: 800
    refusal_rate_above: 0.05

Step 8 – Monitor, document, and version the result

After cutover, track refusal rate, token use per request, schema failures, and downstream accuracy for at least 30 days. Record which prompt version passed on which model version in a compatibility matrix, and store the eval results next to it. Add every new production failure to the eval set so the next migration starts from a stronger baseline. Schedule a periodic re-evaluation, because providers update models and your traffic changes. Share a short migration report with the owners of the affected features so the behavioral changes are understood and approved.

{
  "prompt_id": "support-summary-v3",
  "validated": [
    {"provider": "provider-a", "model_version": "2026-05", "eval_pass_rate": 0.94},
    {"provider": "provider-b", "model_version": "2026-09", "eval_pass_rate": 0.93}
  ]
}

Recommended by AIplusInfo

Books to go deeper on model migration

Two practitioner books that cover evaluation, prompting, and model behavior for teams planning a provider swap.

As an Amazon Associate, AIplusInfo earns from qualifying purchases.

AI Engineering: Building Applications with Foundation Models

Book

AI Engineering: Building Applications with Foundation Models

Covers evaluation, prompt engineering, and deployment of foundation model applications, the exact skills behind a safe model swap.

Buy on Amazon
Hands-On Large Language Models: Language Understanding and Generation

Book

Hands-On Large Language Models: Language Understanding and Generation

Explains tokenizers, embeddings, and model behavior in hands-on detail, which helps teams predict how prompts will differ across models.

Buy on Amazon

Key Insights on Moving Prompts Between LLM Providers

  • Research cited in a portability analysis found that small formatting changes can shift few-shot accuracy by up to 76 points, so prompts rarely transfer unchanged.
  • Teams often estimate one to two weeks for a model swap, yet a migration playbook reports that most take four to eight weeks once adaptation, shadowing, and rollout are included.
  • Reported migration costs range from $30,000 to $250,000 or more, driven by duplicate inference, human review, prompt adaptation, and data export, so the work deserves a real budget.
  • Tokenizer drift of up to 112 percent has been observed in deprecation research, meaning a 500-token prompt on one model can cost more than 1,000 tokens on another.
  • A prompt migration guide recommends side-by-side comparison on at least 20 test cases and human review of 50 to 100 real conversation samples before cutover.
  • For a daily workload of 1 million input and 200,000 output tokens, one pricing comparison lists $4.50 for GPT-4o and $6.00 for Claude Sonnet 4.6, or $3.30 cached.
  • MLflow recommends at least 20 to 50 diverse examples when its experimental prompt optimizer rewrites prompts for a new model, because optimization can only learn from the cases it sees.
  • Notion runs regression evals with 70 engineers and reports deploying suitable new models in under 24 hours, which shows what a mature eval pipeline buys.

Taken together, these figures describe a migration problem that is mostly about evidence rather than syntax. Formatting sensitivity and tokenizer drift explain why identical prompts diverge, while the gap between two-week estimates and eight-week reality explains why projects slip. Costs of tens of thousands of dollars follow from the duplicate inference, review hours, and adaptation work that careful teams cannot avoid. Eval sets of 20 to 200 cases are the cheapest way to convert those unknowns into decisions. Organizations that build the evidence pipeline once, as Notion's example suggests, can adopt new models in hours instead of weeks.

Provider Differences at a Glance

On top of the earlier discussion, the table below condenses the mechanical and behavioral differences that matter most when prompts cross a provider boundary. It compares the OpenAI chat style, the Anthropic messages style, and open models served through hosted endpoints, using the guidance cited throughout this article. Treat every cell as a starting hypothesis, because vendors change defaults and a model released next quarter may behave differently. Use the table to decide which tests to write, not to skip testing. Cost per task deserves its own measurement, and our piece on agent cost per task shows how to compute it from traces instead of list prices. Verify each row against the current documentation before relying on it.

DimensionOpenAI chat styleAnthropic messages styleOpen models on hosted endpoints
System prompt placementA system role message inside the messages arrayA separate top-level system parameterUsually a system message; write hidden vendor rules out explicitly
Maximum output tokensOptional with a model-specific defaultRequired on every requestSet explicitly to control length and cost
Preferred prompt structureMarkdown headers, lists, and delimitersXML tags around each input sectionShort numbered rules and explicit reasoning steps
Tool definitionA function object with a parameters schemaA name with an input schema fieldConfirm the model supports tool use before migrating
Tool arguments and resultsJSON string arguments and a tool role resultParsed object arguments and a result block in a user messageVaries by model and host, so test each pattern
Structured outputStrict JSON schema mode with constrained decodingForced tool choice or instruction-following structured outputsLower temperature, often 0.2 to 0.4, plus validation
Multiple completionsAn n parameter for several candidatesOne completion per callDepends on the host
Reasoning controlsA reasoning effort setting on reasoning modelsA thinking budget that counts against max tokensSpell out reasoning steps in the prompt
Usage fieldsPrompt tokens and completion tokensInput tokens and output tokensVaries by host, so normalize in the adapter

Examples of Prompt Migration in Practice

OpenAI's Prompt Optimizer on a Top-K Task

Building on the idea of automated rewriting, OpenAI's cookbook ran its prompt optimizer on a coding prompt. The prompt asked for a Python script that finds the top-K most frequent tokens in a text stream. The authors pasted a baseline prompt with contradictory instructions into the optimizer, accepted its refinements, and saved the result as a versioned prompt object. Across 30 runs per prompt on 5 million tokens, average runtime fell from 7.906 to 6.977 seconds and peak memory dropped from about 3,626 KB to 578 KB. Exactness and sorting stayed at 100 percent for both versions, so the gains showed up in speed, memory, and judged quality rather than correctness. The OpenAI optimizer cookbook itself lists limits, including a single test machine, judge-based quality scores, and baselines that already had little headroom. That candor is a useful reminder that optimizer gains depend heavily on how weak the starting prompt was.

MLflow's Prompt Rewriting for a Cheaper Model

MLflow's documentation walks through moving a sentiment classification prompt from GPT-5 to the cheaper GPT-4o-mini using its experimental prompt optimization API. The team registered the prompt, captured the original model's outputs on 10 sample inputs as training data, and ran the GEPA optimizer with an equivalence scorer. The workflow needs no human-labeled ground truth, which removes the slowest part of most migrations. The stated aim is a cost reduction from the smaller model, but the page reports no measured savings. It recommends 20 to 50 diverse examples for real use, so the 10-input demo is only a toy, and the feature is still marked experimental. Details appear in MLflow's rewrite prompts guide, which also notes that optimization adds calls to reflection and scoring models.

Notion's Eval-Driven Model Adoption

Notion uses Braintrust with a team of 70 engineers to run regression and frontier evals whenever a new model ships. The team built its evaluation pipeline so that suitable models can be deployed in under 24 hours, which turns migration into a routine event. That speed comes from a standing eval suite, shared scorers, and a gateway that lets the team change the model identifier in one place. The Braintrust analysis of provider lock-in is a vendor publication, so its framing favors its own platform and should be read with that bias in mind. The same page also warns that gateways do not cover provider-specific services such as batch processing, caching, or fine-tuning. Those pieces still need separate migration work even when the prompts are ready.

Lessons From Real Migration Case Studies

Case Study: DeHaze Labs Moves a Brand Intelligence Pipeline

Despite shipping quickly on GPT-4.1, DeHaze Labs faced recurring problems in a pipeline that extracts brand mentions from video and podcast transcripts. Long transcripts caused chunk boundary errors, ambiguous mentions inflated the manual review queue, and unreliable structured output required retry logic and manual intervention. The team ran a production-style comparison that held the pipeline constant and varied only the model, then swapped the client in its abstraction layer and adopted Claude. They adjusted prompt formatting for system messages and structured output, updated tokenization assumptions, and relaxed the chunking strategy to reduce cross-chunk reconciliation. After cutover they kept GPT-4.1 in shadow mode on a subset of production traffic and reported no regressions they had not already seen in evaluation. The DeHaze Labs write-up publishes no percent improvement, cost, or latency figures, so the results are qualitative.

The limitations are worth studying as closely as the outcome. The authors admit the original GPT-4.1 choice was made under timeline pressure and was not rigorously evaluated. Long-transcript boundary effects were never fully solved, and tightening chunking in one place created errors elsewhere. Ambiguous validation cases still depend on human review, and the post does not name the other models it considered. The lesson is that even a successful migration rarely removes a problem entirely, which makes standing evaluations and periodic re-checks the real deliverable. The team says it re-evaluates its model choice periodically for exactly that reason.

Case Study: An Illustrative Triage Assistant Swap

A scenario described in the model deprecation literature shows how a rushed migration goes wrong. A healthcare triage team that faced a retirement deadline received 90 days of notice, swapped the model string, and shipped after a quick manual smoke test. Three weeks later the new model was giving unsolicited diagnostic opinions, token usage had risen fivefold, prompt templates were breaking, and JSON parsing was failing. The solution the analysis proposes is a structured process built on model call abstraction and a prompt compatibility matrix. It adds a golden dataset of 50 to 200 inputs and an eight-week plan with shadow mode and a canary. That plan baselines in weeks one and two, remediates in weeks three and four, and shadows in weeks five and six. A canary of 1 to 5 percent follows before full rollout. The deprecation analysis labels the triage story illustrative, so treat it as a cautionary pattern rather than a documented company incident.

The recommended plan carries its own costs and limits that teams should weigh carefully. An eight-week schedule that starts 60 days before retirement leaves little slack if a provider shortens its notice. Running two models in shadow mode roughly doubles inference spend for the duration, and golden datasets need an independent reviewer to avoid authors testing only what they expect to work. The scenario also shows how a safety-relevant behavior change, unsolicited diagnoses, can hide behind a passing smoke test. Teams in regulated domains should add behavior-specific checks for refusals, disclaimers, and scope before any traffic moves.

Case Study: Google's Cost-Per-Task Routing Across Gemini Models

Faced with coding-agent bills that kept rising even as per-token prices fell, a Google Developers Blog experiment argued that cost per successful task is the better metric. The authors built a router that sends every task to a lightweight model first and escalates tasks flagged as complex to a stronger model on low thinking. In a 50-question auto-graded benchmark, the router solved all 50 tasks, and its classifier scored 48 of 50 on classification. A regex and length heuristic fell from 93.8 percent on development questions to 70.6 percent on unseen ones. The smaller model alone missed 6 of 25 hard tasks, and capping output tokens broke 7 of 25 hard tasks, so naive cost cuts carried real quality risk. The Google Developers Blog post also notes that resending cached context can cost 75 to 90 percent less, but a cache is tied to one model.

The article states its own limitations plainly, which makes it a good model for how to read migration evidence. Each setup ran once on 50 prompts with hand-assigned difficulty labels and simple automatic grading, so the figures will vary with prompt length, caching, and production load. Results come from one classifier, and self-hosted classifiers are billed by GPU hour rather than per token. Routing can conflict with caching, so long context-heavy turns may be better kept on a single model. For migration planners the takeaway is that choosing between models is also a routing decision, and every routing rule needs its own eval set before it reaches production.

Frequently Asked Questions About Migrating Prompts Between LLM Providers

What is the first step when you migrate prompts between LLM providers?

The first step is an inventory of every place your system calls a model, along with the prompt, parameters, owner, and traffic for each. Knowing how to migrate prompts between LLM providers starts with knowing exactly what you have today. Without that list, forgotten prompts surface as production incidents after the switch. Classify each usage as a model string change, a light rewrite, or blocked by API differences.

Can I reuse the same prompt on OpenAI, Anthropic, and Gemini?

You can often run the same prompt text on another provider, but the results will usually differ in length, structure, and refusals. Small formatting changes alone have been reported to shift few-shot accuracy by up to 76 points. Treat the original prompt as a first draft for the new model and adapt formatting, system instructions, and examples. Then verify the adapted version against an eval set before moving any traffic.

How many test cases do I need for a prompt migration?

Published guidance ranges from at least 20 side-by-side cases for a small system to a golden dataset of 50 to 200 representative inputs. Optimizer tools such as MLflow recommend 20 to 50 diverse examples as a minimum. More important than the count is coverage of real traffic, edge cases, and failure modes from support tickets. Have someone outside the prompt authoring team review the set.

What should I measure besides accuracy when switching models?

Measure schema conformance, refusal rate, verbosity, tool-call accuracy, latency at the median and tail, and cost per completed task. Each of these metrics can regress even while average accuracy improves overall. Define thresholds for every metric before running the comparison so results cannot be rationalized afterward. For customer-facing prompts, add human review of 50 to 100 paired outputs.

How long does it take to migrate prompts to a new LLM provider?

A single agent with a solid benchmark suite may take two to three days, while multi-agent systems often take one to two weeks by one guide's estimate. Another playbook reports that most migrations take four to eight weeks once shadowing and canary rollout are included. Budget two to five days of prompt engineering per major prompt. Schedules lengthen when embeddings must be reindexed or when no eval set exists.

Do gateways like LiteLLM or OpenRouter make prompt migration unnecessary?

Gateways standardize the API call, so you can change the model identifier and keep your client code. They do not confirm that output quality, format compliance, or tool behavior holds on the new model. Provider-specific features such as caching, batch processing, and fine-tuning also fall outside a generic interface. Use a gateway for routing and failover, and keep prompt testing in your own eval suite.

Should I use an automated prompt optimizer?

Optimizers can shorten the adaptation step, especially when you already have example inputs and outputs. OpenAI's optimizer, MLflow's experimental GEPA-based API, and llama-prompt-ops are documented examples. Their output should be reviewed like a code change and run through the same eval gate as a hand-edited prompt. Remember that optimizing for equivalence preserves the old model's mistakes along with its strengths.

How do I handle structured output and tool calling differences?

Translate the schema formats first, then measure conformance and tool behavior as their own metrics. OpenAI offers a strict JSON schema mode, while Anthropic uses forced tool choice or instruction-following structured outputs. Validate every response in code and fail loudly when the schema is violated. Test missing arguments, ambiguous requests, and failing tools, because models differ in how they recover.

Why does my token bill change after switching providers?

Tokenizers split the same text into different numbers of tokens, and researchers have observed drift of up to 112 percent. Output verbosity also differs by model, so longer answers increase output spend even when list prices fall. Caching discounts and retry rates change the effective cost further. Compute cost per completed task from real traces rather than comparing list prices.

How do I roll back safely if the new model misbehaves?

Write rollback triggers before the canary starts, such as schema conformance below 97 percent or tail latency above a set threshold. Route traffic through a feature flag so you can return to the old model without a deployment. Keep the old model's configuration warm and its prompts in version control. Rehearse the rollback at least once before the canary reaches a large share of traffic.

What temperature should I use when moving to a different model?

Start by matching the source model's temperature, then adjust based on measurements rather than intuition. Groq's migration guidance notes that many Llama deployments perform better between 0.2 and 0.4. Lower values suit factual answers and strict formats such as JSON. Record the final setting with the prompt version so that results stay reproducible.

How do I keep prompts portable for future migrations?

Store prompts as versioned files per model, with metadata for parameters and the eval results that validated them. Keep a compatibility matrix of which prompt version passed on which model version. Put routing, retries, and cost tracking behind a thin abstraction, but leave prompt strategy outside it. Maintain a living eval set so every future migration starts from evidence.