Skip to content

Commit 8389ba8

Browse files
committed
add PromptTemplate
1 parent fd8018e commit 8389ba8

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

llm4j-api/pom.xml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@
2121

2222
<properties>
2323
<module-name>org.llm4j</module-name>
24+
<commons-text.version>1.10.0</commons-text.version>
2425
</properties>
2526

27+
<dependencies>
28+
<dependency>
29+
<groupId>org.apache.commons</groupId>
30+
<artifactId>commons-text</artifactId>
31+
<version>${commons-text.version}</version>
32+
</dependency>
33+
</dependencies>
34+
2635
</project>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package org.llm4j.api;
2+
3+
import org.apache.commons.text.StringSubstitutor;
4+
5+
import java.nio.file.Files;
6+
import java.nio.file.Path;
7+
import java.nio.file.Paths;
8+
import java.util.HashMap;
9+
import java.util.Map;
10+
11+
public class PromptTemplate {
12+
String template = "";
13+
Map<String, Object> params = new HashMap<>();
14+
15+
String prefix = "{";
16+
String suffix = "}";
17+
18+
public PromptTemplate withFile(String fileName) {
19+
template = "";
20+
try {
21+
ClassLoader classloader = getClass().getClassLoader();
22+
Path path = Paths.get(classloader.getResource(fileName).toURI());
23+
for(String line: Files.readAllLines(path)) {
24+
template += "\n" + line;
25+
}
26+
template = template.substring("\n".length());
27+
} catch (Exception e) {
28+
e.printStackTrace();
29+
}
30+
return this;
31+
}
32+
33+
public PromptTemplate withParam(String key, Object value) {
34+
this.params.put(key, value);
35+
return this;
36+
}
37+
38+
39+
public String render() {
40+
return StringSubstitutor.replace(template, params, prefix, suffix);
41+
}
42+
}

0 commit comments

Comments
 (0)