Skip to content

Add a MustacheTemplateRenderer (with optional constraint hook) for prompt templating #4885

@Hoyaspark

Description

@Hoyaspark

Please do a quick search on GitHub issues first, the feature you are about to request might have already been requested.

Expected Behavior

Spring AI should expose a TemplateRenderer backed by the Mustache JVM implementation so prompts can leverage loops, dotted notation, and section/conditional blocks.

Typical usage

val renderer = MustacheTemplateRenderer.builder().build()

val prompt = renderer.apply(
    """
    Query: {{query}}

    {{#items}}
    - {{name}} ({{pricing.salePrice}})
    {{/items}}
    """.trimIndent(),
    mapOf("query" to userQuery, "items" to rerankedItems)
)

Internally the renderer could follow this structure

class MustacheTemplateRenderer(
    private val constraints: List<Constraint> = emptyList(),
    private val mustacheFactory: DefaultMustacheFactory = DefaultMustacheFactory()
) : TemplateRenderer {

    override fun apply(template: String, variables: Map<String, Any?>): String {
        val sanitized = constraints.fold(variables, ::applyConstraint) // optional hook for apps
        val mustache = mustacheFactory.compile(StringReader(template), "prompt")
        return StringWriter().also { mustache.execute(it, sanitized) }.toString()
    }
}

That constraints.fold hook isn’t required for a first release, but offering some extension point (or builder slot) would let applications plug in limit/filter/range-style processors before rendering without forking the renderer.

Current Behavior

The only built-in renderer today is the StringTemplate (ST) version (spring-ai-template-st/src/main/java/org/springframework/ai/template/st/StTemplateRenderer.java:32).

ST excels at simple key replacement but doesn’t provide Mustache semantics like section blocks ({{#items}}…{{/items}}), inverted sections ({{^items}}), or dotted access ({{item.price.value}}), so expressing structured prompt layouts is cumbersome.

There’s also no standard way to preprocess collection variables before rendering.

Context

Several teams need Mustache-style templating to keep prompts readable, iterate through structured data, and optionally filter/limit lists before they reach the LLM.

A first-party MustacheTemplateRenderer (similar to the ST module) would remove the need for each project to reimplement it and would let us enable it via configuration.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions