Implementation of Template-based Text Generation System
Template-based text generation is creating documents where the structure is fixed and content is filled dynamically from data or via LLM. Commercial proposals, contracts, reports, notifications — billions of documents per year are created this way.
Two Approaches to Templating
Deterministic templates (Jinja2, Word templates): simple variable substitution. Predictable, auditable, no hallucinations. Suitable for legally significant documents.
from jinja2 import Template
template = Template("""
Dear {{ client_name }},
Your order #{{ order_id }} for {{ amount | format_currency }}
is ready for pickup. Address: {{ address }}.
{% if special_note %}
Note: {{ special_note }}
{% endif %}
""")
text = template.render(client_name="Ivan Petrov", order_id="12345", ...)
LLM-based template generation: structure defined via prompt, LLM fills content with context adaptation. Suitable for marketing texts, personalized emails.
def generate_from_template(data: dict, template_type: str) -> str:
prompt = f"""Create a {template_type} based on the data:
{json.dumps(data, ensure_ascii=False, indent=2)}
Requirements:
- Business style
- Length: 3–5 paragraphs
- Must mention: {', '.join(data.keys())}"""
return llm.complete(prompt)
Hybrid Approach
Best of both: Jinja2 for structure and required data, LLM for "live" text blocks:
[Header: {{client_name}}, {{date}}] ← deterministic
[Intro paragraph: LLM generates greeting adapted to client context]
[Data table: {{products_table}}] ← deterministic
[Conclusion: LLM generates personalized call-to-action]
[Signature: {{manager_name}}, {{company}}] ← deterministic
Quality Control
Required field validation: after generation, presence of all key data (name, amount, date) is checked via regex or LLM validation.
Consistency check: client name must match throughout the document, amounts in words and numbers must match.
A/B testing templates: different variants sent to different segments, conversion compared.
For production: version templates in Git, separate review process for changes in legal documents.







