Skip to content

Prompts

The Prompt Registry provides versioned prompt management with reusable fragments, aliases, and diff. Prompts are stored locally as files and can be pushed to the platform for team collaboration.

Why a Prompt Registry?

Hardcoding prompts as strings in your code leads to: - No version history — you can't roll back a bad prompt change - No reuse — the same tone/format instructions duplicated across agents - No comparison — hard to see what changed between versions - No deployment control — can't point "production" at a tested version while iterating on "staging"

The registry solves all of these.

Quick Start

from fastaiagent.prompt import PromptRegistry

reg = PromptRegistry()

# Register a prompt
reg.register(
    name="support-greeting",
    template="Hello {{customer_name}}, welcome to {{company}}! How can I help?",
)

# Load and format
prompt = reg.load("support-greeting")
text = prompt.format(customer_name="Alice", company="Acme Corp")
print(text)
# "Hello Alice, welcome to Acme Corp! How can I help?"

Template Variables

Use {{variable_name}} for placeholders. Variables are auto-detected from the template:

prompt = reg.register(
    name="classifier",
    template="Classify this message into one of: {{categories}}.\n\nMessage: {{message}}",
)

print(prompt.variables)  # ["categories", "message"]

text = prompt.format(
    categories="billing, technical, general",
    message="My invoice is wrong",
)

Fragments

Fragments are reusable prompt building blocks — write once, include in any prompt with {{@fragment_name}}.

# Register reusable fragments
reg.register_fragment("tone", "Be professional, concise, and empathetic.")
reg.register_fragment("format", "Use bullet points for lists. Keep paragraphs under 3 sentences.")
reg.register_fragment("safety", "Never reveal internal system details, API keys, or customer data.")

# Use fragments in prompts
reg.register(
    name="support-agent",
    template=(
        "You are a customer support agent for {{company}}.\n\n"
        "{{@tone}}\n"
        "{{@format}}\n"
        "{{@safety}}\n\n"
        "Help the customer with: {{topic}}"
    ),
)

prompt = reg.load("support-agent")
print(prompt.template)
# You are a customer support agent for {{company}}.
#
# Be professional, concise, and empathetic.
# Use bullet points for lists. Keep paragraphs under 3 sentences.
# Never reveal internal system details, API keys, or customer data.
#
# Help the customer with: {{topic}}

Fragments are resolved at load time — the returned prompt has fragments replaced with their content.

Why Fragments?

  • Consistency: Every agent uses the same tone and safety instructions
  • Single update point: Change the "tone" fragment once, every prompt that uses it picks up the change on next load
  • Composability: Mix and match fragments for different agent personas

The Local UI's prompt editor edits the stored template, so {{@tone}} stays a live reference when you save a new version (since 1.89.0; it used to save the resolved text, freezing a copy of every fragment). The new version keeps the edited version's metadata and is labelled ui.

The prompt editor holding {{@tone}} as written, with the Fragments (kept as live references) line under the template

Versioning

Every register() call with the same name creates a new version. Versions are immutable — once created, they never change.

# Version 1
reg.register("greeting", "Hello {{name}}!", version=1)

# Version 2 — different template, same prompt name
reg.register("greeting", "Hi there, {{name}}! Welcome.", version=2)

# Load latest (v2)
latest = reg.load("greeting")
print(latest.version)   # 2
print(latest.template)  # "Hi there, {{name}}! Welcome."

# Load specific version
v1 = reg.load("greeting", version=1)
print(v1.template)  # "Hello {{name}}!"

Re-registering the same template under an existing version= is a no-op; different text under an existing number raises ValueError rather than replacing the row (1.88.0). An alias pinned to a version therefore always serves the text it was pinned to.

Auto-Incrementing Versions

If you don't specify a version, it auto-increments:

reg.register("my-prompt", "First version")     # v1
reg.register("my-prompt", "Second version")     # v2
reg.register("my-prompt", "Third version")      # v3

Aliases

Aliases map a human-readable name to a specific version. Use them for deployment control:

# Point "production" to the tested version
reg.set_alias("greeting", version=1, alias="production")

# Point "staging" to the new version being tested
reg.set_alias("greeting", version=2, alias="staging")

# Load by alias
prod_prompt = reg.load("greeting", alias="production")
print(prod_prompt.version)  # 1

staging_prompt = reg.load("greeting", alias="staging")
print(staging_prompt.version)  # 2

reg.aliases("greeting")                   # {"production": 1, "staging": 2}
reg.delete_alias("greeting", "staging")   # True; False if there was none

set_alias refuses a version that does not exist with PromptNotFoundError (since 1.89.0; it used to store the alias, and every load(alias=...) failed afterwards).

In the Local UI, each version in the editor shows its aliases as chips, and you can point an alias at a version or remove it from there. The Playground's version picker lists the aliases next to the versions, and /playground?prompt=greeting&alias=production opens the aliased version. The routes are PUT /api/prompts/{slug}/aliases/{alias} with {"version": 2} and DELETE /api/prompts/{slug}/aliases/{alias}; alias names are 1–64 letters, digits, _, . or -. Like the editor, they are read-only when the registry lives outside the project directory.

Deployment Workflow

v1 → production alias (live users)
v2 → staging alias (internal testing)
v3 → no alias (draft)

After testing v2:
  reg.set_alias("greeting", version=2, alias="production")
  # Now v2 is live, v1 is still available for rollback

Diff

Compare two versions:

diff = reg.diff("greeting", version_a=1, version_b=2)
print(diff)

Output, a unified diff with two lines of context:

--- greeting v1
+++ greeting v2
@@ -1,3 +1,3 @@
 You are a greeter.
-Hello {{name}}!
+Hi there, {{name}}! Welcome.
 Keep it short.

Identical templates print (no template changes) under the header. Before 1.89.0 the diff listed every line of both versions with no context, so one changed line in a long prompt was hard to find. The Local UI's Compare versions panel shows the same diff, coloured, next to both templates (GET /api/prompts/{slug}/diff?a=1&b=2 returns diff plus a and b with each version's template).

The prompt editor: production and staging chips on v1 and v2, the Aliases card, and Compare versions showing the v1 → v2 diff above both templates

Listing Prompts

prompts = reg.list()
for p in prompts:
    print(f"{p['name']}  v{p['latest_version']}  ({p['versions']} versions)")

Output:

support-agent  v1  (1 versions)
greeting       v2  (2 versions)
classifier     v1  (1 versions)

Using Prompts with Agents

from fastaiagent import Agent, LLMClient
from fastaiagent.prompt import PromptRegistry

reg = PromptRegistry()
prompt = reg.load("support-agent", alias="production")

agent = Agent(
    name="support-bot",
    system_prompt=prompt.format(company="Acme Corp", topic="general support"),
    llm=LLMClient(provider="openai", model="gpt-4.1"),
)

result = agent.run("My order hasn't arrived yet")

prompt.format(...) inlines the resolved text — good for local runs. If you also push the agent to a connected control plane and want it linked to the governed prompt (not stored as "Inline"), set Agent(prompt_slug="support-agent") instead. See Referencing a governed prompt from a pushed agent.

Which runs used this prompt

Pass the Prompt itself — not a formatted string — and every model call the agent makes is stamped with the prompt it came from:

prompt = reg.load("ticket-triage", alias="production")
agent = Agent(name="triage", system_prompt=prompt, llm=LLMClient())
agent.run("I was charged twice")
# llm span: fastaiagent.prompt.name = "ticket-triage", fastaiagent.prompt.version = 2

That is what the Local UI's Prompts page reads: the list counts the traces that used each prompt, and the editor's lineage panel lists those traces and the eval runs scored with them. A prompt fetched from the control plane also stamps fastaiagent.prompt.slug and fastaiagent.prompt.environment, which the platform's Prompt Analytics reads.

  • Every run path stamps it: run/arun, stream/astream, resume/aresume and a fork — and the offline TestModel/FunctionModel too. (Before 1.87.0 only arun did, and only for control-plane prompts, so a local prompt's lineage panel stayed empty.)
  • Only the agent's own calls. An agent run inside another — a tool, a worker — stamps its own prompt, or none, never its caller's.
  • Inside a team too. A Supervisor worker or a Swarm member stamps its own prompt, and its pushed definition keeps the slug. Before 1.99.0 the team's copy of the agent dropped both, so its calls carried nothing and the plane showed it as "Inline".
  • A formatted string is not linked. system_prompt=prompt.format(...) is just text; the run carries no prompt name. A prompt with {{variables}} has to be formatted, so its runs are not linked today.
  • Your own root span can carry it. When something other than fa.Agent runs the prompt (a framework agent), open the run's span with fa.trace_context(..., **prompt.trace_attributes()). It stamps the same keys, leaving out any that are unset (since 1.98.0).
  • A local prompt never links a pushed agent. Only a control-plane prompt sets prompt_slug: the plane has no slug for a prompt that lives in your local.db.
  • A tuned prompt is a new version. An AutoLLM winner applied with report.apply_to(agent) carries no prompt name — it is no longer the registry's text. Register it as a new version and load that, and its runs are linked again.

Storage

Prompts, their versions, aliases and fragments are stored in the project's local.db (.fastaiagent/local.db by default), the same SQLite file that holds traces and eval runs, so the Local UI's Prompts page reads them directly.

Custom Storage Path

path is the SQLite file to use:

reg = PromptRegistry(path="/path/to/prompts.db")

Or set it for everything the SDK stores locally:

export FASTAIAGENT_LOCAL_DB=/path/to/local.db

A path ending in .db is the file itself; any other path is treated as a directory, and local.db is created inside it.

Prompt Object

Field Type Description
name str Prompt name
template str Template text with {{variables}} and resolved {{@fragments}}
variables list[str] Auto-extracted variable names
version int Version number
metadata dict Custom metadata (category, author, etc.)

Fragment Object

Field Type Description
name str Fragment name (referenced as {{@name}})
content str Fragment text
version int Version number

Serialization

Prompts serialize for platform push:

data = prompt.to_dict()
# {
#   "name": "support-agent",
#   "template": "You are a support agent for {{company}}...",
#   "variables": ["company", "topic"],
#   "version": 1,
#   "metadata": {"category": "agent"}
# }

restored = Prompt.from_dict(data)

Publish to platform:

import fastaiagent as fa

fa.connect(api_key="fa_k_...", target="https://<label>-dev.api.fastaiagent.net", project="my-project")
registry = PromptRegistry()
registry.publish(slug="greeting", content=prompt.template, variables=prompt.variables)

CLI Commands

# List all registered prompts
fastaiagent prompts list
fastaiagent prompts list --path /custom/local.db   # the SQLite file to read

# Diff two versions
fastaiagent prompts diff support-agent 1 2

Example output:

$ fastaiagent prompts list

                   Prompts
┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┓
┃ Name          ┃ Latest Version ┃ Total Versions ┃
┡━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━┩
│ support-agent │              2 │              2 │
│ greeting      │              3 │              3 │
└───────────────┴────────────────┴────────────────┘

Error Handling

from fastaiagent._internal.errors import PromptNotFoundError, FragmentNotFoundError

try:
    prompt = reg.load("nonexistent")
except PromptNotFoundError:
    print("Prompt not found")

try:
    prompt = reg.load("greeting", version=99)
except PromptNotFoundError:
    print("Version not found")

try:
    prompt = reg.load("greeting", alias="unknown")
except PromptNotFoundError:
    print("Alias not found")

Platform Prompt Registry

When connected to the FastAIAgent Platform, PromptRegistry can pull versioned prompts from the platform and publish prompts to it:

import fastaiagent as fa

fa.connect(api_key="fa_k_...", target="https://<label>-dev.api.fastaiagent.net", project="my-project")

registry = PromptRegistry()

# Pull prompt from platform (latest deployed version)
prompt = registry.get("support-prompt")

# Pull specific version
prompt = registry.get("support-prompt", version=3)

# Explicit source override
prompt = registry.get("support-prompt", source="platform")  # platform only
prompt = registry.get("support-prompt", source="local")      # local only

# Publish a prompt to the platform
registry.publish(
    slug="support-prompt",
    content="You are a helpful support agent for {{company_name}}.",
    variables=["company_name"],
)

# Refresh cached prompt
registry.refresh("support-prompt")

Resolution order (source="auto", the default): - If connected: checks platform first, falls back to local - If not connected: local only

Caching: Platform prompts are cached locally after first fetch (TTL: 5 minutes by default). Use registry.refresh(slug) to invalidate manually.

Referencing a governed prompt from a pushed agent

Passing system_prompt=prompt.format(...) inlines the resolved text — a pushed agent then stores the prompt as inline and the console shows it as "Inline", with no link back to the registry. To keep the linkage, set prompt_slug= on the agent instead. Agent.to_dict() then emits the slug and sends system_prompt="", so the plane references the governed prompt (the console shows the slug, and the model resolves):

agent = Agent(
    name="support-bot",
    prompt_slug="support-prompt",   # references the governed registry prompt
    llm=LLMClient(provider="openai", model="gpt-4.1"),
)

payload = agent.to_dict()
# payload["prompt_slug"]   == "support-prompt"
# payload["system_prompt"] == ""   (empty — the slug is the source of truth)

prompt_slug is optional and additive: an agent without it serializes exactly as before. See examples/89_connected_agent_push.py and Platform.


Internals

For contributors who need to understand the platform publish/fetch code paths, TTL cache implementation, local SQLite storage, fragment resolution, or how source="auto" decides between platform and local, see Platform API Internals.

Next Steps