spring-projects/spring-ai · error · IllegalArgumentException

The template string is not valid.

Error message

The template string is not valid.

What it means

StTemplateRenderer.createST wraps StringTemplate group/template construction; any exception while creating the ST from the template string is rethrown as IllegalArgumentException('The template string is not valid.', ex). The underlying cause (from the CommonsLoggingStErrorListener/ST internals) explains what syntax was wrong.

Source

Thrown at spring-ai-template-st/src/main/java/org/springframework/ai/template/st/StTemplateRenderer.java:123

		ST st = createST(template);
		for (Map.Entry<String, ? extends @Nullable Object> entry : variables.entrySet()) {
			st.add(entry.getKey(), entry.getValue());
		}
		if (this.validationMode != ValidationMode.NONE) {
			validate(st, variables);
		}
		return st.render();
	}

	private ST createST(String template) {
		try {
			STGroup group = new STGroup(this.startDelimiterToken, this.endDelimiterToken);
			group.setListener(new CommonsLoggingStErrorListener(logger));
			return new ST(group, template);
		}
		catch (Exception ex) {
			throw new IllegalArgumentException("The template string is not valid.", ex);
		}
	}

	/**
	 * Validates that all required template variables are provided in the model. Returns
	 * the set of missing variables for further handling or logging.
	 * @param st the StringTemplate instance
	 * @param templateVariables the provided variables
	 * @return set of missing variable names, or empty set if none are missing
	 */
	private Set<String> validate(ST st, Map<String, ? extends @Nullable Object> templateVariables) {
		Set<String> templateTokens = getInputVariables(st);
		Set<String> modelKeys = templateVariables.keySet();
		Set<String> missingVariables = new HashSet<>(templateTokens);
		missingVariables.removeAll(modelKeys);

		if (!missingVariables.isEmpty()) {
			if (this.validationMode == ValidationMode.WARN) {

View on GitHub (pinned to 98a7beda4f)

Solutions

  1. Inspect the wrapped cause 'ex' — it names the exact ST syntax error and position
  2. Escape or reformat literal braces in the prompt (e.g. JSON examples) so they don't parse as expressions
  3. Align the start/end delimiter tokens with your template syntax (e.g. use '<' '>' if braces collide with JSON)
  4. Validate attribute names in the template match the model map keys exactly

Example fix

// before
String template = "Respond with JSON: {\"answer\": {answer}}"; // braces conflict
// after (custom delimiters)
StTemplateRenderer renderer = StTemplateRenderer.builder()
    .startDelimiterToken('<').endDelimiterToken('>').build();
String template = "Respond with JSON: {\"answer\": <answer>}";
Defensive patterns

Strategy: validation

Validate before calling

try {
    new STGroup(renderer instanceof Object /* config */ ? "{" : "<", "}");
} catch (Exception e) { /* delimiter config wrong */ }
// assert no unbalanced braces outside known placeholders:
long open = template.chars().filter(c -> c == '{').count();
long close = template.chars().filter(c -> c == '}').count();
if (open != close) throw new IllegalStateException("Unbalanced braces in template");

Try / catch

try { rendered = renderer.render(template, model); }
catch (IllegalArgumentException e) {
    if ("The template string is not valid.".equals(e.getMessage())) { log.error("ST syntax error", e.getCause()); }
}

Prevention

When it happens

Trigger: Calling render with a template containing StringTemplate syntax errors — unbalanced or unescaped delimiters, stray '{' or '}' (matching the configured start/end delimiter tokens), invalid attribute expressions — via PromptTemplate using StTemplateRenderer.

Common situations: Prompts that include literal JSON or code with curly braces not escaped; mismatched custom delimiter tokens; typos in attribute expressions like {question_answer_contex}; migrating from another template engine whose syntax differs.

Related errors


AI-assisted analysis of spring-projects/spring-ai@98a7beda4f (2026-09-11). Data as JSON: /api/errors/c6120421d71bbf1d. Report an issue: GitHub.