Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Copyright 2026 The OpenWeights Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.alpharomercoma.openweights.core.common.model

/**
* Renders a conversation the way LFM3's own chat template does.
*
* A transcription of `LiquidAI/LFM3-1.7B`'s `chat_template.jinja`, held to it byte for
* byte by `Lfm3PromptTest` against fixtures `tools/executorch/render_reference.py` renders
* from the real template. The GGUF carries the same file (compared 2026-11-15), so a
* compiled LFM3 reads the prompt llama.cpp gives the GGUF. It is not LFM2.5's format: the
* tools are one JSON object a line inside `<tools>` at the foot of the system turn, without
* the OpenAI wrapper; a call is XML parameters, the form Qwen3.5 writes; a result is
* wrapped in `<tool_response>` under a `tool` role; and the assistant opener always carries
* a think tag, left open when reasoning is on and closed empty when it is off.
*
* The template also places pictures, video and tools loaded mid-conversation. The compiled
* path is text only and its tools are fixed for a turn, so none of that is transcribed.
*
* @param verbatimHistory write each assistant turn back as the bytes the runtime was fed
* for it. The template empties the think block of every turn before the last question, the
* KV cache still holds it, and LFM3 is a hybrid model that cannot roll back part of its
* state, so following the template would re-read the conversation on every new question.
* @param includeBos whether to open with `<|startoftext|>`. The fixtures carry it; the
* engine renders without and adds it itself where the runtime does not.
*/
object Lfm3Prompt {

@Suppress("LongParameterList")
fun render(
messages: List<ChatMessage>,
tools: List<ToolDefinition> = emptyList(),
thinking: Boolean = true,
addGenerationPrompt: Boolean = true,
verbatimHistory: Boolean = false,
includeBos: Boolean = true,
): String = buildString {
if (includeBos) append("<|startoftext|>")

val leadingSystem = messages.firstOrNull()?.takeIf { it.role == ChatRole.SYSTEM }
val turns = if (leadingSystem != null) messages.drop(1) else messages

val system = buildString {
append(leadingSystem?.text.orEmpty())
if (tools.isNotEmpty()) {
if (isNotEmpty()) append("\n\n")
append("<tools>")
tools.forEach { append('\n').append(it.asBareToolJson()) }
append("\n</tools>")
}
}
if (system.isNotEmpty()) {
append("<|im_start|>system\n").append(system).append(IM_END)
}

val lastUser = turns.indexOfLast { it.role == ChatRole.USER }
turns.forEachIndexed { index, message ->
append("<|im_start|>").append(message.role.wireName).append('\n')
when (message.role) {
ChatRole.ASSISTANT ->
if (verbatimHistory) {
appendAsGenerated(message.text)
} else {
appendAssistant(message.text, keepThinking = index > lastUser)
}

ChatRole.TOOL -> appendToolResult(message.text)
else -> append(message.text)
}
append(IM_END)
}

if (addGenerationPrompt) {
append("<|im_start|>assistant\n").append(if (thinking) THINK_OPEN else EMPTY_THINK)
}
}

/**
* An assistant turn under the template's own history rules: reasoning is kept after
* the last question and replaced by an empty block before it, and a turn that never
* reasoned gets the empty block either way. The app stores a turn as the raw text the
* model wrote, so a call is already in it in the form the template would have built.
*/
private fun StringBuilder.appendAssistant(text: String, keepThinking: Boolean) {
when {
THINK_CLOSE !in text -> append(EMPTY_THINK).append(text)
keepThinking -> append(text)
else -> append(EMPTY_THINK).append(text.substringAfterLast(THINK_CLOSE).trim())
}
}

/**
* An assistant turn as the bytes the runtime holds for it: the opener it was generated
* under, then what the model wrote. The opener is never in the reply, so it is rebuilt
* from the text, the way [Qwen35Prompt] does: a reply holding a close tag was generated
* under the open tag, one without under the empty block. `assistantHistoryText` may
* have put the open tag back already, so it is taken off first.
*/
private fun StringBuilder.appendAsGenerated(text: String) {
val reply = text.removePrefix(THINK_OPEN)
append(if (THINK_CLOSE in reply) THINK_OPEN else EMPTY_THINK).append(reply)
}

/** A result already wrapped goes in as it is, which is the template's rule. */
private fun StringBuilder.appendToolResult(text: String) {
if (RESPONSE_OPEN in text) {
append(text)
} else {
append(RESPONSE_OPEN).append('\n').append(text).append("\n</tool_response>")
}
}

private const val IM_END = "<|im_end|>\n"
private const val THINK_OPEN = "<think>"
private const val THINK_CLOSE = "</think>"
private const val EMPTY_THINK = "<think></think>"
private const val RESPONSE_OPEN = "<tool_response>"
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ internal fun ToolDefinition.asToolJson(): String {
""""description": ${description.jsonQuoted()}, "parameters": $schema}}"""
}

/**
* A tool as the function object alone, which is how LFM3's template lists one: the same
* spelling as [asToolJson] without the OpenAI wrapper around it.
*/
internal fun ToolDefinition.asBareToolJson(): String =
"""{"name": ${name.jsonQuoted()}, "description": ${description.jsonQuoted()}, """ +
""""parameters": ${parametersJson.canonicalJson()}}"""

/**
* [this] JSON with its whitespace laid out the way `json.dumps` does by default: nothing
* between tokens except `", "` after a member and `": "` after a key.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,12 @@ object PromptTemplates {
"phi4mini" in name -> Phi4Template
"gemma3" in name -> Gemma3Template
"lfm25" in name -> Lfm25Template
"lfm3" in name -> Lfm3Template
else -> null
}
}

private val EXCLUDED = listOf("vl", "vision", "coder", "guard")
private val EXCLUDED = listOf("vl", "vision", "coder", "guard", "omni")

/** Families this build can render, for an error message that tells the user something. */
val known: List<String> = listOf(
Expand All @@ -145,6 +146,7 @@ object PromptTemplates {
"Phi-4-mini",
"Gemma 3",
"LFM 2.5",
"LFM3",
"LFM2.5-VL",
)
}
Expand Down Expand Up @@ -350,3 +352,25 @@ private object Lfm25Template : PromptTemplate {
thinking: Boolean,
): String = Lfm25Prompt.render(messages, tools, verbatimHistory = true, includeBos = false)
}

/**
* [Lfm3Prompt] as a [PromptTemplate], verbatim for the same reason as [Lfm25Template].
* Unlike LFM2.5, this template has a switch for reasoning, so the toggle does something.
*/
private object Lfm3Template : PromptTemplate {
override val bosToken: String = "<|startoftext|>"
override val stopMarkers: List<String> = listOf(IM_END)
override val supportsThinking: Boolean = true

override fun render(
messages: List<ChatMessage>,
tools: List<ToolDefinition>,
thinking: Boolean,
): String = Lfm3Prompt.render(
messages,
tools,
thinking,
verbatimHistory = true,
includeBos = false,
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
* Copyright 2026 The OpenWeights Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.github.alpharomercoma.openweights.core.common.model

/**
* Prompts rendered by the `chat_template` that LiquidAI/LFM3-1.7B ships with.
*
* Generated, not written. `tools/executorch/render_reference.py` fetches the template from
* the Hub and renders it with Jinja over the same conversations `Lfm3PromptTest` builds,
* so these strings are what upstream produces rather than anybody's idea of what it should
* produce. Do not edit by hand: rerun the script and read the diff.
*/
internal object Lfm3PromptFixtures {
const val PLAIN: String =
"<|startoftext|><|im_start|>user\n" +
"What is the capital of Japan?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"

const val THINKING_DISABLED: String =
"<|startoftext|><|im_start|>user\n" +
"What is the capital of Japan?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think></think>"

const val WITH_SYSTEM: String =
"<|startoftext|><|im_start|>system\n" +
"You are a terse assistant.<|im_end|>\n" +
"<|im_start|>user\n" +
"What is the capital of Japan?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"

const val WITH_TOOLS: String =
"<|startoftext|><|im_start|>system\n" +
"<tools>\n" +
"{\"name\": \"web_search\", \"description\": \"Search the web for current informa" +
"tion.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"query\": {\"t" +
"ype\": \"string\", \"description\": \"What to search for\"}}, \"required\": [\"q" +
"uery\"]}}\n" +
"</tools><|im_end|>\n" +
"<|im_start|>user\n" +
"What is the weather in Manila?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"

const val WITH_SYSTEM_AND_TOOLS: String =
"<|startoftext|><|im_start|>system\n" +
"You are a terse assistant.\n" +
"\n" +
"<tools>\n" +
"{\"name\": \"web_search\", \"description\": \"Search the web for current informa" +
"tion.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"query\": {\"t" +
"ype\": \"string\", \"description\": \"What to search for\"}}, \"required\": [\"q" +
"uery\"]}}\n" +
"</tools><|im_end|>\n" +
"<|im_start|>user\n" +
"What is the weather in Manila?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"

const val PRIOR_THINKING_DROPPED: String =
"<|startoftext|><|im_start|>user\n" +
"What is 2+2?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think></think>Four.<|im_end|>\n" +
"<|im_start|>user\n" +
"And 3+3?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>Also simple.</think>Six.<|im_end|>\n"

const val TOOL_RUN: String =
"<|startoftext|><|im_start|>system\n" +
"<tools>\n" +
"{\"name\": \"web_search\", \"description\": \"Search the web for current informa" +
"tion.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"query\": {\"t" +
"ype\": \"string\", \"description\": \"What to search for\"}}, \"required\": [\"q" +
"uery\"]}}\n" +
"</tools><|im_end|>\n" +
"<|im_start|>user\n" +
"What is the weather in Manila?<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think></think><tool_call>\n" +
"<function=web_search>\n" +
"<parameter=query>\n" +
"Manila weather\n" +
"</parameter>\n" +
"</function>\n" +
"</tool_call><|im_end|>\n" +
"<|im_start|>tool\n" +
"<tool_response>\n" +
"Manila: 31C, humid.\n" +
"</tool_response><|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"

const val TWO_TOOL_RESULTS: String =
"<|startoftext|><|im_start|>system\n" +
"<tools>\n" +
"{\"name\": \"web_search\", \"description\": \"Search the web for current informa" +
"tion.\", \"parameters\": {\"type\": \"object\", \"properties\": {\"query\": {\"t" +
"ype\": \"string\", \"description\": \"What to search for\"}}, \"required\": [\"q" +
"uery\"]}}\n" +
"</tools><|im_end|>\n" +
"<|im_start|>user\n" +
"Compare Manila and Tokyo.<|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think></think>Looking both up.<|im_end|>\n" +
"<|im_start|>tool\n" +
"<tool_response>\n" +
"Manila: 31C.\n" +
"</tool_response><|im_end|>\n" +
"<|im_start|>tool\n" +
"<tool_response>\n" +
"Tokyo: 22C.\n" +
"</tool_response><|im_end|>\n" +
"<|im_start|>assistant\n" +
"<think>"
}
Loading
Loading