Skip to content
GitHubDiscord

API Reference

Assembles prompt layers in cache-friendly static-to-dynamic order.

The static-first ordering maximizes provider-side KV cache reuse. The assembler also injects provider-specific cache annotations (Anthropic’s cache_control breakpoints, DeepSeek’s 64-token padding, etc.).

def assemble(
    system: str,
    tools: list[ToolDefinition] | None,
    reference_docs: list[str] | None,
    few_shot: list[ChatMessage] | None,
    history: list[ChatMessage],
    query: str,
    provider: str,
    dynamic_metadata: str | None = None
) -> list[ChatMessage]

Assemble a complete prompt message list.

Parameters
ParameterTypeDescription
`system`strSystem instructions (static, cached).
`tools`list[ToolDefinition] | NoneTool/function definitions.
`reference_docs`list[str] | NoneReference documents as text (semi-static).
`few_shot`list[ChatMessage] | NoneFew-shot example messages (static, cached).
`history`list[ChatMessage]Chat history messages (dynamic).
`query`strCurrent user query (dynamic).
`provider`strProvider name for cache annotation strategy.
`dynamic_metadata`str | NoneTimestamps, user IDs, etc. (dynamic).
Returns
TypeDescription
list[ChatMessage]Ordered list of ChatMessage instances ready for the LLM client.

Optimizes a rendered prompt for a specific model.

Consumed by: lexigram-ai-platform prompt submodule.

async def optimize(
    prompt: str,
    model: str,
    max_tokens: int
) -> str

Optimize a prompt for the target model and token budget.

Parameters
ParameterTypeDescription
`prompt`strThe rendered prompt string to optimize.
`model`strTarget model identifier.
`max_tokens`intMaximum token budget for the optimized prompt.
Returns
TypeDescription
strThe optimized prompt string.

Protocol for a named template registry.
def register(
    name: str,
    template: PromptTemplateProtocol,
    *,
    overwrite: bool = False
) -> None

Register a template under name.

def get(name: str) -> PromptTemplateProtocol

Retrieve a template by name.

def list_names() -> list[str]

Return all registered template names.


Renders a prompt template with provided variables.

Consumed by: lexigram-ai-platform prompt submodule, lexigram-ai-rag.

def render(
    template: str,
    variables: dict[str, Any]
) -> str

Render a template string with the supplied variable mapping.

Parameters
ParameterTypeDescription
`template`strThe raw template string.
`variables`dict[str, Any]Mapping of variable names to their values.
Returns
TypeDescription
strThe rendered prompt string.

Protocol for prompt templates that render to text or chat messages.
property name() -> str

Unique name identifying this template.

def render(**kwargs: Any) -> str | list[dict[str, str]]

Render the template with the supplied variable values.

Parameters
ParameterTypeDescription
Returns
TypeDescription
str | list[dict[str, str]]A plain string or a list of ``{"role": ..., "content": ...}`` dicts.
def get_variables() -> list[str]

Return the list of declared variable names.


Common interface for all prompt template implementations.

Subclasses must implement render and expose name.

property name() -> str

Unique name for this template (used by the registry).

property version() -> str

Semantic version of the template (e.g. ‘1.0.0’).

def render(**kwargs: Any) -> str | list[dict[str, str]]

Render the template given kwargs variable values.

Returns
TypeDescription
str | list[dict[str, str]]A plain string (StringPromptTemplate) or a list of chat message dicts ``[{"role": ..., "content": ...}, ...]`` (ChatPromptTemplate).
def validate() -> None

Validate that the template declares all the variables it uses.

Raises
ExceptionDescription
def get_variables() -> list[str]

Return declared variable names for this template.

The base implementation returns an empty list; subclasses override this to report their declared PromptVariable names.


Prompt assembler that enforces static-before-dynamic ordering and applies provider-specific cache annotations.

Implements PromptAssemblerProtocol and enforces the 7-layer ordering:

  1. System instructions (STATIC)
  2. Tool/function definitions (STATIC)
  3. Reference documents (SEMI-STATIC)
  4. Few-shot examples (STATIC) ── CACHE BOUNDARY ──
  5. Chat history (DYNAMIC)
  6. Current user query (DYNAMIC)
  7. Dynamic metadata (DYNAMIC)
Parameters
ParameterTypeDescription
`strategy_registry`Provider cache strategy registry.
`token_counter`Optional token counter for cache-size validation.
def __init__(
    strategy_registry: ProviderCacheStrategyRegistry,
    token_counter: TokenCounterProtocol | None = None
) -> None

Initialize with strategy registry and optional token counter.

def set_token_counter(counter: TokenCounterProtocol) -> None

Inject token counter after construction (called from DI boot phase).

Parameters
ParameterTypeDescription
`counter`TokenCounterProtocolToken counter to use for cache size validation.
def assemble(
    system: str,
    tools: list[ToolDefinition] | None,
    reference_docs: list[str] | None,
    few_shot: list[ChatMessage] | None,
    history: list[ChatMessage],
    query: str,
    provider: str,
    dynamic_metadata: str | None = None
) -> list[ChatMessage]

Assemble messages in canonical static-before-dynamic order.

This method matches the PromptAssemblerProtocol.assemble() signature exactly. It enforces the 7-layer static-to-dynamic ordering:

Layers 1-4 (STATIC) come before cache boundary:

  • Layer 1: System instructions
  • Layer 2: Tool definitions
  • Layer 3: Reference documents
  • Layer 4: Few-shot examples

Layers 5-7 (DYNAMIC) come after cache boundary:

  • Layer 5: Chat history
  • Layer 6: Current user query
  • Layer 7: Dynamic metadata
Parameters
ParameterTypeDescription
`system`strSystem instructions (Layer 1, always static).
`tools`list[ToolDefinition] | NoneTool definitions as list of ToolDefinition objects.
`reference_docs`list[str] | NoneReference document strings (Layer 3).
`few_shot`list[ChatMessage] | NoneFew-shot example messages (Layer 4, static).
`history`list[ChatMessage]Chat history messages (Layer 5, dynamic).
`query`strCurrent user query text (Layer 6, dynamic).
`provider`strProvider key for cache strategy selection.
`dynamic_metadata`str | NoneDynamic metadata string appended after query.
Returns
TypeDescription
list[ChatMessage]Assembled and cache-annotated list of ChatMessage objects.

A prompt template that produces a list of chat messages.

Each message slot (system, user, assistant) is an optional template string. At render time all provided slots are substituted and assembled into the standard [{"role": ..., "content": ...}] format expected by most LLM clients.

Parameters
ParameterTypeDescription
`name`Unique template name.
`system`Optional system message template string.
`user`Optional user message template string.
`assistant`Optional assistant (prefill) message template string.
`variables`Declared typed variables shared across all slots.
`format`Rendering format. Defaults to F_STRING.
`description`Optional human-readable description.

Example

support = ChatPromptTemplate(
name="support-agent-v2",
system="You are a {role} for {company}.",
user="{customer_query}",
variables=[
PromptVariable("role", default="support agent"),
PromptVariable("company", required=True),
PromptVariable("customer_query", required=True),
],
)
messages = support.render(company="Acme Corp", customer_query="Help!")
# [
# {"role": "system", "content": "You are a support agent for Acme Corp."},
# {"role": "user", "content": "Help!"},
# ]
def __init__(
    name: str,
    system: str | None = None,
    user: str | None = None,
    assistant: str | None = None,
    variables: list[PromptVariable] | None = None,
    format: RenderFormat = RenderFormat.F_STRING,
    description: str = '',
    version: str = '1.0.0'
) -> None
property name() -> str
property version() -> str
def validate() -> None

Validate that all variables used in the template are declared.

def get_variables() -> list[str]
def render(**kwargs: Any) -> list[dict[str, str]]

Render all message slots and return a message list.

Parameters
ParameterTypeDescription
Returns
TypeDescription
list[dict[str, str]]List of ``{"role": ..., "content": ...}`` dicts. Only slots that were specified at construction time are included.
Raises
ExceptionDescription
def render_as_string(
    separator: str = '\n\n',
    **kwargs: Any
) -> str

Render all messages and join them into a single string.

Parameters
ParameterTypeDescription
`separator`strString placed between consecutive messages. **kwargs: Variable name → value pairs.
Returns
TypeDescription
strSingle concatenated string of all rendered messages.
def add_message(
    role: str,
    content: str
) -> ChatPromptTemplate

Return a new template with an additional message appended.

The new slot uses the same variable declarations and rendering format as the original. The new role must be "system", "user", or "assistant".

Parameters
ParameterTypeDescription
`role`strMessage role.
`content`strTemplate string for the new message.
Returns
TypeDescription
ChatPromptTemplateA new ChatPromptTemplate.

Selects one of several templates based on a condition function.

The first condition that returns True wins; if no condition matches the default template is used (if provided), otherwise PromptNotFoundError is raised.

Parameters
ParameterTypeDescription
`name`Unique template name.
`branches`Sequence of ``(condition, template)`` pairs. The *condition* receives the render ``**kwargs`` and returns a bool.
`default`Fallback template used when no condition matches.

Example

prompt = ConditionalPrompt(
name="tone-selector",
branches=[
(lambda **kw: kw.get("formal"), formal_template),
(lambda **kw: kw.get("casual"), casual_template),
],
default=neutral_template,
)
result = prompt.render(formal=True, topic="AI")
def __init__(
    name: str,
    branches: list[tuple[Callable[Ellipsis, bool], AbstractPromptTemplate]],
    default: AbstractPromptTemplate | None = None,
    version: str = '1.0.0'
) -> None
property name() -> str
property version() -> str
def validate() -> None

Validate all nested templates.

def get_variables() -> list[str]

Return the union of all branch variable names.

def render(**kwargs: Any) -> str | list[dict[str, str]]

Evaluate conditions in order and render the first matching template.

Parameters
ParameterTypeDescription
Returns
TypeDescription
str | list[dict[str, str]]Rendered output of the winning template.
Raises
ExceptionDescription

A prompt template that injects few-shot examples before the query.

Examples are formatted with example_template (defaults to "{input}\n{output}") and injected between the prefix and suffix with example_separator as a delimiter.

Parameters
ParameterTypeDescription
`name`Unique template name.
`prefix`Text shown before all examples.
`suffix`Text shown after all examples (typically contains the actual query placeholder, e.g. ``"Q: {question}\nA:"``).
`example_selector`Provides the examples to inject.
`example_template`Per-example template string. Must reference the keys present in each example dict.
`example_separator`Delimiter between examples. Defaults to ``"\n\n"``.
`variables`Additional typed variables for the *suffix*.
`format`Rendering format for *prefix*, *suffix*, and *example_template*.
`description`Optional human-readable description.

Example

selector = InMemoryExampleSelector(
examples=[
{"input": "2+2", "output": "4"},
{"input": "3*3", "output": "9"},
],
k=2,
)
tmpl = FewShotPromptTemplate(
name="math-few-shot",
prefix="Solve the following math problems:\n",
suffix="Q: {question}\nA:",
example_selector=selector,
variables=[PromptVariable("question", required=True)],
)
print(tmpl.render(question="5+5"))
def __init__(
    name: str,
    prefix: str,
    suffix: str,
    example_selector: ExampleSelectorProtocol,
    example_template: str = '{input}\n{output}',
    example_separator: str = '\n\n',
    variables: list[PromptVariable] | None = None,
    format: RenderFormat = RenderFormat.F_STRING,
    description: str = '',
    version: str = '1.0.0'
) -> None
property name() -> str
property version() -> str
def validate() -> None

Validate that all variables used in the template are declared.

def get_variables() -> list[str]
def render(**kwargs: Any) -> str

Render the few-shot prompt.

Selects examples, formats each one, then assembles: prefix + example_separator + examples + example_separator + suffix.

Parameters
ParameterTypeDescription
Returns
TypeDescription
strFully rendered prompt string.
Raises
ExceptionDescription

Simple in-memory example selector.

Selects the first k examples from the provided list by default. Subclass and override select for similarity-based selection.

Parameters
ParameterTypeDescription
`examples`List of example dicts.
`k`Maximum number of examples to include.
def __init__(
    examples: list[dict[str, str]],
    k: int = 3
) -> None
def select(**kwargs: Any) -> list[dict[str, str]]

Return up to k examples.

The base implementation returns the first k entries. Override this method to implement query-based or similarity-based selection.

Parameters
ParameterTypeDescription
Returns
TypeDescription
list[dict[str, str]]List of selected example dicts.
def add(example: dict[str, str]) -> None

Append an example to the pool.


Scans user-supplied variable values for prompt-injection attempts.

Use sanitize to validate a single string or sanitize_all to check an entire variable mapping.

Parameters
ParameterTypeDescription
`strict`When ``True`` (default), detected injections raise PromptValidationError. When ``False``, the violating string is returned as-is and a warning is recorded in warnings.
`extra_patterns`Additional compiled patterns to check.
def __init__(
    strict: bool = True,
    extra_patterns: list[re.Pattern[str]] | None = None
) -> None
def sanitize(
    value: str,
    variable_name: str = 'input'
) -> str

Check value for injection patterns.

Parameters
ParameterTypeDescription
`value`strString to inspect.
`variable_name`strName used in error messages.
Returns
TypeDescription
strThe (unchanged) *value* when no injection is detected.
Raises
ExceptionDescription
def sanitize_all(variables: dict[str, object]) -> dict[str, object]

Check all string values in variables.

Non-string values are passed through unchanged.

Parameters
ParameterTypeDescription
`variables`dict[str, object]Variable name → value mapping.
Returns
TypeDescription
dict[str, object]The same mapping (values are not mutated).

Wraps any AbstractPromptTemplate and pre-fills a subset of its variables.

The pre-filled values can be overridden at render time by passing the same key in render(**kwargs).

Parameters
ParameterTypeDescription
`template`Underlying template to wrap.
`partial_variables`Variable name → pre-filled value mapping.

Example

base = StringPromptTemplate(
name="email",
template="Dear {recipient},\n\n{body}\n\nRegards, {sender}",
variables=[
PromptVariable("recipient", required=True),
PromptVariable("body", required=True),
PromptVariable("sender", required=True),
],
)
support_email = PartialPromptTemplate(base, sender="Support Team")
result = support_email.render(recipient="Alice", body="How can we help?")
def __init__(
    template: AbstractPromptTemplate,
    **partial_variables: Any
) -> None
property name() -> str
property version() -> str
def validate() -> None

Validate the underlying template.

def get_variables() -> list[str]
def render(**kwargs: Any) -> str | list[dict[str, str]]

Render by merging pre-filled values with kwargs.

Pre-filled values act as defaults; kwargs take precedence.


Configuration for the prompt management system.

Attributes: default_format: Default rendering format ("f_string", "jinja2", "dollar", or "simple"). sanitize_inputs: When True, apply InputSanitizer to all user-supplied variable values. strict_sanitizer: When True, detected injection patterns raise an error. When False, they only generate warnings. max_variable_length: Global default for maximum allowed variable value length in characters. 0 means unlimited.


Runtime context passed to a template's ``render`` call.

Wraps the raw **kwargs mapping so it can be enriched or validated as a single object.

Attributes: variables: Variable name → value mapping. metadata: Arbitrary caller-supplied metadata (not used in rendering).

def from_kwargs(
    cls,
    **kwargs: Any
) -> PromptContext

Create a PromptContext from keyword arguments.


Payload fired after prompt input sanitization completes.

Prompt template management and rendering integration.

Registers the PromptProvider which wires a PromptRegistry into the container and exposes it as PromptTemplateProtocol.

Usage

from lexigram.ai.prompt import PromptModule
from lexigram.ai.prompt.config import PromptConfig
@module(
imports=[
PromptModule.configure(
PromptConfig(default_format="jinja2")
)
]
)
class AppModule(Module):
pass

Error Handling

Prompt rendering and registry lookups surface typed exceptions that
can be caught directly or handled via the Result pattern::
from lexigram.ai.prompt.exceptions import (
PromptError, # base — catch-all
PromptRenderError, # template rendering failure
PromptValidationError,# variable type / value validation
PromptNotFoundError, # named template not in registry
PromptVersionError, # version conflict or invalid rollback
)

Exports: PromptTemplateProtocol, PromptError, PromptRenderError, PromptValidationError, PromptNotFoundError, PromptVersionError

def configure(
    cls,
    config: PromptConfig | None = None,
    **kwargs: Any
) -> DynamicModule

Create a PromptModule with explicit configuration.

Parameters
ParameterTypeDescription
`config`PromptConfig | NonePromptConfig or ``None`` to use defaults. **kwargs: Additional keyword arguments forwarded to PromptProvider.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.
def stub(
    cls,
    config: PromptConfig | None = None
) -> DynamicModule

Create a PromptModule suitable for unit and integration testing.

Uses in-memory or no-op implementations with minimal side effects.

Parameters
ParameterTypeDescription
`config`PromptConfig | NoneOptional config override. Uses safe test defaults when None.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.

Chains a sequence of AbstractPromptTemplate objects.

Each template’s rendered output is injected into the next template’s context under the key specified by output_key (default "input"). The initial call provides the variables for the first template; subsequent templates receive output_key=<previous output> merged with the same **kwargs.

Parameters
ParameterTypeDescription
`templates`Ordered sequence of templates to chain.
`output_key`The variable name under which each stage's output is passed to the following stage. Defaults to ``"input"``.
Raises
ExceptionDescription
ValueErrorFewer than two templates are provided.

Example

pipeline = PromptPipeline(
templates=[topic_template, elaboration_template],
output_key="previous",
)
final = pipeline.run(subject="climate change")
def __init__(
    templates: list[AbstractPromptTemplate],
    output_key: str = 'input'
) -> None
property templates() -> list[AbstractPromptTemplate]

The ordered list of templates in this pipeline.

def run(**kwargs: Any) -> str | list[dict[str, str]]

Execute the pipeline and return the final template’s output.

Parameters
ParameterTypeDescription
Returns
TypeDescription
str | list[dict[str, str]]The rendered output of the last template in the chain.
Raises
ExceptionDescription

Provider for the prompt registry.

Reads PromptConfig, builds a PromptRegistry, and registers it as a singleton.

def __init__(config: PromptConfig | None = None) -> None

Initialize with optional config.

async def register(container: ContainerRegistrarProtocol) -> None

Register the PromptConfig, PromptRegistry, and CacheAwarePromptAssembler.

async def boot(container: ContainerResolverProtocol) -> None

Boot phase — inject optional TokenCounterProtocol into assembler.

async def shutdown() -> None

Shutdown phase — no cleanup required for prompt registry.

async def health_check(timeout: float = 5.0) -> HealthCheckResult

Health check — always healthy (in-process domain provider).

No external backend to ping.

Parameters
ParameterTypeDescription
`timeout`floatIgnored for in-process providers.
Returns
TypeDescription
HealthCheckResultAlways HEALTHY — no external backend to ping.

A thread-safe, in-memory registry that maps names to templates.

Templates are registered once and can thereafter be retrieved by name. The registry supports optional namespacing via dotted names (e.g. "support.greeting").

Example

registry = PromptRegistry()
registry.register("hello", tmpl)
retrieved = registry.get("hello")
def __init__() -> None
def register(
    name: str,
    template: AbstractPromptTemplate,
    *,
    overwrite: bool = False
) -> None

Register template under name.

Parameters
ParameterTypeDescription
`name`strLookup key.
`template`AbstractPromptTemplateTemplate instance to register.
`overwrite`boolAllow replacing an existing registration. Defaults to ``False`` to prevent accidental overwrites.
Raises
ExceptionDescription
ValueError*name* already registered and *overwrite* is ``False``.
def get(name: str) -> AbstractPromptTemplate

Retrieve a template by name.

Parameters
ParameterTypeDescription
`name`strLookup key.
Returns
TypeDescription
AbstractPromptTemplateThe registered template.
Raises
ExceptionDescription
def list_names() -> list[str]

Return a sorted list of all registered template names.

def unregister(name: str) -> None

Remove template name from the registry.

Parameters
ParameterTypeDescription
`name`strLookup key.
Raises
ExceptionDescription

Emitted when a prompt template is rendered with variables.

Consumed by: analytics, prompt optimization, audit.


Payload fired after prompt rendering produces a formatted payload.

Renders a template string by substituting named variables.

Supports three formats controlled by RenderFormat.

Parameters
ParameterTypeDescription
`format`Substitution format. Defaults to RenderFormat.F_STRING.
def __init__(format: RenderFormat = RenderFormat.F_STRING) -> None
property format() -> RenderFormat

The active rendering format.

def render(
    template: str,
    variables: dict[str, Any]
) -> str

Substitute variables into template.

Parameters
ParameterTypeDescription
`template`strRaw template string.
`variables`dict[str, Any]Variable name → value mapping.
Returns
TypeDescription
strRendered string.
Raises
ExceptionDescription
def get_variables(template: str) -> list[str]

Extract placeholder names from template.

Parameters
ParameterTypeDescription
`template`strRaw template string.
Returns
TypeDescription
list[str]Unique list of variable names detected in the template.

Payload fired when a named prompt template is resolved from the registry.

Declares a typed, validated template variable.

Attributes: name: Variable name as it appears in the template (without braces). type: Expected Python type. Defaults to str. required: If True, a missing value raises PromptRenderError. default: Default value used when the variable is not supplied. Ignored when required=True. description: Human-readable purpose of this variable. max_length: Maximum allowed string length. None means unlimited. allowed_values: Explicit allow-list of valid values. None means any.


Registry mapping provider names to cache annotation strategies.

Uses registry-based dispatch — no if/elif chains.

Usage

registry = ProviderCacheStrategyRegistry.with_defaults()
strategy = registry.for_provider("anthropic")
annotated = strategy.annotate(messages, static_count=3, token_counter=counter)
def __init__() -> None

Create an empty registry.

def with_defaults(cls) -> ProviderCacheStrategyRegistry

Create a registry pre-populated with all provider strategies.

def register(
    provider: str,
    strategy: CacheStrategy
) -> None

Register a strategy for a provider key.

Parameters
ParameterTypeDescription
`provider`strProvider name (e.g. "anthropic", "openai").
`strategy`CacheStrategyCache annotation strategy.
def for_provider(provider: str) -> CacheStrategy

Get the strategy for the given provider.

Falls back to wildcard ’*’ strategy if provider not found, then to PassthroughCacheStrategy default.

Parameters
ParameterTypeDescription
`provider`strProvider name.
Returns
TypeDescription
CacheStrategyCacheStrategy for the provider (or wildcard/passthrough fallback).

Supported template substitution formats.

A single-string prompt template with typed variable validation.

Supports all RenderFormat modes (f-string by default).

Parameters
ParameterTypeDescription
`name`Unique template name.
`template`Raw template string, e.g. ``"Hello, {name}!"``.
`variables`Declared PromptVariable objects. Any undeclared variable is passed through as-is.
`format`Rendering format. Defaults to F_STRING.
`description`Optional human-readable description.

Example

tmpl = StringPromptTemplate(
name="greeting",
template="Hello, {name}! You are a {role}.",
variables=[
PromptVariable("name", required=True),
PromptVariable("role", default="user"),
],
)
result = tmpl.render(name="Alice")
# "Hello, Alice! You are a user."
def __init__(
    name: str,
    template: str,
    variables: list[PromptVariable] | None = None,
    format: RenderFormat = RenderFormat.F_STRING,
    description: str = '',
    version: str = '1.0.0'
) -> None
property name() -> str
property version() -> str
def validate() -> None

Validate that all variables used in the template are declared.

property template() -> str

The raw (un-rendered) template string.

def get_variables() -> list[str]
def render(**kwargs: Any) -> str

Render the template string.

Parameters
ParameterTypeDescription
Returns
TypeDescription
strThe rendered string.
Raises
ExceptionDescription
def partial(**kwargs: Any) -> StringPromptTemplate

Return a new template with kwargs pre-filled.

The returned template has the same declared variables; pre-filled ones will override missing values at render time.

Parameters
ParameterTypeDescription
Returns
TypeDescription
StringPromptTemplateA new StringPromptTemplate with a partial closure.

A store that maintains a full version history for each named template.

Templates are added with push, which appends a new version and makes it the current (latest) version. Previous versions remain accessible via get_version and can be restored with rollback.

Parameters
ParameterTypeDescription
`max_versions`Maximum history depth per name. When the limit is reached the oldest version is evicted. ``0`` means unlimited. Defaults to ``0``.

Example

store = VersionedPromptStore()
store.push("greeting", v1_template) # version 1
store.push("greeting", v2_template) # version 2
store.rollback("greeting") # restores version 1
def __init__(max_versions: int = 0) -> None
def push(
    name: str,
    template: AbstractPromptTemplate,
    metadata: dict[str, Any] | None = None
) -> int

Add a new version of template under name.

Parameters
ParameterTypeDescription
`name`strUnique template name.
`template`AbstractPromptTemplateTemplate to store.
`metadata`dict[str, Any] | NoneArbitrary metadata attached to this version.
Returns
TypeDescription
intThe new version number (1-based, incrementing).
def get(name: str) -> AbstractPromptTemplate

Return the current (latest active) version of name.

Parameters
ParameterTypeDescription
`name`strTemplate name.
Raises
ExceptionDescription
def get_version(
    name: str,
    version: int
) -> AbstractPromptTemplate

Return a specific historical version.

Parameters
ParameterTypeDescription
`name`strTemplate name.
`version`int1-based version number.
Raises
ExceptionDescription
def rollback(
    name: str,
    steps: int = 1
) -> AbstractPromptTemplate

Roll back steps version(s) and return the restored template.

Parameters
ParameterTypeDescription
`name`strTemplate name.
`steps`intNumber of versions to roll back. Defaults to ``1``.
Returns
TypeDescription
AbstractPromptTemplateThe restored (now current) template.
Raises
ExceptionDescription
def list_versions(name: str) -> list[dict[str, Any]]

Return metadata for all stored versions of name (oldest first).

Parameters
ParameterTypeDescription
`name`strTemplate name.
Returns
TypeDescription
list[dict[str, Any]]List of ``{"version": int, "current": bool, "metadata": dict}`` dicts.
Raises
ExceptionDescription

def prompt_template(
    name: str,
    version: str = '1.0',
    tags: list[str] | None = None
) -> Callable[[type], type]

Register a class as a named, versioned prompt template.

Parameters
ParameterTypeDescription
`name`strUnique template name used for retrieval from the registry.
`version`strSemantic version string. Allows multiple versions to coexist.
`tags`list[str] | NoneOptional list of tags for filtering and discovery.
Returns
TypeDescription
Callable[[type], type]Class decorator that registers the template in the prompt registry.

Example

@prompt_template(name="rag.synthesis", version="2.0", tags=["rag"])
class RAGSynthesisPrompt:
system = "You are a helpful assistant."
user = "Context:\n{context}\n\nQuestion: {question}"

Raised when the prompt configuration is invalid.

Base exception for all prompt-related errors.

Raised when a named template is not found in the registry.

Raised when a template cannot be rendered.

Common causes: missing required variable, type mismatch, Jinja2 syntax error.


Raised when a variable fails validation (type, length, allowed values).

Raised on version conflicts or invalid rollback targets.