Otera.ChatTemplate (otera v0.1.0)

Copy Markdown View Source

Renders the chat template of a Hugging Face model like apply_chat_template in Python transformers.

template = File.read!("chat_template.jinja")

Otera.ChatTemplate.render(template, [%{role: "user", content: "Hello!"}],
  add_generation_prompt: true,
  variables: %{bos_token: "<|begin_of_text|>"}
)
#=> {:ok, "<|begin_of_text|><|start_header_id|>user<|end_header_id|>..."}

options/1 gives the environment of transformers: trim_blocks and lstrip_blocks, the raise_exception(message) and strftime_now(format) functions, and a tojson filter that does not escape HTML or non-ASCII characters and accepts the ensure_ascii, indent, separators and sort_keys arguments of Python json.dumps.

Key order

tojson prints the keys of a dict in order. A plain Elixir map gives its keys in sorted order, and Python gives them in insertion order. To get the output of transformers for tools or messages that come from JSON, decode the JSON with Otera.JSON.decode!/1, which keeps the key order of the text.

Summary

Functions

Returns the options of the transformers environment, for Otera.parse/2 and Otera.render/3.

Renders messages with a chat template, given as source or as a template that Otera.parse/2 made with options/0.

Functions

options(opts \\ [])

@spec options(keyword()) :: keyword()

Returns the options of the transformers environment, for Otera.parse/2 and Otera.render/3.

Options

  • :now - the local time that strftime_now formats, as a NaiveDateTime. By default, strftime_now formats the current local time.

render(template, messages, opts \\ [])

@spec render(String.t() | Otera.Template.t(), list(), keyword()) ::
  {:ok, String.t()} | {:error, Otera.error()}

Renders messages with a chat template, given as source or as a template that Otera.parse/2 made with options/0.

Options

  • :add_generation_prompt - ends the prompt with the start of an assistant message. The default is false.
  • :continue_final_message - ends the prompt inside the final message, so that the model continues it. true continues the "content" of the message, and a string continues the field with that name. The default is false.
  • :tools - a list of tool definitions in JSON schema form. The default is nil.
  • :documents - a list of documents for retrieval-augmented generation. The default is nil.
  • :variables - other variables of the template, such as the special tokens bos_token and eos_token, or enable_thinking: false for Qwen3.

render!(template, messages, opts \\ [])

@spec render!(String.t() | Otera.Template.t(), list(), keyword()) :: String.t()

Like render/3, but raises the error.