Skip to main content

Prompt versioning and regression testing for LLM apps with W&B Weave

Last updated: August 10, 2026
A prompt edit is a production deploy with no build step and no test suite. Here is how to turn prompts into versioned Weave objects with history, aliases, and a quality gate.
Someone edits a prompt on a Friday afternoon. It is a one-line change, the kind that does not feel like it needs a review. Nothing crashes, no test goes red, and the deploy is green in four minutes. On Monday the support queue is full of tickets marked high priority, the on-call engineer cannot find the one that actually matters, and nobody remembers what changed.
Your application code has version history, review, and tests. The string that decides how the model behaves usually has none of those things. It lives in a constant at the top of a file, or in a config value someone can edit from a dashboard, and its entire history is whatever Git blame happens to show. That gap produces most LLM quality incidents, and it closes with two habits: publish every prompt as an immutable object with its own identity, and score every version against the same labeled set before it reaches users.
In this tutorial, we will build a support ticket triage assistant whose prompt lives in W&B Weave rather than in the codebase, publish three versions of it, score each one against twenty hand-labeled tickets, catch a regression that one of the two obvious metrics completely misses, roll it back by moving an alias, and wrap the suite in a script you can run in CI.

What is prompt versioning?

Prompt versioning means storing each edit of a prompt as an immutable, named object with its own identity, so you can point at a specific version, load it in code, and know exactly which one produced a given output. Instead of one mutable string that changes underneath you, you get a history you can query, compare, and roll back.
Most teams will point out that their prompts already live in Git, which is true, and putting them there is better than leaving them in a config field somebody can edit from a dashboard. A commit tells you what changed, who changed it, and when. What it does not tell you is whether the change helped, because nothing in a diff connects a prompt edit to the quality it produced. Git also cannot change which prompt version production uses without shipping code, and that one matters a lot at 2am. What follows keeps the review and the CI gate you would get from Git either way, and adds the two things it cannot do: link a prompt version to the scores it produced, and move production onto a different version without a deploy.
W&B Weave treats prompts as first-class objects. You build one with a Weave prompt class, publish it under a name, and get back a reference. Publish a different body under the same name and Weave stores a second version rather than replacing the first. Every version carries a permanent address you can load from application code, plus whatever aliases and tags you attach. An alias is a movable pointer, so triage_prompt:production means "whichever version is currently in production" and resolves differently depending on where you last pointed it. A tag is a sticky label on one specific version, useful for recording that a version was reviewed or that it failed evaluation. The Weave docs cover this across two pages, creating prompt objects and storing and tracking versions, and both are worth a skim before you start.

What is regression testing for LLM apps?

Prompt regression testing means running a fixed, labeled set of inputs through your system every time something changes, scoring the outputs, and comparing the aggregate result against the scores your current production version achieved on the same set. You are checking that overall quality holds, rather than asserting that any single input produces one exact string.
That distinction matters because LLM outputs vary. Asserting that ticket seventeen always comes back as billing gives you a test that fails for reasons you do not care about. Asserting that priority accuracy across twenty tickets stays above a floor gives you a test that fails when something real has broken.
Three parts make it work. The first is a dataset: a set of inputs paired with the output each one should produce, which people usually call the label. For a triage assistant, an input is the ticket text and its labels are the category and priority a person decided it belongs in. The second is scorers, functions that take one output and its label and return a number saying how close they were. The third is a threshold, because a number on its own is trivia until someone decides what value of it should block a release.
A suite like this has real limits, and they are worth knowing before you trust it. A small set will catch a coarse regression and miss a subtle one, and every label in it is a judgment call rather than a fact, so two people building the same suite would not produce quite the same numbers. Then there is the part you do not control at all, which is that model providers update models underneath a prompt you never touched, so a suite that passed in March can fail in June with no code change on your side. What all of this adds up to is that a passing suite is evidence you did not break the obvious thing, and treating it as proof of quality is how teams get comfortable right before an incident.

The tutorial: a triage assistant that survives prompt edits

We are building a support ticket triage assistant for a fictional B2B analytics product. It reads an incoming ticket and returns a category and a priority as JSON. The application itself is about fifty lines of Python, with another hundred or so for the dataset and the scoring code, and it exists to give us something small enough to reason about and realistic enough that the failure mode will look familiar.
By the end, the prompt will live in W&B Weave rather than in your code. Your application will load it by name at runtime, every edit will be stored as its own version you can compare against the others, and you will be able to switch which version production uses without touching the codebase. Alongside it you will have a regression suite that tells you when an edit made things worse. All code is inline, so you can follow along without cloning anything; the companion repository is there if you would rather start from a working tree. Everything lands in a Weave project called prompt-versioning-demo.
You will build eight files. Six of them you run directly, in this order: prompts.py, dataset.py, evaluate.py once per prompt version, promote.py, write_baseline.py, then check_regression.py. The other three, triage.py, scorers.py, and the config they share, are imported rather than run.

Step 0: Set up the environment

You need Python 3.10 or newer, an OpenAI API key, and a Weights & Biases account. The free tier covers everything here, and the full tutorial costs a few cents in API calls.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate

pip install "weave==0.53.4" "wandb==0.28.1" "openai==2.53.0" "python-dotenv==1.2.2"
wandb login
Create a .env file next to your scripts:
OPENAI_API_KEY=sk-your-key-here
The wandb login step writes credentials to ~/.netrc, so weave.init can talk to your Weights & Biases account without further configuration. If you are running inside a container or a CI job where interactive login is awkward, set WANDB_API_KEY as an environment variable and skip the login command.

Step 1: Publish a prompt as a versioned Weave object

Weave ships two prompt classes, and the choice between them is about shape rather than complexity.
StringPrompt holds a single block of text. It fits a system message you drop into a larger request that you assemble yourself, or any standalone instruction you want to track. MessagesPrompt holds a list of role and content pairs, which is what you want when the prompt itself defines the conversation structure, including few-shot exchanges.
Save this as prompts.py and run it once.
import weave

weave.init("prompt-versioning-demo")

triage_v0 = weave.MessagesPrompt([
{
"role": "system",
"content": (
"You are a support triage assistant. Read the ticket and return JSON "
"with two keys: category and priority. "
"Category must be one of: billing, account_access, bug, "
"feature_request, other. "
"Priority must be one of: low, medium, high."
),
},
{"role": "user", "content": "{ticket}"},
])

ref_v0 = weave.publish(triage_v0, name="triage_prompt")
print("published:", ref_v0.uri())
And you will get something like:
published: weave:///your-entity/prompt-versioning-demo/object/triage_prompt:HiHlkAVBOY76OYFJHQl9JVDADuKQWA9ch7bWQ64328c
The return value is worth understanding properly, because everything later depends on it. weave.publish gives you a reference object, and .uri() renders it as a fully qualified address: entity, project, object name, and a version identifier. That URI is the permanent, unambiguous name for this exact prompt body. The entity segment will be your own username or team, since weave.init above takes a project name and lets Weave resolve the entity from your login. If you want it pinned explicitly, pass weave.init("your-team/prompt-versioning-demo") instead.
The version identifier at the end can take three forms, and knowing which to use where saves a lot of confusion. A content hash pins one exact body forever. A version index like v0 or v1 counts publications under that name in order. An alias like latest or production resolves to whichever version currently carries that label. Every object gets latest automatically.
Run prompts.py a second time without editing it and nothing new appears. Weave hashes the content, so republishing an identical body returns the same digest rather than creating a duplicate version. Change one word and republish, and you get a second version alongside the first, with both permanently loadable. Nothing you publish is ever edited in place.
The prompt now shows up on the Prompts page in your project, where anyone on the team can browse and reuse it. That is the part that makes this more than a storage trick: a prompt that three services share stops being copy-pasted into three repositories.

Step 2: Fill in the prompt and load it by reference

A prompt with a placeholder in it is a template, and format() is what fills it. This is the mechanism that lets one published version serve every request.
import weave

weave.init("prompt-versioning-demo")

prompt = weave.ref("triage_prompt:v0").get()

messages = prompt.format(ticket="My card was declined but the dashboard says active.")
print(messages[1]["content"])
That shows:
My card was declined but the dashboard says active.
That reference has two parts: triage_prompt is the name you published under, and v0 after the colon is which version of it you want. Together they identify an object, but not where that object lives, so Weave takes the entity and project from the active session. Pass the full URI instead, and all four are in the string:
weave.ref(
"weave:///your-entity/prompt-versioning-demo/object/triage_prompt:v0"
).get()
Look closely at what it substitutes, because this is wider than it first appears. Weave runs Python's str.format over every string value in every message, so the system message gets processed too. A placeholder in the system content works, and so does a literal curly brace breaking it.
That is the hazard. The moment you paste an example JSON object into a prompt to show the model the shape you want, format() stops working. MessagesPrompt raises IncorrectPromptVarError and tells you which variable it could not find; StringPrompt raises a plain KeyError. Double the braces to escape them:
weave.StringPrompt(
'Return JSON shaped like {{"category": "billing", "priority": "high"}} '
'for the ticket: {ticket}'
)
This is the kind of thing you discover at the worst possible moment, usually with a customer's ticket in the payload.
Now the application. It never contains prompt text. It contains a reference, and it loads the prompt at call time. Save this as triage.py.
import json
import os
from functools import lru_cache

import weave
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()


@lru_cache(maxsize=1)
def get_openai_client() -> OpenAI:
"""Lazy so that importing this module never requires a key."""
key = os.getenv("OPENAI_API_KEY")
if not key:
raise RuntimeError(
"OPENAI_API_KEY is not set. Copy .env.example to .env and fill it in."
)
return OpenAI(api_key=key)


class TriageModel(weave.Model):
"""Classifies a support ticket using a specific published prompt version."""

model_name: str = "gpt-4o-mini"
prompt_ref: str

@weave.op()
def predict(self, ticket: str) -> dict:
prompt = weave.ref(self.prompt_ref).get()

response = get_openai_client().chat.completions.create(
model=self.model_name,
temperature=0,
response_format={"type": "json_object"},
messages=prompt.format(ticket=ticket),
)
raw = response.choices[0].message.content

try:
parsed = json.loads(raw)
except json.JSONDecodeError:
return {"category": None, "priority": None, "raw": raw}

return {
"category": parsed.get("category"),
"priority": parsed.get("priority"),
"raw": raw,
}
That indirection is the whole trick. Because the prompt arrives by reference, swapping which version runs is a change to a pointer rather than a change to code.
Which reference you pass depends on what you are doing. Pin a version index or a content hash for evaluations, because an evaluation whose prompt can move underneath it is not reproducible. Follow an alias in production, so you can promote a new version without a deploy.
Two smaller notes on the model class. weave.Model is a Pydantic model underneath, so every field you declare becomes part of the model's own version identity: change model_name and Weave records a new model version, which is why an evaluation result is always attributable to a specific combination of code, model, and prompt. That is also why the OpenAI client sits outside the class instead of being a field, since Weave would try to serialize it. And the @weave.op() decorator on predict traces every call with inputs, outputs, latency, token counts, and any exception.
One wrinkle to expect: weave.ref("triage_prompt:production").get() has nothing to resolve until something has been aliased as production. We set that in Step 8, so pass explicit version references until then.

Step 3: Build the evaluation dataset and scorers

Twenty tickets, each with a category and a priority that a human decided on. That last part matters. These labels are judgment calls and you could argue with several of them. Writing them down anyway is the point, because a written-down opinion can be tested and a vague one cannot.
Save this as dataset.py.
import weave

weave.init("prompt-versioning-demo")

rows = [
{"ticket": "I was charged twice for my October subscription. Can you refund the duplicate?",
"label_category": "billing", "label_priority": "high"},
{"ticket": "The invoice PDF for last month has the wrong VAT number on it.",
"label_category": "billing", "label_priority": "low"},
{"ticket": "Can you tell me when my next payment is due?",
"label_category": "billing", "label_priority": "low"},
{"ticket": "My card was declined but the dashboard still says active. Which is it?",
"label_category": "billing", "label_priority": "medium"},
{"ticket": "I've been locked out after too many login attempts.",
"label_category": "account_access", "label_priority": "high"},
{"ticket": "The password reset email never arrives. I've tried four times.",
"label_category": "account_access", "label_priority": "high"},
{"ticket": "How do I add a second admin to my workspace?",
"label_category": "account_access", "label_priority": "low"},
{"ticket": "Our SSO login redirects to a blank page since this morning.",
"label_category": "account_access", "label_priority": "high"},
{"ticket": "Exporting a report crashes the tab every time, on Chrome and Firefox.",
"label_category": "bug", "label_priority": "high"},
{"ticket": "The date filter shows yesterday's data when I pick today.",
"label_category": "bug", "label_priority": "medium"},
{"ticket": "Minor thing: the tooltip on the settings gear is cut off on mobile.",
"label_category": "bug", "label_priority": "low"},
{"ticket": "Charts render blank if the dataset has more than 50k rows.",
"label_category": "bug", "label_priority": "high"},
{"ticket": "Would love a dark mode for the dashboard.",
"label_category": "feature_request", "label_priority": "low"},
{"ticket": "Any chance of a Slack integration for alerts?",
"label_category": "feature_request", "label_priority": "low"},
{"ticket": "We need per-seat usage reporting before we renew in January.",
"label_category": "feature_request", "label_priority": "medium"},
{"ticket": "Can you add CSV export to the audit log page?",
"label_category": "feature_request", "label_priority": "low"},
{"ticket": "Just wanted to say the new onboarding flow is much better.",
"label_category": "other", "label_priority": "low"},
{"ticket": "Who should I contact about a partnership?",
"label_category": "other", "label_priority": "low"},
{"ticket": "Is your service affected by the outage I read about this morning?",
"label_category": "other", "label_priority": "medium"},
{"ticket": "I need a copy of our signed data processing agreement.",
"label_category": "other", "label_priority": "medium"},
]

dataset = weave.Dataset(name="triage_eval_v1", rows=rows)
weave.publish(dataset)
Datasets are versioned objects too, on exactly the same model as prompts. Add five rows next month, publish under the same name, and you get a second version with both histories intact. This matters more than it sounds: when your scores jump, the first question is always whether the system got better or the test got easier, and versioned datasets answer it.
Screenshot by Author. The twenty labeled tickets stored as a versioned dataset object, with the two label columns the scorers read by name.
Now the scorers. A scorer is a function decorated with @weave.op that returns a dictionary. Weave calls it once per row and then aggregates, summarizing booleans as a count and a fraction, so returning a boolean gives you an accuracy for free. Save this as scorers.py.
import weave

PRIORITY_ORDER = {"low": 0, "medium": 1, "high": 2}


@weave.op()
def category_match(label_category: str, output: dict) -> dict:
return {"correct": output["category"] == label_category}


@weave.op()
def priority_match(label_priority: str, output: dict) -> dict:
return {"correct": output["priority"] == label_priority}


@weave.op()
def over_escalation(label_priority: str, output: dict) -> dict:
"""Fires when the model assigns a higher priority than the label."""
predicted = PRIORITY_ORDER.get(output["priority"], -1)
actual = PRIORITY_ORDER.get(label_priority, -1)
return {"escalated": predicted > actual}
The argument names do real work. output is special and always receives whatever predict returned. If you are copying from an older tutorial you may see model_output instead, which is the deprecated name for the same thing. Every other argument name gets matched against a column in the dataset row, which is why the labels are spelled label_category and label_priority in both places. Get one of those names wrong and the scorer fails at runtime complaining about a missing argument, which is the most common way a first Weave evaluation falls over. If you would rather keep column names and scorer signatures independent, a class-based scorer accepts a column_map.
That third scorer is the one to watch. The first two are accuracy metrics and they answer "how often was it right". The third answers "when it was wrong, which way did it lean", and by the end of this tutorial it is the only metric that catches the thing we are looking for.

Step 4: Run the baseline evaluation

One weave.Evaluation holds the dataset and the scorers. You then run it against as many models as you like, and because the evaluation definition stays fixed, results are directly comparable.
Save this as evaluate.py.
import asyncio
import json
import sys

import weave

from scorers import category_match, priority_match, over_escalation
from triage import TriageModel

_evaluation = None


def get_evaluation() -> weave.Evaluation:
global _evaluation
if _evaluation is None:
_evaluation = weave.Evaluation(
name="triage_regression_suite",
dataset=weave.ref("triage_eval_v1").get(),
scorers=[category_match, priority_match, over_escalation],
)
return _evaluation


def run(prompt_ref: str) -> dict:
weave.init("prompt-versioning-demo")
model = TriageModel(prompt_ref=prompt_ref)
return asyncio.run(get_evaluation().evaluate(model))


if __name__ == "__main__":
prompt_ref = sys.argv[1] if len(sys.argv) > 1 else "triage_prompt:v0"
summary = run(prompt_ref)
print(json.dumps(summary, indent=2, default=str))
Building the evaluation lazily rather than at import time is worth the four extra lines. check_regression.py imports run from this module in Step 9, and an import that reaches out to resolve a dataset reference fails in confusing ways when the dataset has not been published yet.
python evaluate.py triage_prompt:v0
Which outputs:
{
"category_match": {"correct": {"true_count": 18, "true_fraction": 0.9}},
"priority_match": {"correct": {"true_count": 10, "true_fraction": 0.5}},
"over_escalation": {"escalated": {"true_count": 10, "true_fraction": 0.5}},
"model_latency": {"mean": 2.2276086688041685}
}
🍩 https://wandb.ai/your-entity/prompt-versioning-demo/r/call/019fdb7f...
Category comes in at 0.90 with almost no help. A five-way classification over short, unambiguous tickets is not hard, and a bare list of valid values gets most of the way there. Priority is a coin flip at 0.50, and half of all twenty tickets came back rated higher than the label says they should be. The model has no rule for what makes something urgent, so it is reading urgency in how the customer wrote the ticket.
Print that summary dictionary once and read it carefully. The nesting goes scorer name, then metric name, then the aggregation Weave chose, and that exact key path is what the CI gate indexes into in Step 9. Reading it off real output beats guessing.
Follow the link at the end. It opens the evaluation in the W&B Weave UI, where you can sort the twenty rows by score and read the failures. That is usually more informative than the aggregate.
Each row expands into the full trace of the call that produced it, which is where the @weave.op() decorator pays off. You get the exact messages sent, the raw response, token counts, and latency, all attributable to one prompt version.

Step 5: Publish v1 and measure the improvement

The failures point at the fix. The model has no rule for what makes something high priority, so it falls back on how urgent the ticket sounds. So we give it one, along with definitions for each category.
Add this to prompts.py and run it again.
triage_v1 = weave.MessagesPrompt([
{
"role": "system",
"content": (
"You are a support triage assistant for a B2B analytics product. "
"Read the ticket and return JSON with two keys: category and priority.\n\n"
"Categories:\n"
"- billing: charges, invoices, refunds, payment methods, renewal pricing\n"
"- account_access: login, passwords, SSO, seats, permissions\n"
"- bug: the product behaves differently from how it is documented\n"
"- feature_request: something the product does not do yet\n"
"- other: anything else, including partnerships, compliance paperwork "
"and general feedback\n\n"
"Priority is about blast radius, not tone. Use high when a customer "
"cannot work or when money moved incorrectly. Use medium when there is "
"a workaround or a deadline within a month. Use low for anything "
"cosmetic, informational or wishlist."
),
},
{"role": "user", "content": "{ticket}"},
])

ref_v1 = weave.publish(triage_v1, name="triage_prompt")
print("published:", ref_v1.uri())
And then:
python evaluate.py triage_prompt:v1
Which outputs:
{
"category_match": {"correct": {"true_count": 20, "true_fraction": 1.0}},
"priority_match": {"correct": {"true_count": 14, "true_fraction": 0.7}},
"over_escalation": {"escalated": {"true_count": 4, "true_fraction": 0.2}},
"model_latency": {"mean": 1.5822437286376954}
}
Category goes from 0.90 to a clean sweep. Priority climbs from 0.50 to 0.70. The largest move is over-escalation, which falls from 0.50 to 0.20: ten tickets were rated too high before, and now four are. That is the sentence about blast radius doing its work, replacing a vague word the model has to guess at with a test it can apply.
Strictly, v1 changes two things at once, the category definitions and the priority rule, and if the definitions had mattered we would not know which edit earned the gain. Publishing them as separate versions is what this workflow is for, and on a longer prompt it is what I would do.
Two more things worth sitting with. Priority at 0.70 is still not good, and pretending otherwise would be dishonest. There is more prompt engineering to do here, and the point of this article is the workflow rather than the final score. More interesting is that category has hit its ceiling and stays at 1.00 for every remaining version in this tutorial. A metric pinned at the top tells you nothing about any future change, in either direction. Suites accumulate metrics like this, and the discipline is noticing which ones have stopped discriminating before you start trusting them.
Open the run and you get the three scorers summarized on one side and the twenty examples on the other, sorted most-failing-first so the disagreements surface without hunting.
Screenshot by Author. The v1 evaluation, with all three scorers summarized on the left and the examples sorted most-failing-first on the right.
The prompt name has not changed. Both bodies live under triage_prompt, as v0 and v1, and both stay loadable forever.

Step 6: Publish v2 and watch the regression

Here is the part worth staying awake for.
Imagine the support lead reads the evaluation, sees two tickets that should have been high and came back medium, and sends a perfectly reasonable Slack message: can we make it err on the side of caution? So you add one sentence. It is defensive, it is well-intentioned, and it would pass any code review in the world.
triage_v2 = weave.MessagesPrompt([
{
"role": "system",
"content": (
triage_v1.messages[0]["content"]
+ "\n\nIf you are unsure about priority, choose high so that nothing "
"important gets missed."
),
},
{"role": "user", "content": "{ticket}"},
])

ref_v2 = weave.publish(triage_v2, name="triage_prompt")
And then:
python evaluate.py triage_prompt:v2
Which outputs:
{
"category_match": {"correct": {"true_count": 20, "true_fraction": 1.0}},
"priority_match": {"correct": {"true_count": 13, "true_fraction": 0.65}},
"over_escalation": {"escalated": {"true_count": 6, "true_fraction": 0.3}},
"model_latency": {"mean": 1.5148249864578247}
}
Read those three lines in order, because the order is the lesson.
Category is unchanged at 1.00 and reports nothing, exactly as predicted. Priority accuracy slips from 0.70 to 0.65, which is one ticket out of twenty. On its own that is indistinguishable from noise, and if priority accuracy were your only metric you would ship this without a second thought. Over-escalation is where the damage shows: it climbs from 0.20 to 0.30, giving back a third of everything v1 gained.
That gap between the two priority metrics is the whole point. Accuracy tells you how often the model was wrong. It says nothing about which direction wrong went, so a change that shifts every borderline call the same way barely moves it. The directional metric moves immediately, because shifting borderline calls in one direction is precisely what it measures.
What happened is that "unsure" has no threshold in it. A language model is unsure about almost everything, at least a little, so an instruction to escalate under uncertainty is functionally an instruction to escalate. The dark mode request comes back as high priority. So does the tooltip that is cut off on mobile.
Sit with how this would have gone without the evaluation. Nothing errors. Every response is valid JSON with valid values. A spot check on three tickets looks fine, because on a genuinely urgent ticket the answer is still correct. Structured outputs would not have caught it, and neither would a type checker, because the failure is a shift in a judgment boundary rather than a malformed response. You find out when a customer asks why their cosmetic bug report paged an engineer at midnight.
The honest footnote is that this regression is smaller than the story usually told about prompt edits, and that is worth knowing rather than hiding. One sentence moved two tickets. It did not break the app, and on twenty rows it barely clears the noise floor. Real regressions often look like this, which is the argument for having the suite rather than against it: a change you can only see at the aggregate level is exactly the change no reviewer catches.

Step 7: Compare prompt versions in the W&B Weave UI

Open the project at wandb.ai. In the Weave project sidebar, click Assets, then Prompts. Your project's prompts are listed there, and the Versions column shows how many versions each one has. Click the version count for triage_prompt and you get all three.
Screenshot by Author. Three immutable versions under one name, each independently loadable forever. The production alias on v1 gets set in the next step.
Tick the checkboxes beside two versions and click Compare in the table toolbar. You get a line-level diff between the two prompt bodies, which for v1 against v2 is a single added sentence.
Screenshot by Author. The entire difference between a working prompt and a regressed one is the single highlighted line, which is exactly why it needed measuring rather than reviewing.
The evaluation comparison is the other half of the picture. From the Evals tab you get every run in one table, with each scorer as its own column. Reading the diff and the score change next to each other is the moment the whole workflow justifies itself.
Screenshot by Author. Every run against the fixed suite in one table, with each scorer as its own column. The model version encodes which prompt reference produced each row.

Step 8: Promote and roll back with aliases and tags

Because the application loads its prompt by reference, pointing production at v1 takes one line and no deploy. Save this as promote.py.
import weave
from weave.trace.refs import ObjectRef

client = weave.init("prompt-versioning-demo")


def resolve(version: str) -> ObjectRef:
"""Turn a version index into a ref carrying a real content digest.

weave.ref("triage_prompt:v1") builds a ref whose digest is the literal
string "v1". Reads accept that, but the alias and tag endpoints want a
content digest and return 404 otherwise. Loading the object gives back
a ref with the digest filled in.
"""
return weave.ref(version).get().ref


v1 = resolve("triage_prompt:v1")
v2 = resolve("triage_prompt:v2")
print("v1 digest:", v1.digest)
print("v2 digest:", v2.digest)

# Point production at the version that actually scored well.
client.set_aliases(v1, "production")

# Leave a note on the bad version so nobody promotes it again by accident.
client.add_tags(v1, ["reviewed", "passed-eval"])
client.add_tags(v2, ["over-escalates", "failed-eval"])

print("\naliases on v1:", client.get_aliases(v1))
print("all aliases in project:", client.list_aliases())
print("tags on v2:", client.get_tags(v2))
And this should output:
v1 digest: IdK4VpztVS4rT3jMADAYX2i4DhlfroL61SWiF2N6gWM
v2 digest: YxY34qzD0vEzBD9O13k1qzXVxgdxgLfhNXhbR0emIe4

aliases on v1: ['production']
all aliases in project: ['latest', 'production']
tags on v2: ['failed-eval', 'over-escalates']
That resolve helper is the non-obvious part, and it is worth the docstring. A ref built from a version index carries the string v1 where a digest should be, and the alias endpoints reject it with a 404 that says the object version was not found. Reads tolerate the index form, writes do not. Loading the object and taking its .ref gives you one with the content digest filled in.
Note that the project has two aliases and v1 holds only one of them. latest is on v2, because it always follows the most recent publication regardless of quality. That is the whole reason production exists as a separate pointer: one alias tracks recency and the other tracks what you have actually decided to run.
An alias resolves to exactly one version at a time, so setting production on v1 detaches it from wherever it was pointing. Tags work the other way: a version can carry several, and they stay attached permanently. The practical division is that aliases answer "what is running right now" and tags answer "what did we learn about this one".
Both can also be set at publication time, which is tidier when you already know what a version is for: weave.publish(prompt, name="triage_prompt", tags=["reviewed"], aliases=["staging"]).
With the alias set, the model from Step 2 can take prompt_ref="triage_prompt:production" and follow whatever you promote. Your rollback becomes a set_aliases call rather than a revert, a build, and a deploy.
Both controls also live in the UI, on the prompt detail panel, which is what you want when the person deciding to roll back is on the support team rather than the engineering one.
Screenshot by Author. Tags surface on the Prompts page, so a version that failed evaluation carries that label everywhere it appears.
The honest trade is that your running behavior is now controlled by something outside your repository. Someone with project access can change production without a pull request, so alias moves belong in an audit trail and behind whatever access controls the change deserves. If you need heavier governance than that, prompt objects can be linked into a Registry collection, which brings approval workflows with them.

Step 9: Gate the suite in CI

Everything so far has been you deciding to run the suite. That works right up until the afternoon somebody edits a prompt, is confident it is an improvement, and pushes it. A gate moves that decision off the person and into the pipeline.
The idea is the one you already use for tests. On every change that touches a prompt, CI runs the twenty tickets through the candidate version, scores them, and compares the result against the numbers your current production version achieved. If any score has dropped by more than a set tolerance, the job exits non-zero and the merge is blocked. If nothing has dropped, it passes silently and nobody thinks about it again.
That needs two files. check_regression.py runs the comparison and decides pass or fail, and write_baseline.py records the numbers it compares against. Building them separately is what makes the second half of this step interesting, because deciding when to move a baseline turns out to be a judgment call rather than an automation problem.
The gate compares a fresh run against a stored baseline. Save it as check_regression.py.
import json
import sys
from pathlib import Path

from evaluate import run

TOLERANCE = 0.05 # one row out of twenty

# (scorer, metric, direction) where +1 means higher is better.
CHECKS = [
("category_match", "correct", +1),
("priority_match", "correct", +1),
("over_escalation", "escalated", -1),
]


def fraction(summary: dict, scorer: str, metric: str) -> float:
"""Pull the true_fraction out of Weave's nested summary dict."""
return summary[scorer][metric]["true_fraction"]


def main(prompt_ref: str) -> int:
baseline = json.loads(Path("baseline.json").read_text())
summary = run(prompt_ref)

failures = []
for scorer, metric, direction in CHECKS:
current = fraction(summary, scorer, metric)
previous = baseline[scorer][metric]
delta = (current - previous) * direction

status = "ok" if delta >= -TOLERANCE else "REGRESSION"
print(f"{status:>10} {scorer}.{metric}: {previous:.2f} -> {current:.2f}")

if delta < -TOLERANCE:
failures.append(f"{scorer}.{metric}")

if failures:
print(f"\nBlocking: {', '.join(failures)} regressed beyond tolerance.")
return 1

print("\nAll metrics within tolerance.")
return 0


if __name__ == "__main__":
# Defaults to :latest because the CI case is "gate whatever was just
# published". Pass an explicit version when running it by hand.
ref = sys.argv[1] if len(sys.argv) > 1 else "triage_prompt:latest"
sys.exit(main(ref))
The direction field lets one loop handle metrics that move opposite ways. Accuracy going up is good; escalation rate going up is bad. Multiplying the delta by the direction turns both into the same comparison and saves you from a special case someone will eventually get backwards.
The baseline it reads is a flattened version of the summary, holding one float per metric rather than the nested aggregation dict:
{
"category_match": {"correct": 1.0},
"priority_match": {"correct": 0.7},
"over_escalation": {"escalated": 0.2}
}
Write it from a run you have decided to accept rather than by hand. Save this as write_baseline.py:
import json
import sys
from pathlib import Path

from check_regression import CHECKS, fraction
from evaluate import run

summary = run(sys.argv[1])
baseline: dict = {}
for scorer, metric, _ in CHECKS:
baseline.setdefault(scorer, {})[metric] = round(fraction(summary, scorer, metric), 4)

Path("baseline.json").write_text(json.dumps(baseline, indent=2) + "\n")
print(json.dumps(baseline, indent=2))
Keeping this separate from the gate is deliberate. Every time you accept an improvement you are also accepting a new floor, and that should be a decision rather than a side effect of running the check.
python write_baseline.py triage_prompt:v1
python check_regression.py triage_prompt:v2
echo $?
Which outputs
ok category_match.correct: 1.00 -> 1.00
REGRESSION priority_match.correct: 0.70 -> 0.60
REGRESSION over_escalation.escalated: 0.20 -> 0.35

Blocking: priority_match.correct, over_escalation.escalated regressed beyond tolerance.
1
Non-zero exit, so the pipeline stops.
Compare those numbers against the v2 evaluation back in Step 6, which came out at 0.65 and 0.30. Same prompt, same dataset, same temperature=0, one row different on each metric. That is not a mistake in either run, it is what this looks like at twenty rows, and it is the reason the tolerance exists.
Which brings us to why 0.05 and not something rounder. On twenty rows, one row is exactly 0.05, so the gate tolerates a single example flipping and nothing more. Across seven runs of the same three prompts, that is precisely what the movement was: v0 was identical twice, v1 sat at 0.70 priority three times and 0.65 once, v2 at 0.30 escalation twice and 0.35 once. Never more than one row, and usually none.
Two consequences worth taking away. Set your tolerance from your own measured spread rather than from this article, since the right number depends on your dataset size and your model. And notice how close this gate came to missing the regression: on the Step 6 numbers, priority accuracy drops exactly one row and passes, so over_escalation is doing all the work. Twenty rows with one directional metric is the minimum viable version of this, not a comfortable one. The first thing I would do before trusting it in production is grow the dataset, because every row you add buys resolution the tolerance can use.

Conclusion

What you have built is small: a prompt published as a versioned object, twenty labeled tickets, three scorer functions, and a script that fails the build when a score drops. It took an afternoon, and it was enough to catch a one-sentence prompt edit that passed review, broke nothing, and quietly moved two tickets to the wrong priority. If your team ships an LLM feature and has none of this, the honest advice is to build it before you need it rather than during the incident that proves you needed it.
Prompts change behavior the way code does, so they deserve the same treatment: history you can reference, a test suite that runs on change, and a fast way to undo a bad decision. W&B Weave gives you the first as immutable published objects with aliases and tags, and StringPrompt and MessagesPrompt cover both shapes a prompt actually takes.
Accuracy metrics are the ones everybody writes first, and in this tutorial the accuracy metrics were the ones that missed: category pinned at its ceiling and stopped saying anything, and priority moved one row and shrugged. The metric that caught the regression was the one measuring which direction the errors leaned. When you sit down to write your suite, ask what a bad change would look like rather than what a good one looks like, and write the metric that would see it.
Brett Young
Brett Young •  *
Two things this tutorial leaves out, and you will meet both. Exact-match scoring works here because the triage output is a short structured value; open-ended outputs like summaries or drafted - Avoid ending the article with shortcomings. Any shortcoming in the article should either be fixed or not mentioned.
1 reply
Brett Young
Brett Young •  
e part I would carry into your own project is the third scorer. - I would avoid recommending only one part of the article.
1 reply
Brett Young
Brett Young •  
The gap this closes is specific. Avoid short sentences that aren't stating anything specific.
1 reply
Brett Young
Brett Young •  
A prompt object, twenty labeled rows, and three scorer functions. That is the smallest thing that works, it takes an afternoon, and it catches a change no reviewer would have flagged. - A bit vague what is meant here.
1 reply
Brett Young
Brett Young •  
Step 10: Gate the suite in CIRunning the suite by hand catches regressions only when someone remembers. Wiring LLM evaluation into CI catches them every time.The gate compares a fresh run against a stored baseline. Save it as check_regression.py.import jsonimport sysfrom pathlib import Path - Again its not clear what the objective of the section is. Please explain in the intro of the section what the purpose of the section is.
1 reply
Brett Young
Brett Young •  
This scorer stays out of the suite we have been running, deliberately. Adding it would make the v0, v1, and v2 numbers non-comparable with everything above, and it depends on an object that does not exist until this step. A new metric usually deserves a new baseline rather than a retrofit into an old one.The brace hazard from Step 2 disappears. You control format now, so the ticket text goes into the message directly rather than through str.format, and a customer who writes JSON in their support ticket no longer breaks your prompt. That last one is not hypothetical for anyone running a developer-facing product.Note the new name. This is a different object class, so it gets its own history rather than becoming v3 of triage_prompt. Migrating means publishing it, evaluating it, and moving the production alias only if it scores at least as well as what it replaces. The application code does not change at all, since weave.ref(...).get() returns whatever class was published and format(ticket=...) returns messages either way.python evaluate.py triage_prompt_structured:v0Which outputs: { "category_match": {"correct": {"true_count": 20, "true_fraction": 1.0}}, "priority_match": {"correct": {"true_count": 14, "true_fraction": 0.7}}, "over_escalation": {"escalated": {"true_count": 4, "true_fraction": 0.2}}, "model_latency": {"mean": 1.8478824496269226}}Identical to v1 on all three metrics, which is the point. The restructure was for maintainability rather than quality, and now you have evidence that it cost you nothing rather than a hope that it did not. Promote it with the same set_aliases call from Step 8. - Please rewrite this section to make it flow a bit better. I'm not sure exactly what the main objective of this section is.
Reply
Brett Young
Brett Young •  
The reason StringPrompt and MessagesPrompt need none of this is that Weave registers them at import time. Your subclass is not in that registry until you put it there, so the requirement is a consequence rather than an arbitrary rule.Two practical notes. register_object raises ValueError: Class TriagePrompt already registered if the class is registered twice, which happens if you re-run a notebook cell or import the module under - getting too into the weeds here.
Reply
Brett Young
Brett Young •  
Step 9: Build a custom prompt class when the built-ins run outLook again at the v1 prompt. Most of it is a category taxonomy, and that taxonomy is data pretending to be prose. Any code that wants to know the valid categories has to either duplicate the list or parse it out of a string, and a diff between two versions shows a wall of text where the real change was "we added a category".Subclassing weave.Prompt fixes that. You declare the structured parts as fields and override format to assemble the messages. Save this as structured_prompt.py.from __future__ import annotationsfrom typing import Anyimport weavefrom weave.trace.objectify import register_object@register_objectclass TriagePrompt(weave.Prompt): role_description: str categories: dict[str, str] priority_rule: str def format(self, **kwargs: Any) -> list[dict]: catalog = "\n".join( f"- {name}: {description}" for name, description in self.categories.items() ) system = ( f"{self.role_description}\n\n" f"Read the ticket and return JSON with two keys: category and priority.\n\n" f"Categories:\n{catalog}\n\n" f"{self.priority_rule}" ) return [ {"role": "system", "content": system}, {"role": "user", "content": kwargs["ticket"]}, ] @classmethod def from_obj(cls, obj: Any) -> TriagePrompt: """Rebuild an instance from a stored object.""" prompt = cls( role_description=obj.role_description, categories=dict(obj.categories), priority_rule=obj.priority_rule, ) prompt.name = obj.name prompt.description = obj.description return promptSTRUCTURED = TriagePrompt( role_description="You are a support triage assistant for a B2B analytics product.", categories={ "billing": "charges, invoices, refunds, payment methods, renewal pricing", "account_access": "login, passwords, SSO, seats, permissions", "bug": "the product behaves differently from how it is documented", "feature_request": "something the product does not do yet", "other": "partnerships, compliance paperwork, general feedback", }, priority_rule=( "Priority is about blast radius, not tone. Use high when a customer cannot " "work or when money moved incorrectly. Use medium when there is a workaround " "or a deadline within a month. Use low for anything cosmetic, informational " "or wishlist." ),)if __name__ == "__main__": weave.init("prompt-versioning-demo") print("published:", weave.publish(STRUCTURED, name="triage_prompt_structured").uri())Two pieces here are easy to miss, and skipping either produces the same confusing failure. @register_object puts the class in Weave's deserialization registry, and from_obj tells Weave how to rebuild an instance from the stored fields. Without both, weave.ref(...).get() hands back an objec - I would avoid making subclasses of our prompt to avoid the default syntax (if I understand correctly)
Reply
Brett Young
Brett Young •  
The fully qualified weave:///... form carries its own entity and project and works without it. - Unclear what is meant here
1 reply
Brett Young
Brett Young •  
triage_prompt:v0 only means Probably best to explain what this means exactly.
1 reply
Brett Young
Brett Young •  
That weave.init line is not decoration - Avoiud the "X is not Y." pattern
1 reply
Brett Young
Brett Young •  
Step 2: Parameterize the prompt and load it by referenceA prompt with a placehold - Parameterize hasn't been introduced yet as a concept.
1 reply
Brett Young
Brett Young •  
parameterize, reference, and promote Its a bit unclear what this means so you may want to reword it before you explain everything you will be able to do.
1 reply
Brett Young
Brett Young •  
two reasonable engineers will disagree on a handful of them Again this is abstract, please rephrase
1 reply
Brett Young
Brett Young •  
labels are opinions Not always.
1 reply
Brett Young
Brett Young •  
Twenty rows catch coarse regressions and miss subtle ones. Unclear what 20 is here. It feels a bit abstract.
1 reply
Brett Young
Brett Young •  
Now the honest part - Avoid this as it implies the rest is dishonest
1 reply
Brett Young
Brett Young •  
you believe the right answer is - Again I would be more precise about what this is.
1 reply
Brett Young
Brett Young •  
the last known-good numbers - We can be a bit more precise with the wording here.
1 reply
Brett Young
Brett Young •  
out that their prompts already live in Git, and that is true and it beats nothing. It is also where the industry is heading. On June 3, 2026, OpenAI deprecated reusable prompt objects in its API, with v1/prompts shutting down on November 30, 2026, and deprecated its hosted Evals platform on the same day. Its migration guide tells developers to move prompt content into their application code and version it with Git commits, pull request review, and tests. That advice is right as far as it goes, and it is exactly the gap this article opened with: a commit tells you what changed and who changed it, never whether it helped. What follows keeps the review and the CI gate OpenAI is pointing at, and adds the one thing a commit history cannot give you, which is a link from a prompt version to the quality scores it produced. It also adds a second thing Git cannot do, which is changing the prompt version production uses without shipping code. That one - I think we can avoid mentioning OpenAI here.
1 reply
Brett Young
Brett Young •  
is true and it beats nothing Re-word, I'm not sure I understand fully.
1 reply
Iterate on AI agents and models faster. Try Weights & Biases today.