Articles

Prompt Registry Design for Teams Shipping LLM Features

A prompt registry design you can build: schema, immutable versions, labels, runtime fetch with cache and fallback, rollback, and an eval gate for promotion.

· 11 min read
prompt-registry prompt-versioning prompt-version-control prompt-templates llmops python
A fanned hand of four locked prompt version cards, v1 to v4, with the Production label tag moved from v1 to v4.
Table of Contents

An engineer adds “order” to the keyword list in the order-routing prompt so more shipping emails reach the shipping team. Soon invoices that mention an order number land there too. The prompt lives in a Python string, so undoing one line takes a review, a build and a deploy.

Nobody knows which wording is live where or who changed it, and switching back to the old wording means shipping code. A prompt registry design fixes that. It stores each prompt as data your app reads at runtime, apart from your code release.

The build below stores the fields, fetches each prompt by label with a cache and a fallback, rolls back by moving a label and demonstrates a single-writer promotion gate. That gate catches this exact edit. Three small files on Python’s sqlite3 cover it, with full run output.

TL;DR

  • A prompt registry design stores immutable versions (template, variables, model settings, author, change note) and movable labels that point at one version each.
  • Your app fetches by label, caches for a fixed time, and keeps the last good copy if the registry stops answering.
  • Rollback moves a label back; each process follows on a successful fetch after cache expiry. An outage can keep the rolled-back version cached indefinitely.
  • With one writer, the gate promotes a new version only if it beats the current one on a fixed dataset and breaks no row the current one passes.
  • The change log records who made each label move and why.
  • Git alone covers prompt version control until a rollback has to beat your deploy time or a trace has to name the prompt version.

The data model behind a prompt registry design

A registry needs three tables. A version holds the template text, its variable names, the model settings, the author, a change note and free-form metadata, and nobody edits it once written. A label points a name like Production at one version. The log records every label move.

TableFieldsRule it enforces
versionsname, version, template, variables, model_settings (model, temperature, any tool or response schema), author, change_note, metadata, created_atUpdate, delete and replacement inserts blocked by triggers
labelsname, label, versionOne version per label
label_logfrom_version, to_version, actor, reason, gate_result, atAppend only in code

Teams who would rather buy than build can start from prompt registry tools compared side by side.

Prompt templates and their variables

The running example, order-router, sorts customer emails into shipping, billing, returns or other. Its template is plain text with {{email}} where the message goes, and each version stores its variable names, so a caller can check inputs before rendering. Add types beside the names if needed.

A tool definition or a JSON response schema for structured output belongs in the version too, inside model_settings. A schema edit then ships as a new version with the text. The wording and the schema it was written for always ship and roll back together.

Model settings, author and change note

model_settings holds the model, the temperature and any tool or response schema; the demo stores a model name and a temperature. Swapping the model also creates a new version. Author and change note say who changed what and why, and metadata keeps tags, owner and ticket.

Immutable versions and movable labels

Prompt versioning only works if a version never changes after it is written. Edit version 3 in place and every eval score and trace tied to it now describes text that no longer exists. Labels carry the change. You move Production from one version to another and leave the versions alone.

What prompt versioning means and why it matters covers the concept itself.

The example registry enforces this in the database. Triggers abort UPDATE, DELETE and inserts over an existing version, including INSERT OR REPLACE. The demo’s attempt to overwrite version 1 gets “versions are immutable” back. A wrong prompt gets fixed with a new, higher version.

Labels are the only state that changes. The labels table keys on prompt name and label, so each label points at exactly one version; in this example schema a version may carry several labels. A move is one upsert plus one log row.

Environments are labels

Development, Staging and Production are three label rows on one prompt name. Each environment’s app asks for its own label. In the demo, v2 sits on Staging as a “candidate under review” and is meant to reach Production only through the gate. A canary adds one more label row.

State diagram of the Development, Staging and Production labels on one prompt, where a candidate on Staging moves to Production only if it passes the promotion gate and otherwise holds

Fetching a prompt at runtime by label

Your app asks the registry for a prompt name and a label, then renders the template with its variables. A cache with a fixed time to live sits in front of that call, the call gets a short timeout, and when a fetch fails the app keeps serving the copy it already holds and logs it as stale.

The timeout lives in your source callable, such as your HTTP client; the demo fakes an outage by raising TimeoutError. CachedFetcher tags every copy it serves live, cache or stale. For a fresh process with nothing cached, keep a default prompt in code.

The cache time is your rollback delay

With successful refreshes, cache time bounds staleness: the next fetch after expiry picks up a label move. An outage removes that bound because this demo serves stale entries without an age limit.

Carol moves Production to v2 by hand, and the app fetches v2 live at t=0s. Bob rolls back to v1 that second, yet at t=30s the app still serves v2 from cache. At t=61s, past the 60 second time to live, it fetches v1.

4. someone skips the gate, then a runtime fetch by label with a 60 second cache
  carol moves Production -> v2 by hand (no gate result)
  t=0s    app fetches Production -> v2 (live)
  t=0s    rollback: Production -> v1 in the registry
  t=30s   app fetches Production -> v2 (cache)
  t=61s   app fetches Production -> v1 (live)

5. registry down
  t=130s  app fetches Production -> v1 (stale)
  cold start, nothing cached: TimeoutError(registry did not answer) -> caller uses its baked-in default

Pick the time to live by how long you can tolerate a bad version after a rollback while refreshes succeed. The demo’s 60 seconds is an example value. Shorter means more registry calls; longer means more requests answered by a version you rolled back. A hard outage limit needs a separate maximum stale age and safe-default or fail-closed policy.

When the registry stops answering

At t=130s the demo takes the registry down. The cached v1 entry has expired, the fetch raises, and the app serves v1 marked stale. A cold process with nothing cached gets TimeoutError("registry did not answer") and uses the default prompt in its code.

Here the rollback reached the cache before the outage. If the outage started while v2 was still cached, the app would keep serving v2 beyond the TTL, despite the label pointing at v1.

Rollback and the audit trail in a prompt registry design

Rolling back moves the label to the version it held before, in one transaction that also writes the log row. Nothing is rebuilt and no text is edited. Because each log row keeps the old version, the new version, who moved it and why, the same table tells you what was live on any past date.

rollback() reads the latest log row and moves the label to its from_version. That undoes the last move. To go further back, call move_label with the older version. In the run, Alice releases v1, Carol moves Production to v2 by hand, Bob rolls back, then promotes v4.

8. label change log for Production
  #1 start -> v1 by alice: initial release
  #3 v1 -> v2 by carol: manual move, gate skipped: courier emails piling up
  #4 v2 -> v1 by bob: v2 misroutes invoices that mention an order number
  #5 v1 -> v4 by bob: gate pass on 10 rows [candidate v4=1.00 current v1=0.70, no new failures]

If a prompt shipped with a new tool schema, roll back to a version whose model_settings hold the old schema too. That restores text and schema as a pair. Moving only the text back leaves the old wording facing a schema it was never written for.

Timeline of order-router label_log rows 1, 3, 4 and 5 pointing the Production label at v1, then v2, then v1 again, then v4, each row tagged with who made the move and why

An append-only change log

label_log stores from_version, to_version, actor, reason, gate_result and a timestamp. The registry code never updates or deletes its rows. A manual move stores NULL for gate_result, so Carol’s skipped gate shows as row #3 with no scores. Row #2 was the Staging move.

A promotion gate that a new version must pass

A candidate version moves the Production label only if it scores higher than the current version on the same fixed dataset and gets right every row the current version already gets right. Write the dataset, the metric, both checks and the approver down before the run, so nobody tunes them to the result.

This demo requires a single writer across version creation, evaluation, promotion and rollback. It has no concurrency guarantee: another writer can change Production during evaluation, and the gate can overwrite that newer release. Before sharing it among concurrent writers, add an atomic baseline check to the label move and re-evaluate if the baseline changed.

v2 adds keywords, “order” among them, and scores 0.90 against 0.70 for v1, passing check 1. Check 2 fails on row 4, “Please resend the invoice for order 4412 with our VAT number.”, which v2 sends to shipping. Production stays on v1.

3. promotion gate: beat current on the same rows, break none it gets right
  candidate v2 for Production, approver: bob
  check 1 score: candidate v2=0.90 current v1=0.70 -> PASS
  check 2 no new failures: row 4 'Please resend the invoice for order 4412 with our VAT number.' -> FAIL
  gate: HOLD, label stays
  candidate v3 for Production, approver: bob
  check 1 score: candidate v3=0.60 current v1=0.70 -> FAIL
  check 2 no new failures: row 4 'Please resend the invoice for order 4412 with our VAT number.' -> FAIL
  gate: HOLD, label stays
  Production -> v1

v3 puts order in its shipping rules and fails both checks. After the rollback, v4 keeps v2’s keywords minus “order”, scores 1.00 against 0.70 and moves Production. A score-only gate would have shipped the opening bug: v2 gained rows 6, 7 and 8 and lost row 4.

The higher-score check and the no-regression check

Both versions run on the same 10 synthetic order emails, scored by exact match. Check 1 requires a strict win; add a margin once your dataset is large enough. Check 2 is a per-row diff: a row the current version passes and the candidate fails holds the move.

gate.py prints each broken row by its text, so the reviewer reads the email. The approver’s name goes into label_log. The stand-in model is a deterministic keyword matcher, so scores repeat every run and say nothing about real model accuracy.

For confidence intervals and the rest of the lifecycle, see statistical gates and the full prompt lifecycle, and for where the check sits in a pipeline, see running eval gates inside an agent CI/CD pipeline.

The full code

registry.py, gate.py and demo.py, the three blocks below in that order, use only the Python standard library and need SQLite 3.24 or newer. Run python3 demo.py in their folder; the output below is that run, tested end to end.

This is a single-writer, text-only gate demo. For live prompts, pass each full version record through row_results to your model adapter, render its variables, and use its stored model_settings, including model, temperature, tools and response schema. Swapping only stand_in_model does not test that versioned bundle. Idempotent schema creation supports reopening a file database; it is not a migration system.

"""Minimal prompt registry on the Python standard library (sqlite3).

Three tables: versions (immutable), labels (movable pointers), label_log
(append-only change log). A cached fetcher sits in front of it.
Single-writer demo: callers must serialize version creation and label changes.
"""
import json
import sqlite3
import time

SCHEMA = """
CREATE TABLE IF NOT EXISTS versions (
    name           TEXT    NOT NULL,
    version        INTEGER NOT NULL,
    template       TEXT    NOT NULL,
    variables      TEXT    NOT NULL,  -- JSON list of variable names
    model_settings TEXT    NOT NULL,  -- JSON object (model, temperature, ...)
    author         TEXT    NOT NULL,
    change_note    TEXT    NOT NULL,
    metadata       TEXT    NOT NULL DEFAULT '{}',  -- JSON object (tags, owner, ticket, ...)
    created_at     TEXT    NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (name, version)
);
CREATE TRIGGER IF NOT EXISTS versions_no_update BEFORE UPDATE ON versions
BEGIN SELECT RAISE(ABORT, 'versions are immutable'); END;
CREATE TRIGGER IF NOT EXISTS versions_no_delete BEFORE DELETE ON versions
BEGIN SELECT RAISE(ABORT, 'versions are immutable'); END;
CREATE TRIGGER IF NOT EXISTS versions_no_replace BEFORE INSERT ON versions
WHEN EXISTS (SELECT 1 FROM versions WHERE name = NEW.name AND version = NEW.version)
BEGIN SELECT RAISE(ABORT, 'versions are immutable'); END;

CREATE TABLE IF NOT EXISTS labels (
    name    TEXT    NOT NULL,
    label   TEXT    NOT NULL,
    version INTEGER NOT NULL,
    PRIMARY KEY (name, label),        -- one version per label
    FOREIGN KEY (name, version) REFERENCES versions (name, version)
);

CREATE TABLE IF NOT EXISTS label_log (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    name         TEXT NOT NULL,
    label        TEXT NOT NULL,
    from_version INTEGER,             -- NULL on first assignment
    to_version   INTEGER NOT NULL,
    actor        TEXT NOT NULL,
    reason       TEXT NOT NULL,
    gate_result  TEXT,                -- gate summary, NULL for manual moves
    at           TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""


class Registry:
    def __init__(self, path=":memory:"):
        self.db = sqlite3.connect(path)
        self.db.execute("PRAGMA foreign_keys = ON")
        self.db.executescript(SCHEMA)

    def add_version(self, name, template, variables, model_settings, author, change_note, metadata=None):
        """Insert the next version number for `name`. Returns the new version."""
        with self.db:
            (last,) = self.db.execute(
                "SELECT COALESCE(MAX(version), 0) FROM versions WHERE name = ?", (name,)
            ).fetchone()
            self.db.execute(
                "INSERT INTO versions (name, version, template, variables, model_settings,"
                " author, change_note, metadata) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                (name, last + 1, template, json.dumps(variables),
                 json.dumps(model_settings), author, change_note, json.dumps(metadata or {})),
            )
        return last + 1

    def get_version(self, name, version):
        row = self.db.execute(
            "SELECT version, template, variables, model_settings, author, change_note"
            " FROM versions WHERE name = ? AND version = ?", (name, version)
        ).fetchone()
        if row is None:
            raise KeyError(f"{name} v{version} not found")
        return self._row(row)

    def fetch(self, name, label):
        """Resolve a label to the version it points at right now."""
        row = self.db.execute(
            "SELECT v.version, v.template, v.variables, v.model_settings, v.author, v.change_note"
            " FROM labels l JOIN versions v ON v.name = l.name AND v.version = l.version"
            " WHERE l.name = ? AND l.label = ?", (name, label)
        ).fetchone()
        if row is None:
            raise KeyError(f"{name} has no label {label!r}")
        return self._row(row)

    def label_version(self, name, label):
        row = self.db.execute(
            "SELECT version FROM labels WHERE name = ? AND label = ?", (name, label)
        ).fetchone()
        return row[0] if row else None

    def move_label(self, name, label, to_version, actor, reason, gate_result=None):
        """Point `label` at `to_version` and append one row to label_log."""
        with self.db:
            from_version = self.label_version(name, label)
            self.db.execute(
                "INSERT INTO labels (name, label, version) VALUES (?, ?, ?)"
                " ON CONFLICT (name, label) DO UPDATE SET version = excluded.version",
                (name, label, to_version),
            )
            self.db.execute(
                "INSERT INTO label_log (name, label, from_version, to_version, actor,"
                " reason, gate_result) VALUES (?, ?, ?, ?, ?, ?, ?)",
                (name, label, from_version, to_version, actor, reason, gate_result),
            )

    def rollback(self, name, label, actor, reason):
        """Move `label` back to the version it held before its most recent move."""
        row = self.db.execute(
            "SELECT from_version FROM label_log WHERE name = ? AND label = ?"
            " ORDER BY id DESC LIMIT 1", (name, label)
        ).fetchone()
        if row is None or row[0] is None:
            raise ValueError(f"{name}/{label} has no earlier version to return to")
        self.move_label(name, label, row[0], actor, reason)
        return row[0]

    def history(self, name, label):
        return self.db.execute(
            "SELECT id, from_version, to_version, actor, reason, gate_result"
            " FROM label_log WHERE name = ? AND label = ? ORDER BY id", (name, label)
        ).fetchall()

    @staticmethod
    def _row(row):
        version, template, variables, model_settings, author, change_note = row
        return {"version": version, "template": template, "variables": json.loads(variables),
                "model_settings": json.loads(model_settings), "author": author,
                "change_note": change_note}


class CachedFetcher:
    """Runtime-side fetch: TTL cache, one call per miss, stale copy if the source fails.

    `source(name, label)` is any callable that returns a prompt dict or raises.
    After TTL expiry, the next successful fetch sees the label move.
    Failed refreshes can keep a rolled-back version cached indefinitely.
    """

    def __init__(self, source, ttl_seconds, clock=time.monotonic):
        self.source, self.ttl, self.clock = source, ttl_seconds, clock
        self.cache = {}  # (name, label) -> (fetched_at, prompt)
        self.served = []  # (version, how) per call, for the demo printout

    def get(self, name, label):
        key, now = (name, label), self.clock()
        hit = self.cache.get(key)
        if hit and now - hit[0] < self.ttl:
            self.served.append((hit[1]["version"], "cache"))
            return hit[1]
        try:
            prompt = self.source(name, label)
        except Exception:
            if hit:  # registry down: keep serving the last good copy
                self.served.append((hit[1]["version"], "stale"))
                return hit[1]
            raise  # nothing cached: the caller decides (for example a baked-in default)
        self.cache[key] = (now, prompt)
        self.served.append((prompt["version"], "live"))
        return prompt
"""Promotion gate: a candidate version moves a label only if it beats the current one
on the same rows AND gets right every row the current version gets right.

SYNTHETIC: the dataset below is 10 made-up order emails, and `stand_in_model`
is a keyword matcher that reads rules out of the template text. No LLM is called.
This is a single-writer, text-only demo, not a concurrency-safe release gate.
For live prompts, pass the full version through row_results to a model adapter
that renders variables and uses the version's model_settings, not just its text.
"""

CATEGORIES = ("shipping", "billing", "returns")

# SYNTHETIC fixed dataset: (email text, expected category)
DATASET = [
    ("Where is my parcel? Tracking has not moved in a week.", "shipping"),
    ("The delivery date keeps slipping, please confirm the courier.", "shipping"),
    ("You charged me twice on my last invoice.", "billing"),
    ("Please resend the invoice for order 4412 with our VAT number.", "billing"),
    ("I want a refund, the blender arrived cracked.", "returns"),
    ("How do I send this jacket back? It is the wrong size.", "returns"),
    ("My payment failed but the money left my account.", "billing"),
    ("The box was left at the wrong address.", "shipping"),
    ("Can you tell me your opening hours?", "other"),
    ("Do you sell gift cards?", "other"),
]


def stand_in_model(template, email):
    """Reads lines like 'shipping: parcel, courier' from the template and matches keywords."""
    text = email.lower()
    for line in template.splitlines():
        category, _, words = line.partition(":")
        if category.strip() in CATEGORIES:
            if any(w.strip() and w.strip() in text for w in words.split(",")):
                return category.strip()
    return "other"


def row_results(template, dataset=DATASET):
    """One True/False per row: did the template route that email correctly."""
    return [stand_in_model(template, email) == expected for email, expected in dataset]


def score(template, dataset=DATASET):
    """Exact-match accuracy. Deterministic: same template, same number, every run."""
    results = row_results(template, dataset)
    return sum(results) / len(results)


def promote(registry, name, label, candidate_version, approver):
    """Two checks on the same dataset; the label moves only if both pass.

    1. score: candidate accuracy is strictly higher than current accuracy.
    2. no new failures: every row the current version gets right, the candidate also gets right.
    Requires one writer throughout evaluation and the move; no atomic baseline check.
    """
    current_version = registry.label_version(name, label)
    cand_rows = row_results(registry.get_version(name, candidate_version)["template"])
    cur_rows = row_results(registry.get_version(name, current_version)["template"])
    cand, cur = sum(cand_rows) / len(cand_rows), sum(cur_rows) / len(cur_rows)
    broken = [i for i, (c, k) in enumerate(zip(cand_rows, cur_rows), start=1) if k and not c]
    score_ok, rows_ok = cand > cur, not broken
    print(f"  check 1 score: candidate v{candidate_version}={cand:.2f} current v{current_version}={cur:.2f}"
          f" -> {'PASS' if score_ok else 'FAIL'}")
    print(f"  check 2 no new failures: "
          + ("none -> PASS" if rows_ok else
             "; ".join(f"row {i} {DATASET[i - 1][0]!r}" for i in broken) + " -> FAIL"))
    won = score_ok and rows_ok
    print(f"  gate: {'PASS, label moves' if won else 'HOLD, label stays'}")
    if won:
        summary = f"candidate v{candidate_version}={cand:.2f} current v{current_version}={cur:.2f}, no new failures"
        registry.move_label(name, label, candidate_version, approver,
                            f"gate pass on {len(DATASET)} rows", summary)
    return won
"""Run the registry end to end: versions, labels, gate, a skipped gate, cached fetch,
rollback, outage, a fixed version through the gate, immutability, audit log.

SYNTHETIC: prompts, emails and the stand-in model are made up for this demo.
"""
import sqlite3

from gate import DATASET, promote, score
from registry import CachedFetcher, Registry

NAME = "order-router"
HEAD = "Route the customer email to one team: shipping, billing, returns or other.\n"
FOOT = "\nEmail: {{email}}"
TEMPLATES = {
    "v1 first draft": HEAD + "shipping: parcel, delivery\nbilling: invoice\nreturns: refund" + FOOT,
    "v2 more keywords": HEAD + "shipping: parcel, delivery, courier, address, tracking, order\n"
                        "billing: invoice, charged, payment\nreturns: refund, back" + FOOT,
    "v3 too broad": HEAD + "shipping: order, delivery, parcel\nbilling: charged\nreturns: refund" + FOOT,
}
FIX = ("v4 more keywords, order removed",
       HEAD + "shipping: parcel, delivery, courier, address, tracking\n"
       "billing: invoice, charged, payment\nreturns: refund, back" + FOOT)
METADATA = {"owner": "support-tools", "tags": ["routing"]}
SETTINGS = {"model": "synthetic-stand-in", "temperature": 0.0}


class Clock:
    def __init__(self):
        self.t = 0.0

    def __call__(self):
        return self.t


def main():
    print(f"SYNTHETIC DATA: {len(DATASET)} made-up order emails, keyword-rule stand-in model, no LLM called")
    reg = Registry()

    print("\n1. add three immutable versions")
    for i, (title, template) in enumerate(TEMPLATES.items(), start=1):
        v = reg.add_version(NAME, template, ["email"], SETTINGS, "alice", title.split(" ", 1)[1], METADATA)
        print(f"  added {NAME} v{v}: {title.split(' ', 1)[1]} (score on fixed dataset {score(template):.2f})")

    print("\n2. labels point at versions; first move is manual")
    reg.move_label(NAME, "Production", 1, "alice", "initial release")
    reg.move_label(NAME, "Staging", 2, "alice", "candidate under review")
    for label in ("Production", "Staging"):
        print(f"  {label} -> v{reg.label_version(NAME, label)}")

    print("\n3. promotion gate: beat current on the same rows, break none it gets right")
    for candidate in (2, 3):
        print(f"  candidate v{candidate} for Production, approver: bob")
        promote(reg, NAME, "Production", candidate, "bob")
    print(f"  Production -> v{reg.label_version(NAME, 'Production')}")

    print("\n4. someone skips the gate, then a runtime fetch by label with a 60 second cache")
    reg.move_label(NAME, "Production", 2, "carol", "manual move, gate skipped: courier emails piling up")
    print(f"  carol moves Production -> v{reg.label_version(NAME, 'Production')} by hand (no gate result)")
    clock = Clock()
    outage = {"down": False}

    def source(name, label):
        if outage["down"]:
            raise TimeoutError("registry did not answer")
        return reg.fetch(name, label)

    client = CachedFetcher(source, ttl_seconds=60, clock=clock)
    print(f"  t=0s    app fetches Production -> v{client.get(NAME, 'Production')['version']} ({client.served[-1][1]})")
    reg.rollback(NAME, "Production", "bob", "v2 misroutes invoices that mention an order number")
    print(f"  t=0s    rollback: Production -> v{reg.label_version(NAME, 'Production')} in the registry")
    clock.t = 30
    print(f"  t=30s   app fetches Production -> v{client.get(NAME, 'Production')['version']} ({client.served[-1][1]})")
    clock.t = 61
    print(f"  t=61s   app fetches Production -> v{client.get(NAME, 'Production')['version']} ({client.served[-1][1]})")

    print("\n5. registry down")
    outage["down"] = True
    clock.t = 130
    print(f"  t=130s  app fetches Production -> v{client.get(NAME, 'Production')['version']} ({client.served[-1][1]})")
    cold = CachedFetcher(source, ttl_seconds=60, clock=clock)
    try:
        cold.get(NAME, "Production")
    except TimeoutError as exc:
        print(f"  cold start, nothing cached: TimeoutError({exc}) -> caller uses its baked-in default")

    print("\n6. the fix goes through the gate")
    v = reg.add_version(NAME, FIX[1], ["email"], SETTINGS, "alice", FIX[0].split(" ", 1)[1], METADATA)
    print(f"  added {NAME} v{v}: {FIX[0].split(' ', 1)[1]}")
    print(f"  candidate v{v} for Production, approver: bob")
    promote(reg, NAME, "Production", v, "bob")
    print(f"  Production -> v{reg.label_version(NAME, 'Production')}")

    print("\n7. versions cannot be edited")
    try:
        reg.db.execute("UPDATE versions SET template = 'x' WHERE name = ? AND version = 1", (NAME,))
    except sqlite3.DatabaseError as exc:
        print(f"  UPDATE rejected: {exc}")

    print("\n8. label change log for Production")
    for row in reg.history(NAME, "Production"):
        print(f"  #{row[0]} {'start' if row[1] is None else 'v' + str(row[1])} -> v{row[2]} by {row[3]}: {row[4]}" + (f" [{row[5]}]" if row[5] else ""))

    assert reg.label_version(NAME, "Production") == 4
    assert [r[2] for r in reg.history(NAME, "Production")] == [1, 2, 1, 4]
    assert [r[5] is None for r in reg.history(NAME, "Production")] == [True, True, True, False]
    assert [how for _, how in client.served] == ["live", "cache", "live", "stale"]


if __name__ == "__main__":
    main()
SYNTHETIC DATA: 10 made-up order emails, keyword-rule stand-in model, no LLM called

1. add three immutable versions
  added order-router v1: first draft (score on fixed dataset 0.70)
  added order-router v2: more keywords (score on fixed dataset 0.90)
  added order-router v3: too broad (score on fixed dataset 0.60)

2. labels point at versions; first move is manual
  Production -> v1
  Staging -> v2

3. promotion gate: beat current on the same rows, break none it gets right
  candidate v2 for Production, approver: bob
  check 1 score: candidate v2=0.90 current v1=0.70 -> PASS
  check 2 no new failures: row 4 'Please resend the invoice for order 4412 with our VAT number.' -> FAIL
  gate: HOLD, label stays
  candidate v3 for Production, approver: bob
  check 1 score: candidate v3=0.60 current v1=0.70 -> FAIL
  check 2 no new failures: row 4 'Please resend the invoice for order 4412 with our VAT number.' -> FAIL
  gate: HOLD, label stays
  Production -> v1

4. someone skips the gate, then a runtime fetch by label with a 60 second cache
  carol moves Production -> v2 by hand (no gate result)
  t=0s    app fetches Production -> v2 (live)
  t=0s    rollback: Production -> v1 in the registry
  t=30s   app fetches Production -> v2 (cache)
  t=61s   app fetches Production -> v1 (live)

5. registry down
  t=130s  app fetches Production -> v1 (stale)
  cold start, nothing cached: TimeoutError(registry did not answer) -> caller uses its baked-in default

6. the fix goes through the gate
  added order-router v4: more keywords, order removed
  candidate v4 for Production, approver: bob
  check 1 score: candidate v4=1.00 current v1=0.70 -> PASS
  check 2 no new failures: none -> PASS
  gate: PASS, label moves
  Production -> v4

7. versions cannot be edited
  UPDATE rejected: versions are immutable

8. label change log for Production
  #1 start -> v1 by alice: initial release
  #3 v1 -> v2 by carol: manual move, gate skipped: courier emails piling up
  #4 v2 -> v1 by bob: v2 misroutes invoices that mention an order number
  #5 v1 -> v4 by bob: gate pass on 10 rows [candidate v4=1.00 current v1=0.70, no new failures]

When Git alone is enough for prompt version control

Git gives you prompt version control while a prompt change and a code change always ship together and a deploy is fast enough to serve as your rollback. Once a bad prompt has to come out faster than your deploy runs, or a trace has to name the prompt version that answered, it is time for labels in a registry.

Does every prompt change ship with code? Is a deploy fast enough to be the rollback? Must a trace name the prompt version? Git covers diffs, review and history. It has no label per environment, no change without a deploy and no gate result.

NeedGit onlyRegistry
Edit history and diffsYesYes
Review before changePull requestGate plus approver
Change without a deployNoLabel move
Different text per environmentBranches or filesLabels
Rollback timeA deployLabel move, then a successful fetch after cache expiry; unbounded while serving stale
Version named on each requestOnly if you add itLabel and version in every fetch

A middle path keeps prompt files in Git for review. CI registers each merged file as a new version, and only labels and the log live in a small table. Wording gets pull-request review, and label moves need no deploy.

Signs you have outgrown Git

Prompt-only pull requests still wait for a full build. A rollback sits in the CI queue behind unrelated jobs while users keep getting the bad wording. A bad answer from last week cannot be tied to a prompt version, because no request logged its version.

Prompt versions, labels and experiments in Future AGI

Future AGI stores each committed prompt as a numbered version and lets you move the Production, Staging and Development labels, plus your own labels, between versions. Your code fetches a prompt by name and label through the Python SDK, and experiments score versions on the same dataset rows before you move a label.

Each commit creates the next numbered version: v1, v2, v3. A label sits on one version of a template at a time. Assigning it elsewhere moves it, so promotion and rollback are both label moves, as versions and labels explains.

Fetch by label from the SDK

The futureagi package, imported as fi, reads FI_API_KEY and FI_SECRET_KEY from the environment. get_template_by_name takes a name plus a label or a version, and an explicit version wins over a label. compile() fills {{email}} in the template’s messages.

from fi.prompt import Prompt  # noqa: E402


def fetch_live(name="order-router"):
    live = Prompt.get_template_by_name(name, label="Production")  # or label="Staging", or version="v3"
    return live.compile(email="Where is my parcel?")


def promote_live(name="order-router", version="v3"):
    return Prompt.assign_label_to_template_version(template_name=name, version=version, label="Production")

After a version wins, assign_label_to_template_version moves Production to it from code. The source is in futureagi-sdk on GitHub, where get_template_by_name lives in python/fi/prompt/client.py, and the reference shows how to fetch a prompt by name and label.

Experiments as the promotion gate

You run versions on the same dataset from the dataset’s Experiment button. Each configuration pairs a prompt version with a model. Every eval scores every configuration on the same rows, and Choose winner weighs response time, tokens and each eval.

To make it a merge check, run evals in CI on each pull request. Results post back to the pull request, and your CI script fails the step when a score misses the threshold you set. When the candidate wins, move the label.

Shipping the next order-router change without a redeploy

This time the engineer’s edit to the order-routing prompt becomes a new version instead of a code change. The gate scores it, a per-row diff shows the broken invoice before Production moves, and if someone ships it by hand anyway, one label move restores the pointer. The cache follows when a refresh succeeds; an outage can delay that indefinitely.

The engineer writes the new wording as a version and runs both checks. If row 4 breaks again, they read that email and fix the keyword list before approval. Adapt the three-file demo by passing full version records and their settings to your live model adapter, or begin with labels in Future AGI and wire the gate into CI.

Frequently Asked Questions

Is Git enough for prompt version control, or do you need a prompt registry?

Git is enough for prompt version control while every prompt change ships with a code change and a deploy is fast enough to be your rollback. Add a registry once a bad prompt has to come out faster than a deploy allows, or once each request must record which prompt version answered it.

What is a prompt registry design template?

A prompt registry design template is the field list every version carries: template text, variable names, model settings, author, change note, metadata and a creation time. Labels sit in their own table and point at one version each, and a separate log records every label move with who made it and why.

How does instant rollback work in prompt version control?

Instant rollback in prompt version control means moving the Production label back to the earlier version, with no deploy and no text edit. Each app process follows on its next successful fetch after cache expiry. During an outage, this demo can keep serving the rolled-back version indefinitely. Keep the tool schema and model settings in each version too.

How do lifecycle states and aliases work in a prompt registry?

In a prompt registry, lifecycle states and aliases such as Development, Staging and Production are labels, and each label points at exactly one immutable version. Your app fetches a prompt by name and label, so moving a label changes what runs without a deploy. Adding a canary is one more label row.

How to build a 'prompt registry' for team-wide collaboration?

Let anyone on the team write a new version, let only the promotion gate move the Production label, and store the approver's name in the change log. Versions never change once written, so two people editing the same prompt never overwrite each other. This demo requires one writer; concurrent releases need an atomic baseline check before promotion.
Related Articles
View all