API Reference
Protocols
Section titled “Protocols”PromptAssemblerProtocol
Section titled “PromptAssemblerProtocol”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.
| Parameter | Type | Description |
|---|---|---|
| `system` | str | System instructions (static, cached). |
| `tools` | list[ToolDefinition] | None | Tool/function definitions. |
| `reference_docs` | list[str] | None | Reference documents as text (semi-static). |
| `few_shot` | list[ChatMessage] | None | Few-shot example messages (static, cached). |
| `history` | list[ChatMessage] | Chat history messages (dynamic). |
| `query` | str | Current user query (dynamic). |
| `provider` | str | Provider name for cache annotation strategy. |
| `dynamic_metadata` | str | None | Timestamps, user IDs, etc. (dynamic). |
| Type | Description |
|---|---|
| list[ChatMessage] | Ordered list of ChatMessage instances ready for the LLM client. |
PromptOptimizerProtocol
Section titled “PromptOptimizerProtocol”Optimizes a rendered prompt for a specific model.
Consumed by: lexigram-ai-platform prompt submodule.
Optimize a prompt for the target model and token budget.
| Parameter | Type | Description |
|---|---|---|
| `prompt` | str | The rendered prompt string to optimize. |
| `model` | str | Target model identifier. |
| `max_tokens` | int | Maximum token budget for the optimized prompt. |
| Type | Description |
|---|---|
| str | The optimized prompt string. |
PromptRegistryProtocol
Section titled “PromptRegistryProtocol”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.
Return all registered template names.
PromptRendererProtocol
Section titled “PromptRendererProtocol”Renders a prompt template with provided variables.
Consumed by: lexigram-ai-platform prompt submodule, lexigram-ai-rag.
Render a template string with the supplied variable mapping.
| Parameter | Type | Description |
|---|---|---|
| `template` | str | The raw template string. |
| `variables` | dict[str, Any] | Mapping of variable names to their values. |
| Type | Description |
|---|---|
| str | The rendered prompt string. |
PromptTemplateProtocol
Section titled “PromptTemplateProtocol”Protocol for prompt templates that render to text or chat messages.
Unique name identifying this template.
Render the template with the supplied variable values.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| str | list[dict[str, str]] | A plain string or a list of ``{"role": ..., "content": ...}`` dicts. |
Return the list of declared variable names.
Classes
Section titled “Classes”AbstractPromptTemplate
Section titled “AbstractPromptTemplate”Common interface for all prompt template implementations.
Subclasses must implement render and expose name.
Unique name for this template (used by the registry).
Semantic version of the template (e.g. ‘1.0.0’).
Render the template given kwargs variable values.
| Type | Description |
|---|---|
| str | list[dict[str, str]] | A plain string (StringPromptTemplate) or a list of chat message dicts ``[{"role": ..., "content": ...}, ...]`` (ChatPromptTemplate). |
Validate that the template declares all the variables it uses.
| Exception | Description |
|---|
Return declared variable names for this template.
The base implementation returns an empty list; subclasses override this to report their declared PromptVariable names.
CacheAwarePromptAssembler
Section titled “CacheAwarePromptAssembler”Prompt assembler that enforces static-before-dynamic ordering and applies provider-specific cache annotations.
Implements PromptAssemblerProtocol and enforces the 7-layer ordering:
- System instructions (STATIC)
- Tool/function definitions (STATIC)
- Reference documents (SEMI-STATIC)
- Few-shot examples (STATIC) ── CACHE BOUNDARY ──
- Chat history (DYNAMIC)
- Current user query (DYNAMIC)
- Dynamic metadata (DYNAMIC)
| Parameter | Type | Description |
|---|---|---|
| `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).
| Parameter | Type | Description |
|---|---|---|
| `counter` | TokenCounterProtocol | Token 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
| Parameter | Type | Description |
|---|---|---|
| `system` | str | System instructions (Layer 1, always static). |
| `tools` | list[ToolDefinition] | None | Tool definitions as list of ToolDefinition objects. |
| `reference_docs` | list[str] | None | Reference document strings (Layer 3). |
| `few_shot` | list[ChatMessage] | None | Few-shot example messages (Layer 4, static). |
| `history` | list[ChatMessage] | Chat history messages (Layer 5, dynamic). |
| `query` | str | Current user query text (Layer 6, dynamic). |
| `provider` | str | Provider key for cache strategy selection. |
| `dynamic_metadata` | str | None | Dynamic metadata string appended after query. |
| Type | Description |
|---|---|
| list[ChatMessage] | Assembled and cache-annotated list of ChatMessage objects. |
ChatPromptTemplate
Section titled “ChatPromptTemplate”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.
| Parameter | Type | Description |
|---|---|---|
| `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
Validate that all variables used in the template are declared.
Render all message slots and return a message list.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| list[dict[str, str]] | List of ``{"role": ..., "content": ...}`` dicts. Only slots that were specified at construction time are included. |
| Exception | Description |
|---|
Render all messages and join them into a single string.
| Parameter | Type | Description |
|---|---|---|
| `separator` | str | String placed between consecutive messages. **kwargs: Variable name → value pairs. |
| Type | Description |
|---|---|
| str | Single 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".
| Parameter | Type | Description |
|---|---|---|
| `role` | str | Message role. |
| `content` | str | Template string for the new message. |
| Type | Description |
|---|---|
| ChatPromptTemplate | A new ChatPromptTemplate. |
ConditionalPrompt
Section titled “ConditionalPrompt”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.
| Parameter | Type | Description |
|---|---|---|
| `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
Validate all nested templates.
Return the union of all branch variable names.
Evaluate conditions in order and render the first matching template.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| str | list[dict[str, str]] | Rendered output of the winning template. |
| Exception | Description |
|---|
FewShotPromptTemplate
Section titled “FewShotPromptTemplate”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.
| Parameter | Type | Description |
|---|---|---|
| `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
Validate that all variables used in the template are declared.
Render the few-shot prompt.
Selects examples, formats each one, then assembles:
prefix + example_separator + examples + example_separator + suffix.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| str | Fully rendered prompt string. |
| Exception | Description |
|---|
InMemoryExampleSelector
Section titled “InMemoryExampleSelector”Simple in-memory example selector.
Selects the first k examples from the provided list by default. Subclass and override select for similarity-based selection.
| Parameter | Type | Description |
|---|---|---|
| `examples` | List of example dicts. | |
| `k` | Maximum number of examples to include. |
Return up to k examples.
The base implementation returns the first k entries. Override this method to implement query-based or similarity-based selection.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| list[dict[str, str]] | List of selected example dicts. |
Append an example to the pool.
InputSanitizer
Section titled “InputSanitizer”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.
| Parameter | Type | Description |
|---|---|---|
| `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. |
Check value for injection patterns.
| Parameter | Type | Description |
|---|---|---|
| `value` | str | String to inspect. |
| `variable_name` | str | Name used in error messages. |
| Type | Description |
|---|---|
| str | The (unchanged) *value* when no injection is detected. |
| Exception | Description |
|---|
Check all string values in variables.
Non-string values are passed through unchanged.
| Parameter | Type | Description |
|---|---|---|
| `variables` | dict[str, object] | Variable name → value mapping. |
| Type | Description |
|---|---|
| dict[str, object] | The same mapping (values are not mutated). |
PartialPromptTemplate
Section titled “PartialPromptTemplate”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).
| Parameter | Type | Description |
|---|---|---|
| `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
Validate the underlying template.
Render by merging pre-filled values with kwargs.
Pre-filled values act as defaults; kwargs take precedence.
PromptConfig
Section titled “PromptConfig”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.
PromptContext
Section titled “PromptContext”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.
PromptInputSanitizedHook
Section titled “PromptInputSanitizedHook”Payload fired after prompt input sanitization completes.
PromptModule
Section titled “PromptModule”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 PromptModulefrom lexigram.ai.prompt.config import PromptConfig
@module( imports=[ PromptModule.configure( PromptConfig(default_format="jinja2") ) ])class AppModule(Module): passError Handling
Prompt rendering and registry lookups surface typed exceptions thatcan 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.
| Parameter | Type | Description |
|---|---|---|
| `config` | PromptConfig | None | PromptConfig or ``None`` to use defaults. **kwargs: Additional keyword arguments forwarded to PromptProvider. |
| Type | Description |
|---|---|
| DynamicModule | A 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.
| Parameter | Type | Description |
|---|---|---|
| `config` | PromptConfig | None | Optional config override. Uses safe test defaults when None. |
| Type | Description |
|---|---|
| DynamicModule | A DynamicModule descriptor. |
PromptPipeline
Section titled “PromptPipeline”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.
| Parameter | Type | Description |
|---|---|---|
| `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"``. |
| Exception | Description |
|---|---|
| ValueError | Fewer 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.
Execute the pipeline and return the final template’s output.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| str | list[dict[str, str]] | The rendered output of the last template in the chain. |
| Exception | Description |
|---|
PromptProvider
Section titled “PromptProvider”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.
Shutdown phase — no cleanup required for prompt registry.
Health check — always healthy (in-process domain provider).
No external backend to ping.
| Parameter | Type | Description |
|---|---|---|
| `timeout` | float | Ignored for in-process providers. |
| Type | Description |
|---|---|
| HealthCheckResult | Always HEALTHY — no external backend to ping. |
PromptRegistry
Section titled “PromptRegistry”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 register( name: str, template: AbstractPromptTemplate, *, overwrite: bool = False ) -> None
Register template under name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Lookup key. |
| `template` | AbstractPromptTemplate | Template instance to register. |
| `overwrite` | bool | Allow replacing an existing registration. Defaults to ``False`` to prevent accidental overwrites. |
| Exception | Description |
|---|---|
| ValueError | *name* already registered and *overwrite* is ``False``. |
def get(name: str) -> AbstractPromptTemplate
Retrieve a template by name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Lookup key. |
| Type | Description |
|---|---|
| AbstractPromptTemplate | The registered template. |
| Exception | Description |
|---|
Return a sorted list of all registered template names.
Remove template name from the registry.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Lookup key. |
| Exception | Description |
|---|
PromptRenderedEvent
Section titled “PromptRenderedEvent”Emitted when a prompt template is rendered with variables.
Consumed by: analytics, prompt optimization, audit.
PromptRenderedHook
Section titled “PromptRenderedHook”Payload fired after prompt rendering produces a formatted payload.
PromptRenderer
Section titled “PromptRenderer”Renders a template string by substituting named variables.
Supports three formats controlled by RenderFormat.
| Parameter | Type | Description |
|---|---|---|
| `format` | Substitution format. Defaults to RenderFormat.F_STRING. |
def __init__(format: RenderFormat = RenderFormat.F_STRING) -> None
property format() -> RenderFormat
The active rendering format.
Substitute variables into template.
| Parameter | Type | Description |
|---|---|---|
| `template` | str | Raw template string. |
| `variables` | dict[str, Any] | Variable name → value mapping. |
| Type | Description |
|---|---|
| str | Rendered string. |
| Exception | Description |
|---|
Extract placeholder names from template.
| Parameter | Type | Description |
|---|---|---|
| `template` | str | Raw template string. |
| Type | Description |
|---|---|
| list[str] | Unique list of variable names detected in the template. |
PromptTemplateResolvedHook
Section titled “PromptTemplateResolvedHook”Payload fired when a named prompt template is resolved from the registry.
PromptVariable
Section titled “PromptVariable”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.
ProviderCacheStrategyRegistry
Section titled “ProviderCacheStrategyRegistry”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)Create an empty registry.
def with_defaults(cls) -> ProviderCacheStrategyRegistry
Create a registry pre-populated with all provider strategies.
Register a strategy for a provider key.
| Parameter | Type | Description |
|---|---|---|
| `provider` | str | Provider name (e.g. "anthropic", "openai"). |
| `strategy` | CacheStrategy | Cache annotation strategy. |
Get the strategy for the given provider.
Falls back to wildcard ’*’ strategy if provider not found, then to PassthroughCacheStrategy default.
| Parameter | Type | Description |
|---|---|---|
| `provider` | str | Provider name. |
| Type | Description |
|---|---|
| CacheStrategy | CacheStrategy for the provider (or wildcard/passthrough fallback). |
RenderFormat
Section titled “RenderFormat”Supported template substitution formats.
StringPromptTemplate
Section titled “StringPromptTemplate”A single-string prompt template with typed variable validation.
Supports all RenderFormat modes (f-string by default).
| Parameter | Type | Description |
|---|---|---|
| `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
Validate that all variables used in the template are declared.
The raw (un-rendered) template string.
Render the template string.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| str | The rendered string. |
| Exception | Description |
|---|
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.
| Parameter | Type | Description |
|---|
| Type | Description |
|---|---|
| StringPromptTemplate | A new StringPromptTemplate with a partial closure. |
VersionedPromptStore
Section titled “VersionedPromptStore”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.
| Parameter | Type | Description |
|---|---|---|
| `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 1store.push("greeting", v2_template) # version 2store.rollback("greeting") # restores version 1def push( name: str, template: AbstractPromptTemplate, metadata: dict[str, Any] | None = None ) -> int
Add a new version of template under name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Unique template name. |
| `template` | AbstractPromptTemplate | Template to store. |
| `metadata` | dict[str, Any] | None | Arbitrary metadata attached to this version. |
| Type | Description |
|---|---|
| int | The new version number (1-based, incrementing). |
def get(name: str) -> AbstractPromptTemplate
Return the current (latest active) version of name.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Template name. |
| Exception | Description |
|---|
def get_version( name: str, version: int ) -> AbstractPromptTemplate
Return a specific historical version.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Template name. |
| `version` | int | 1-based version number. |
| Exception | Description |
|---|
def rollback( name: str, steps: int = 1 ) -> AbstractPromptTemplate
Roll back steps version(s) and return the restored template.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Template name. |
| `steps` | int | Number of versions to roll back. Defaults to ``1``. |
| Type | Description |
|---|---|
| AbstractPromptTemplate | The restored (now current) template. |
| Exception | Description |
|---|
Return metadata for all stored versions of name (oldest first).
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Template name. |
| Type | Description |
|---|---|
| list[dict[str, Any]] | List of ``{"version": int, "current": bool, "metadata": dict}`` dicts. |
| Exception | Description |
|---|
Functions
Section titled “Functions”prompt_template
Section titled “prompt_template”
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.
| Parameter | Type | Description |
|---|---|---|
| `name` | str | Unique template name used for retrieval from the registry. |
| `version` | str | Semantic version string. Allows multiple versions to coexist. |
| `tags` | list[str] | None | Optional list of tags for filtering and discovery. |
| Type | Description |
|---|---|
| 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}"Exceptions
Section titled “Exceptions”PromptConfigError
Section titled “PromptConfigError”Raised when the prompt configuration is invalid.
PromptError
Section titled “PromptError”Base exception for all prompt-related errors.
PromptNotFoundError
Section titled “PromptNotFoundError”Raised when a named template is not found in the registry.
PromptRenderError
Section titled “PromptRenderError”Raised when a template cannot be rendered.
Common causes: missing required variable, type mismatch, Jinja2 syntax error.
PromptValidationError
Section titled “PromptValidationError”Raised when a variable fails validation (type, length, allowed values).
PromptVersionError
Section titled “PromptVersionError”Raised on version conflicts or invalid rollback targets.