HuggingfaceClient.Jinja (huggingface_client v0.1.0)

Copy Markdown View Source

A Jinja2-compatible template engine for rendering HuggingFace chat templates.

Supports a broad subset of Jinja2 including:

  • Variable interpolation {{ expr }}
  • Control tags {% if %}, {% for %}, {% set %}, {% macro %}
  • Filters: upper, lower, trim, reverse, length, first, last, join, replace, default, truncate, title, sort, unique
  • loop object: .index, .index0, .first, .last, .length
  • Arithmetic: +, -, *, //, **; concatenation: ~
  • Index/slice access: x[0], x[-1], x[1:3], x["key"]
  • is tests: defined, string, integer, none
  • in / not in operators
  • Ternary: "yes" if cond else "no"
  • Comments {# ... #}
  • range(n) / range(start, stop)

Usage

{:ok, "Hello, World!"} = HuggingfaceClient.Jinja.render("Hello, {{ name }}!", %{"name" => "World"})

{:ok, text} = HuggingfaceClient.Jinja.apply_chat_template(template, messages, %{"add_generation_prompt" => true})

Summary

Functions

Applies a chat template (Jinja2) to a list of messages.

Renders a Jinja2 template string with the given variable map.

Functions

apply_chat_template(template, messages, extra_vars \\ %{})

@spec apply_chat_template(String.t(), list(), map()) ::
  {:ok, String.t()} | {:error, term()}

Applies a chat template (Jinja2) to a list of messages.

extra_vars is merged into the template context alongside messages.

render(template, vars \\ %{})

@spec render(String.t(), map()) :: {:ok, String.t()} | {:error, term()}

Renders a Jinja2 template string with the given variable map.

Returns {:ok, rendered_string} or {:error, reason}.