Skip to content

Add Spring SpEL implementation of TemplateRenderer #3262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<module>spring-ai-bom</module>
<module>spring-ai-commons</module>
<module>spring-ai-template-st</module>
<module>spring-ai-template-spel</module>
<module>spring-ai-client-chat</module>
<module>spring-ai-model</module>
<module>spring-ai-test</module>
Expand Down
6 changes: 6 additions & 0 deletions spring-ai-bom/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,12 @@
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-template-spel</artifactId>
<version>${project.version}</version>
</dependency>

<!-- Spring AI model -->

<dependency>
Expand Down
6 changes: 6 additions & 0 deletions spring-ai-model/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@
<version>${project.parent.version}</version>
</dependency>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-template-spel</artifactId>
<version>${project.parent.version}</version>
</dependency>

<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-observation</artifactId>
Expand Down
69 changes: 69 additions & 0 deletions spring-ai-template-spel/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2023-2025 the original author or 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
~
~ https://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.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-parent</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
<artifactId>spring-ai-template-spel</artifactId>
<packaging>jar</packaging>
<name>Spring AI Template SpEL</name>
<description>SpEL implementation for Spring AI templating</description>
<url>https://github.com/spring-projects/spring-ai</url>

<scm>
<url>https://github.com/spring-projects/spring-ai</url>
<connection>git://github.com/spring-projects/spring-ai.git</connection>
<developerConnection>[email protected]:spring-projects/spring-ai.git</developerConnection>
</scm>

<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-commons</artifactId>
<version>${project.parent.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
</dependency>

<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<!-- test dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/*
* Copyright 2023-2025 the original author or 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
*
* https://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 org.springframework.ai.template.spel;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.ai.template.TemplateRenderer;
import org.springframework.ai.template.ValidationMode;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.common.CompositeStringExpression;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.DataBindingPropertyAccessor;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.Assert;

/**
* Renders a template using the Spring SpEL.
*
* <p>
* This renderer allows customization of delimiters, validation behavior when template
* variables are missing.
*
* <p>
* Use the {@link #builder()} to create and configure instances.
*
* <p>
* <b>Thread safety:</b> This class is safe for concurrent use. Each call to
* {@link #apply(String, Map)} creates a new SpEL Expression instance, and no mutable
* state is shared between threads.
*
* @author Yanming Zhou
* @since 1.1.0
*/
public class SpelTemplateRenderer implements TemplateRenderer {

private static final Logger logger = LoggerFactory.getLogger(SpelTemplateRenderer.class);

private static final String VALIDATION_MESSAGE = "Not all variables were replaced in the template. Missing variable names are: %s.";

private static final char DEFAULT_START_DELIMITER_TOKEN = '{';

private static final char DEFAULT_END_DELIMITER_TOKEN = '}';

private static final ValidationMode DEFAULT_VALIDATION_MODE = ValidationMode.THROW;

private final char startDelimiterToken;

private final char endDelimiterToken;

private final ValidationMode validationMode;

private final EvaluationContext evaluationContext;

/**
* Constructs a new {@code SpelTemplateRenderer} with the specified delimiter tokens,
* validation mode.
* @param startDelimiterToken the character used to denote the start of a template
* variable (e.g., '{')
* @param endDelimiterToken the character used to denote the end of a template
* variable (e.g., '}')
* @param validationMode the mode to use for template variable validation; must not be
* null template
*/
public SpelTemplateRenderer(char startDelimiterToken, char endDelimiterToken, ValidationMode validationMode) {
Assert.notNull(validationMode, "validationMode cannot be null");
this.startDelimiterToken = startDelimiterToken;
this.endDelimiterToken = endDelimiterToken;
this.validationMode = validationMode;

StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setPropertyAccessors(List.of(new MapAccessor(false), DataBindingPropertyAccessor.forReadOnlyAccess()));
this.evaluationContext = ctx;
}

@Override
public String apply(String template, Map<String, Object> variables) {
Assert.hasText(template, "template cannot be null or empty");
Assert.notNull(variables, "variables cannot be null");
Assert.noNullElements(variables.keySet(), "variables keys cannot be null");

Expression expression = parseExpression(template);

if (this.validationMode != ValidationMode.NONE) {
validate(expression, variables);
}

return String.valueOf(expression.getValue(this.evaluationContext, variables));
}

private Expression parseExpression(String template) {
SpelExpressionParser parser = new SpelExpressionParser();
return parser.parseExpression(template, new TemplateParserContext(String.valueOf(this.startDelimiterToken),
String.valueOf(this.endDelimiterToken)));
}

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

if (!missingVariables.isEmpty()) {
if (this.validationMode == ValidationMode.WARN) {
logger.warn(VALIDATION_MESSAGE.formatted(missingVariables));
}
else if (this.validationMode == ValidationMode.THROW) {
throw new IllegalStateException(VALIDATION_MESSAGE.formatted(missingVariables));
}
}
return missingVariables;
}

public Set<String> getInputVariables(Expression expression) {
Set<String> inputVariables = new LinkedHashSet<>();
if (expression instanceof CompositeStringExpression cse) {
for (Expression ex : cse.getExpressions()) {
if (ex instanceof SpelExpression se) {
inputVariables.add(se.getExpressionString());
}
}
}

return inputVariables;
}

public static Builder builder() {
return new Builder();
}

/**
* Builder for configuring and creating {@link SpelTemplateRenderer} instances.
*/
public static final class Builder {

private char startDelimiterToken = DEFAULT_START_DELIMITER_TOKEN;

private char endDelimiterToken = DEFAULT_END_DELIMITER_TOKEN;

private ValidationMode validationMode = DEFAULT_VALIDATION_MODE;

private Builder() {
}

/**
* Sets the character used as the start delimiter for template expressions.
* Default is '{'.
* @param startDelimiterToken The start delimiter character.
* @return This builder instance for chaining.
*/
public Builder startDelimiterToken(char startDelimiterToken) {
this.startDelimiterToken = startDelimiterToken;
return this;
}

/**
* Sets the character used as the end delimiter for template expressions. Default
* is '}'.
* @param endDelimiterToken The end delimiter character.
* @return This builder instance for chaining.
*/
public Builder endDelimiterToken(char endDelimiterToken) {
this.endDelimiterToken = endDelimiterToken;
return this;
}

/**
* Sets the validation mode to control behavior when the provided variables do not
* match the variables required by the template. Default is
* {@link ValidationMode#THROW}.
* @param validationMode The desired validation mode.
* @return This builder instance for chaining.
*/
public Builder validationMode(ValidationMode validationMode) {
this.validationMode = validationMode;
return this;
}

/**
* Builds and returns a new {@link SpelTemplateRenderer} instance with the
* configured settings.
* @return A configured {@link SpelTemplateRenderer}.
*/
public SpelTemplateRenderer build() {
return new SpelTemplateRenderer(this.startDelimiterToken, this.endDelimiterToken, this.validationMode);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright 2023-2025 the original author or 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
*
* https://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.
*/

@NonNullApi
@NonNullFields
package org.springframework.ai.template.spel;

import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
Loading