Initial upload: Local LLM Prompt Manager CLI tool
Some checks failed
CI / test (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / build (push) Has been cancelled

This commit is contained in:
2026-02-05 20:56:03 +00:00
parent 33418d8218
commit b8f7594e50

59
src/templates.py Normal file
View 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)