Skip to content

Commit 13e7f18

Browse files
committed
Optimize PromptTemplate constructor.
1 parent 5e1f681 commit 13e7f18

File tree

1 file changed

+10
-25
lines changed

1 file changed

+10
-25
lines changed

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

Lines changed: 10 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import java.io.IOException;
2020
import java.io.InputStream;
2121
import java.nio.charset.Charset;
22+
import java.util.Collections;
2223
import java.util.HashMap;
2324
import java.util.HashSet;
2425
import java.util.List;
@@ -54,37 +55,17 @@ public PromptTemplate(Resource resource) {
5455
catch (IOException ex) {
5556
throw new RuntimeException("Failed to read resource", ex);
5657
}
57-
try {
58-
this.st = new ST(this.template, '{', '}');
59-
}
60-
catch (Exception ex) {
61-
throw new IllegalArgumentException("The template string is not valid.", ex);
62-
}
58+
initST(this.template, Collections.emptyMap());
6359
}
6460

6561
public PromptTemplate(String template) {
6662
this.template = template;
67-
// If the template string is not valid, an exception will be thrown
68-
try {
69-
this.st = new ST(this.template, '{', '}');
70-
}
71-
catch (Exception ex) {
72-
throw new IllegalArgumentException("The template string is not valid.", ex);
73-
}
63+
initST(this.template, Collections.emptyMap());
7464
}
7565

7666
public PromptTemplate(String template, Map<String, Object> model) {
7767
this.template = template;
78-
// If the template string is not valid, an exception will be thrown
79-
try {
80-
this.st = new ST(this.template, '{', '}');
81-
for (Entry<String, Object> entry : model.entrySet()) {
82-
add(entry.getKey(), entry.getValue());
83-
}
84-
}
85-
catch (Exception ex) {
86-
throw new IllegalArgumentException("The template string is not valid.", ex);
87-
}
68+
initST(this.template, model);
8869
}
8970

9071
public PromptTemplate(Resource resource, Map<String, Object> model) {
@@ -94,11 +75,15 @@ public PromptTemplate(Resource resource, Map<String, Object> model) {
9475
catch (IOException ex) {
9576
throw new RuntimeException("Failed to read resource", ex);
9677
}
78+
initST(this.template, model);
79+
}
80+
81+
private void initST(String template, Map<String, Object> model) {
9782
// If the template string is not valid, an exception will be thrown
9883
try {
99-
this.st = new ST(this.template, '{', '}');
84+
this.st = new ST(template, '{', '}');
10085
for (Entry<String, Object> entry : model.entrySet()) {
101-
this.add(entry.getKey(), entry.getValue());
86+
add(entry.getKey(), entry.getValue());
10287
}
10388
}
10489
catch (Exception ex) {

0 commit comments

Comments
 (0)