Templating & macros
Every prompt Marginalia sends is rendered from a template: the master template, the user prompt, lorebook entries and the summary prompt. Templates are Handlebars with SillyTavern-compatible macros on top. This page explains how that is implemented and how to add variables and macros. What users can write is documented in the user guide: Prompt templates and the Macro reference.
The texts of the agents are the exception: the system prompt, the compaction prompt and the instructions of an
agent (Defaults.agentPrompt() and the others around it) are plain text, put into the request as they are, with no
Handlebars and no macros.
The built-in prompts and their languages
The built-in templates (what an empty field of a book, a folder and the settings stands for) are the methods of Defaults
(masterTemplate(), userPrompt(), summaryPrompt(), redraftSystemPrompt(), agentRunnerNote()...). Defaults is an
object, not a set of constants: the English texts, with DefaultsJA, DefaultsFR, DefaultsES, DefaultsDE, DefaultsIT and DefaultsKO overriding every text method. Italian and Korean exist only as prompt languages, the interface has no bundle for them; the plugins with prompts translate all of them (PluginLocalizationBundle.ES, DE, IT, KO as keys of forPromptLanguage).
An extension can bring more languages: ExtensionHasLocalizedPrompts.getPromptDefaults() returns its Defaults subclasses,
which ExtensionPromptsRegistrar (a listener of the extensions) registers with MarginaliaLocalization.registerDefaults when the extension is loaded and removes on unload (the
Chinese localization plugin brings DefaultsZH this way; a language that already has prompts is refused, the ones of the
application can't be removed). MarginaliaLocalization.getDefaults() returns the one of the prompt language of the session,
getDefaults(language) the one of a language (English when it has none). Defaults.builtIn() lists the application's own,
Defaults.all() every language there is now (a snapshot replaced when an extension adds or removes one) for code that has to
recognize a text in any language (AgentDiagnostics rebuilds its patterns when the snapshot changes,
AgentTranscriptRenderer).
The prompt language is the user's setting UserSetting.promptLanguage (null is English; the combo box Prompt language
of the Templates tab, UserPart.showDefaultPrompts puts the texts of the chosen language into the placeholders before it is
saved). It is independent of the language of the interface: Main.proceedWithLogin and UserPart.save copy it into
SessionPoint.promptLanguage, which LocalizationImpl.getPromptLanguage() reads (English without a session or for a language
without texts). An agent run puts the language of its agent there instead (AgentRequestAttributes); the runner and
CheckpointServiceImpl (rewind from the interface) ask for the language of the run explicitly. PromptField.fallback(Defaults)
takes the texts, so ManuscriptService.resolve falls back to fallback(loc.getDefaults()).
A translation keeps every Handlebars tag of the English text (the sections in the same order, the variables may move with
the word order) and every String.format placeholder of the agent texts, and the notices of a run start with its
agentNoticePrefix(): DefaultsTranslationTest checks all of it and that every text method is overridden, and
DefaultTemplatesTest validates the templates of every language against their data classes. A new text is a method of
Defaults plus its override in both translations. The plugins do the same with their own defaults object, see
Texts in several languages.
The code is in domain/templates/ (data objects, context, variables), domain/templates/macros/ (translator,
helpers, macro registry) and domain/service/impl/TemplateServiceImpl.java.
Rendering in one picture
flowchart LR
T["template text<br/>(SillyTavern macros<br/>+ Handlebars)"] --> MT["MacroTranslator"]
MT --> HB["pure Handlebars source<br/>+ literal table"]
HB --> C["Handlebars.compileInline<br/>(cached)"]
C --> R["apply(Context)"]
D["TemplateData<br/>+ TemplateContext"] --> R
H["MacroHelpers<br/>st_* helpers"] --> R
R --> P["postProcess<br/>({{trim}})"]
P --> O["prompt text"]TemplateService.processTemplate(template, name, data):
-
Translate the SillyTavern syntax into plain Handlebars (
MacroTranslator.translate). -
Compile the result with Handlebars. Compiled templates are cached by template text (Caffeine, 500 entries, 24 h after last access), so a lorebook entry is parsed once, not on every generation.
-
Render it against a Handlebars
Contextbuilt from theTemplateData(MacroHelpers.createContext). -
Post-process the output:
{{trim}}markers are removed together with the newlines around them.
Handlebars runs with EscapingStrategy.NOOP - the output is a prompt, not HTML, so quotes, & and < stay as
they are.
isValidTemplate(template, name) only does steps 1-2, so it catches syntax errors. isValidTemplate(template, name, dataClass) also walks the compiled template (Template.collect of variables and sections, in all branches) and
reports names that would end in helperMissing (see ValidationResult.unknownNames(). They are warnings, isValid() stays true; the UI shows them as the field's helper
text (TemplateHints.showWarnings). Names relative to the current context (this, ., ../x, @index) and
parameters ({{#if name}}) are not checked.
Where templates are rendered
The order of the [generation pipeline]
Closest parts and summaries
closest-message::n, closest-summary::n and current-message (TemplateData.closestMessage / closestSummary /
currentMessage) read the TemplateContext: the story messages (the position counts back from the end), summaryLookup (an
IntFunction set by GenerationStepBase.createTemplateContext, it walks the branch from its end and reads the n-th summary only
when a template asks, a long branch has many) and currentMessage (the stored text of GenerationRequest.getNode(), set for a
regenerate and a swipe only). Their argument may be a macro: the translator turns the nested macro into a sub-expression
before the helper is called.
Macros that run commands
{{command::name::arg::arg}} (Macros, TemplateData.command) runs a command
that is declared readOnly and availableInMacros; the macro is static, so templates compiled (and cached) before an extension
brought the command keep working. TemplateData.command hands the call to the CommandMacroRunner of the
TemplateContext; a render without one (the summaries, the exports) leaves the macro empty. A name that is not such a command
renders as Error, like a variable that does not exist.
The generation sets a CommandMacros (domain/service/impl/generation) in GenerationStepBase.createTemplateContext. It
runs the command lazily, when the helper is reached, with CommandService.executePositional in the scope
CommandScopes.forManuscript(book) and waits for the answer on the worker thread of the generation (120 seconds at most; a
command that fails or runs out of time renders nothing and is not kept). The answers are kept in the attributes of the part the
generation continues from (the last part of the branch before the new one, commandMacroCache: an object with
name+arguments as the key), so the estimation render of the master template, the real one, the lorebook entries and a second
generation from the same part run the command once. A regenerate and a swipe (GenerationRequestType) do not read what is
kept, and the first answer they get replaces everything kept before; the first part of a book has nothing to keep it with
(the answers live for that generation only). Saving the answer is best effort, a failure is logged and the generation goes on.
TemplateContext.fork shares the runner, so a dry render does not run the commands twice.
Expressions
{{eval::expression}} (Macros, TemplateData.eval) gives true or false for a small expression language, parsed and evaluated by
ExpressionEvaluator (domain.templates.macros): or / ||, and / &&, not / !, parentheses, the comparisons == != < <= > >= ~= contains has and operands that are quoted texts, numbers, true / false, names, .local and $global variables. The whole expression
is read before anything is evaluated and every name is checked then (Environment.knows), so an unknown name is an error also in an
and / or branch that is not reached. TemplateData.ExpressionEnvironment answers the names: a property of the data or of the
TemplateContext (hasProperty / resolveProperty), else a macro with no arguments (Macros.find, minArgs == 0, not if), and
the variables through getVar. A text is only ever in quotes, on purpose: unlike the plain text of {{if text}} (always true), a word
that is not a name cannot turn a typo into a true result. An ExpressionException (syntax, unknown name) is logged at debug level and the
macro renders MacroHelpers.MISSING_VALUE (Error), like any name that is not defined; the lorebook condition (activationCondition) takes a
result of Error as CONDITION_ERROR. == / != / ~= compare numbers by value when both sides are numbers (BigDecimal), the
ordering operators are false for a side that is not a number, has splits the list at , ; and line breaks. It is not
a Macros.IF condition: {{if {{eval::...}} }} is the way to use it there.
Joining texts
{{join::separator::a::b::c}} (Macros, TemplateData.join) puts the separator between the texts that follow it, any number of
them (macros included, they are evaluated first like every argument). Empty texts are left out, so an optional macro such as
{{getvar::missing}} leaves no stray separator; a single text gives itself, a separator alone gives nothing.