Skip to main content

Prompt Engineering API Specification

Version: v1.1.9 | Status: Active | Last Updated: February 2026

Overview​

The prompt_engineering module provides template management, version tracking, optimization strategies, and evaluation scoring for prompts. It covers the full lifecycle from authoring and versioning through optimization and quality assessment.

Templates API​

PromptTemplate (dataclass)​

A reusable prompt template with {variable_name} placeholders.

FieldTypeDefaultDescription
namestr(required)Template name
template_strstr(required)Template string with {var} placeholders
variableslist[str]auto-detectedExpected variable names
versionstr"1.0.0"Version string
metadatadict[str, Any]{}Arbitrary metadata

Methods:

MethodSignatureReturnsDescription
render(**kwargs: Any) -> strstrRender with variable values. Raises KeyError if missing
validate(**kwargs: Any) -> list[str]list[str]List of missing variable names
to_dict() -> dict[str, Any]dictConvert to dictionary
from_dict(data: dict) -> PromptTemplatePromptTemplateCreate from dictionary (classmethod)

TemplateRegistry​

Registry for managing collections of prompt templates.

TemplateRegistry(config: Any | None = None)
MethodSignatureReturnsDescription
add(template: PromptTemplate) -> NoneNoneRegister. Raises ValueError if name exists
update(template: PromptTemplate) -> NoneNoneAdd or replace
get(name: str) -> PromptTemplatePromptTemplateRetrieve. Raises KeyError if not found
remove(name: str) -> PromptTemplatePromptTemplateRemove and return. Raises KeyError if not found
list() -> list[str]list[str]Sorted template names
list_templates() -> list[PromptTemplate]list[PromptTemplate]All templates sorted by name
render(template_name, /, **kwargs) -> strstrRender template by name
search(query: str) -> list[PromptTemplate]list[PromptTemplate]Search by name or metadata keyword
export_all() -> list[dict]list[dict]Export all as dictionaries
import_all(data, overwrite=False) -> intintImport from dicts; returns count imported

Properties: size (number of templates).

get_default_registry​

def get_default_registry() -> TemplateRegistry

Returns the module-level default template registry singleton.


Versioning API​

PromptVersion (dataclass)​

FieldTypeDefaultDescription
versionstr(required)Version string (e.g., "1.0.0")
templatePromptTemplate(required)The template at this version
created_atdatetimenow (UTC)Creation timestamp
changelogstr""Description of changes
authorstr""Who made the change
metadatadict[str, Any]{}Additional metadata

Methods: to_dict(), from_dict() (classmethod).

VersionManager​

Manages version history for prompt templates with diff and rollback.

VersionManager()
MethodSignatureReturnsDescription
create_version(template, changelog, author, bump, version_override) -> PromptVersionPromptVersionCreate new version (auto-increments)
get_version(template_name, version=None) -> PromptVersionPromptVersionGet specific or latest version
list_versions(template_name) -> list[PromptVersion]list[PromptVersion]All versions chronologically
list_template_names() -> list[str]list[str]All template names with versions
diff(template_name, version_a, version_b) -> strstrUnified diff between versions
rollback(template_name, target_version) -> PromptVersionPromptVersionCreate rollback version
get_latest_version(template_name) -> PromptVersionPromptVersionLatest version shortcut
version_count(template_name) -> intintNumber of versions
export_history(template_name) -> list[dict]list[dict]Export version history as dicts

create_version() parameters:

ParameterTypeDefaultDescription
templatePromptTemplate(required)Template to version
changelogstr""Change description
authorstr""Author name
bumpstr"patch"Version bump level: "major", "minor", "patch"
version_override`str \None`None Explicit version (overrides auto-increment)

Optimization API​

OptimizationStrategy (Enum)​

ValueDescription
CONCISEReduce verbosity, remove filler phrases
DETAILEDAdd structure with role, task, constraints, output format sections
CHAIN_OF_THOUGHTAdd step-by-step reasoning scaffold
FEW_SHOTInject examples before the prompt

OptimizationResult (dataclass)​

FieldTypeDefaultDescription
originalPromptTemplate(required)Original template
optimizedPromptTemplate(required)Optimized template
strategyOptimizationStrategy(required)Strategy used
changeslist[str][]Description of changes made
metadatadict[str, Any]{}Additional metadata

Properties:

PropertyTypeDescription
token_reduction_estimatefloatRatio of optimized/original word count (< 1.0 = shorter)

PromptOptimizer​

PromptOptimizer()
MethodSignatureReturnsDescription
optimize(template, strategy, **kwargs) -> OptimizationResultOptimizationResultOptimize with strategy. Raises ValueError for unknown strategy
bulk_optimize(templates, strategy, **kwargs) -> list[OptimizationResult]list[OptimizationResult]Optimize multiple templates
available_strategies() -> list[str]list[str]Sorted strategy value strings
set_few_shot_examples(examples: list[dict[str, str]]) -> NoneNoneSet examples for FEW_SHOT strategy

Evaluation API​

EvaluationCriteria (dataclass)​

FieldTypeDefaultDescription
namestr(required)Criterion name
weightfloat(required)Weight for weighted average
scorer_fnCallable[[str, str], float](required)Takes (prompt, response), returns 0.0-1.0
descriptionstr""Human-readable description

Methods:

MethodSignatureReturnsDescription
score(prompt: str, response: str) -> floatfloatRun scorer, clamped to 0.0-1.0

EvaluationResult (dataclass)​

FieldTypeDefaultDescription
promptstr(required)The evaluated prompt
responsestr(required)The evaluated response
scoresdict[str, float]{}Per-criterion scores
weighted_scorefloat0.0Weighted total score
detailsdict[str, Any]{}Additional details

Built-in Scorer Functions​

score_response_length(prompt: str, response: str) -> float # Length appropriateness
score_relevance(prompt: str, response: str) -> float # Keyword overlap
score_structure(prompt: str, response: str) -> float # Formatting quality
score_completeness(prompt: str, response: str) -> float # Addresses intent

get_default_criteria​

def get_default_criteria() -> list[EvaluationCriteria]

Returns: relevance (0.35), completeness (0.30), structure (0.20), length (0.15).

PromptEvaluator​

PromptEvaluator(criteria: list[EvaluationCriteria] | None = None)
MethodSignatureReturnsDescription
evaluate(prompt, response, criteria=None) -> EvaluationResultEvaluationResultEvaluate a pair
evaluate_batch(pairs: list[tuple[str, str]]) -> list[EvaluationResult]list[EvaluationResult]Evaluate multiple pairs
compare_responses(prompt, responses) -> dictdictCompare responses with rankings and stats
add_criteria(criteria: EvaluationCriteria) -> NoneNoneAdd a criterion
remove_criteria(name: str) -> boolboolRemove by name
criteria_names() -> list[str]list[str]Sorted criterion names

Properties: criteria (list copy).

Error Handling​

ExceptionRaised When
KeyErrorTemplate not found in registry; missing render variables; version not found
ValueErrorDuplicate template name in registry (use update instead); unknown optimization strategy
PromptEngineeringErrorModule-level operation failures