Skip to content

Commit 955a081

Browse files
authored
Polishing
1 parent 9588711 commit 955a081

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

spring-ai-core/src/main/java/org/springframework/ai/chat/prompt/PromptTemplate.java

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
import org.antlr.runtime.Token;
3131
import org.antlr.runtime.TokenStream;
32+
import org.springframework.util.Assert;
3233
import org.stringtemplate.v4.ST;
3334
import org.stringtemplate.v4.compiler.STLexer;
3435

@@ -53,37 +54,37 @@ public PromptTemplate(Resource resource) {
5354
}
5455

5556
public PromptTemplate(Resource resource, Map<String, Object> model) {
56-
try (InputStream inputStream = resource.getInputStream()) {
57-
this.template = StreamUtils.copyToString(inputStream, Charset.defaultCharset());
58-
}
59-
catch (IOException ex) {
60-
throw new RuntimeException("Failed to read resource", ex);
61-
}
62-
initST(this.template, model);
57+
this(readTemplateFromResource(resource), model);
6358
}
6459

6560
public PromptTemplate(String template) {
6661
this(template, Collections.emptyMap());
6762
}
6863

6964
public PromptTemplate(String template, Map<String, Object> model) {
65+
Assert.notNull(template, "template must not be null");
66+
Assert.notNull(model, "model must not be null");
7067
this.template = template;
71-
initST(this.template, model);
72-
}
73-
74-
private void initST(String template, Map<String, Object> model) {
7568
// If the template string is not valid, an exception will be thrown
7669
try {
7770
this.st = new ST(template, '{', '}');
7871
for (Entry<String, Object> entry : model.entrySet()) {
7972
add(entry.getKey(), entry.getValue());
8073
}
81-
}
82-
catch (Exception ex) {
74+
} catch (Exception ex) {
8375
throw new IllegalArgumentException("The template string is not valid.", ex);
8476
}
8577
}
8678

79+
private static String readTemplateFromResource(Resource resource) {
80+
Assert.notNull(resource, "resource must not be null");
81+
try (InputStream inputStream = resource.getInputStream()) {
82+
return StreamUtils.copyToString(inputStream, Charset.defaultCharset());
83+
} catch (IOException ex) {
84+
throw new RuntimeException("Failed to read resource", ex);
85+
}
86+
}
87+
8788
public void add(String name, Object value) {
8889
this.st.add(name, value);
8990
this.dynamicModel.put(name, value);

0 commit comments

Comments
 (0)