Skip to main content
Version: Next

mellea.formatters.template_formatter

TemplateFormatter: Jinja2-template-based formatter for legacy backends.

TemplateFormatter extends ChatFormatter to look up a per-component Jinja2 template at rendering time, allowing each Component type to control its own prompt representation. Template discovery walks a configurable template_path and the built-in templates directory; results are cached in a SimpleLRUCache for performance. Use this formatter when your backend requires hand-crafted prompts rather than a generic chat-message rendering.

Classes​

CLASS TemplateFormatter ​

Formatter that uses Jinja2 templates to render components into prompt strings.

Template discovery walks a configurable template_path and the built-in templates directory. Results are optionally cached in a SimpleLRUCache for performance. Use this formatter when your backend requires hand-crafted prompts rather than generic chat-message rendering.

Args:

  • model_id: Describes the model for which templates will be looked up. Should match the template directory structure.
  • template_path: An alternate location where templates can be found. Will be preferred over all other template directories even if a less exact match is found. Defaults to "".
  • use_template_cache: When True, caches template lookup results. Set to False if you plan to change model_id or template_path after construction. Defaults to True.

Methods:

FUNC print ​

print(self, c: Span) -> str

Render a component, content block, or model output to a string using a Jinja2 template.

Args:

  • c: The component, content block, or model output to render.

Returns:

  • The rendered string representation of the component.

FUNC prompt_template_for ​

prompt_template_for(self, action: Span) -> tuple[str | None, dict[str, Any] | None]

Return the template source and rendered variables for an action.

Recovers the Jinja source and the post-substitution variables the formatter would render action with, without producing the rendered string. Best-effort and never raises: returns (None, None) when action has no template (a CBlock, a ModelOutputThunk, or a component whose format_for_llm returns a plain string) or when lookup or rendering fails.

Args:

  • action: The component or block a backend generates from.

Returns:

  • A (template_source, variables) tuple, where variables maps each
  • template argument to its stringified value, or (None, None) when no
  • template applies.