Prompts (SDK)

Fetch versioned prompts from TrailAI at runtime instead of hard-coding strings — so a prompt change is a dashboard edit, not a deploy.

Author prompts first: Prompt Management.


The API

trail.get_prompt(
    name=None,
    prompt_id=None,
    label=None,
    version=None,
) -> dict | None
Argument Purpose
name Fetch by prompt name — the usual way
prompt_id Fetch by ID
label Which labelled version: production, staging, …
version A specific version number

Supply name or prompt_id. Add label or version to pin which version; omit both to get the latest.


Basic usage

import trail

trail.init(
    application_name="support-bot",
    url=TRAIL_URL, public_key=TRAIL_PUBLIC_KEY, secret_key=TRAIL_SECRET_KEY,
)

prompt = trail.get_prompt(name="support-answer", label="production")

Fetching a prompt


⚠️ It returns None on failure

get_prompt() does not raise on a network error or a missing prompt. It logs and returns None.

Always handle it:

prompt = trail.get_prompt(name="support-answer", label="production")

if prompt is None:
    logger.warning("Prompt fetch failed; using built-in fallback")
    messages = FALLBACK_MESSAGES
else:
    messages = prompt["messages"]

Skip this and None propagates into your model client, producing an error far from its cause. Keep a hard-coded fallback for every prompt on a critical path. It's the difference between a degraded service and an outage when TrailAI is unreachable.

It does raise ValueError: make sure trail.init is defined when credentials weren't passed as trail.init() arguments — why.


Fetching strategies

By label (production default)

prompt = trail.get_prompt(name="support-answer", label="production")

The label points at a version; moving it in the dashboard changes what your app gets, with no deploy. This is what you want in production.

By version (pinned)

prompt = trail.get_prompt(name="support-answer", version="3")

Deterministic. Use for reproducible test runs, or when you need certainty that nothing changes under you.

Latest

prompt = trail.get_prompt(name="support-answer")

Convenient in development. Risky in production — any save in the dashboard reaches production immediately, unreviewed.

Strategy Development Staging Production
Latest ✅ — ❌
By label ✅ ✅ ✅
By version — ✅ ✅ when you need a hard pin

Caching

Every get_prompt() call is a network round trip. Fetching per request adds latency and load.

Fetch once at startup

class PromptStore:
    def __init__(self):
        self.prompts = {}

    def load(self):
        for name in ["support-answer", "summarize", "classify-intent"]:
            p = trail.get_prompt(name=name, label="production")
            if p is not None:
                self.prompts[name] = p
            else:
                logger.error("Failed to load prompt: %s", name)

    def get(self, name):
        return self.prompts.get(name, FALLBACKS[name])

store = PromptStore()
store.load()

Simple and fast — but you must restart to pick up a prompt change.

Refresh periodically

import schedule, threading, time

def refresh_prompts():
    store.load()

schedule.every(5).minutes.do(refresh_prompts)

def _run():
    while True:
        schedule.run_pending()
        time.sleep(1)

threading.Thread(target=_run, daemon=True).start()

Changes propagate within the refresh interval without a restart. Five minutes is a reasonable balance for most applications.

TTL cache

import time

_cache = {}
TTL = 300

def cached_prompt(name: str, label: str = "production"):
    key = (name, label)
    entry = _cache.get(key)

    if entry and time.time() - entry["at"] < TTL:
        return entry["prompt"]

    prompt = trail.get_prompt(name=name, label=label)
    if prompt is not None:
        _cache[key] = {"prompt": prompt, "at": time.time()}
        return prompt

    return entry["prompt"] if entry else None   # serve stale rather than nothing

Serving stale on failure is usually the right call — a slightly old prompt beats no prompt.


Using a fetched prompt

The response contains the compiled messages:

prompt = trail.get_prompt(name="support-answer", label="production")

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=prompt["messages"],
)

Adding runtime content to a stored template:

messages = list(prompt["messages"])
messages.append({"role": "user", "content": user_question})

Or design the prompt with a placeholder message and substitute into it — see Prompt Management.


Download counting

Each fetch increments the prompt's Downloads counter in the dashboard. That makes it your best signal for what's actually in use — and a reason to cache rather than fetch per request, so the number reflects deployments rather than traffic.


Complete pattern

import logging
import trail

logger = logging.getLogger(__name__)

FALLBACKS = {
    "support-answer": [
        {"role": "system", "content": "You are a helpful support agent. Be concise."},
    ],
}

class Prompts:
    def __init__(self, names, label="production"):
        self.names, self.label, self.cache = names, label, {}

    def load(self):
        for name in self.names:
            p = trail.get_prompt(name=name, label=self.label)
            if p is not None:
                self.cache[name] = p["messages"]
                logger.info("Loaded prompt %s", name)
            else:
                logger.error("Prompt %s unavailable; using fallback", name)

    def messages(self, name):
        return self.cache.get(name) or FALLBACKS[name]

prompts = Prompts(["support-answer"])
prompts.load()

@trail.trace(role="agent")
def answer(question: str) -> str:
    messages = list(prompts.messages("support-answer"))
    messages.append({"role": "user", "content": question})

    response = client.chat.completions.create(model="gpt-4o-mini", messages=messages)
    return response.choices[0].message.content

Related