Initial upload: Local LLM Prompt Manager CLI tool
This commit is contained in:
59
src/templates.py
Normal file
59
src/templates.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
"""Template engine for prompt variable substitution."""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from jinja2 import BaseLoader, Environment
|
||||||
|
from jinja2.exceptions import UndefinedError
|
||||||
|
|
||||||
|
from .models import Prompt
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateEngine:
|
||||||
|
"""Handles Jinja2 template rendering for prompts."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.env = Environment(
|
||||||
|
loader=BaseLoader(),
|
||||||
|
trim_blocks=True,
|
||||||
|
lstrip_blocks=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def render(self, template: str, variables: dict[str, Any]) -> str:
|
||||||
|
"""Render a template with the provided variables."""
|
||||||
|
try:
|
||||||
|
tmpl = self.env.from_string(template)
|
||||||
|
return tmpl.render(**variables)
|
||||||
|
except UndefinedError as e:
|
||||||
|
raise ValueError(f"Missing template variable: {e}") from None
|
||||||
|
|
||||||
|
def render_prompt(self, prompt: Prompt, variables: dict[str, Any]) -> str:
|
||||||
|
"""Render a prompt with the provided variables."""
|
||||||
|
missing = self._check_required_variables(prompt, variables)
|
||||||
|
if missing:
|
||||||
|
raise ValueError(f"Missing required variables: {', '.join(missing)}")
|
||||||
|
return self.render(prompt.template, variables)
|
||||||
|
|
||||||
|
def _check_required_variables(
|
||||||
|
self, prompt: Prompt, variables: dict[str, Any]
|
||||||
|
) -> list[str]:
|
||||||
|
"""Check if all required variables are provided."""
|
||||||
|
required = prompt.get_required_variables()
|
||||||
|
return [v for v in required if v not in variables or variables[v] is None]
|
||||||
|
|
||||||
|
def extract_variables(self, template: str) -> set[str]:
|
||||||
|
"""Extract variable names from a template."""
|
||||||
|
try:
|
||||||
|
ast = self.env.parse(template)
|
||||||
|
variables = self.env.find_undeclared_variables(ast)
|
||||||
|
return variables
|
||||||
|
except Exception:
|
||||||
|
return set()
|
||||||
|
|
||||||
|
def validate_variables(
|
||||||
|
self, prompt: Prompt, variables: dict[str, Any]
|
||||||
|
) -> list[str]:
|
||||||
|
"""Validate that provided variables are valid for the prompt."""
|
||||||
|
extracted = self.extract_variables(prompt.template)
|
||||||
|
provided = set(variables.keys())
|
||||||
|
invalid = provided - extracted
|
||||||
|
return list(invalid)
|
||||||
Reference in New Issue
Block a user