Prompt 模板
约 464 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Spring AI › ChatClient 与 Prompt 工程
PromptTemplate
PromptTemplate 使用 {{placeholder}} 语法进行变量替换,类似 Spring 的 JdbcTemplate。
PromptTemplate template = new PromptTemplate("Tell me a {{adjective}} joke about {{topic}}");
Prompt prompt = template.create(Map.of(
"adjective", "funny",
"topic", "programming"
));
ChatResponse response = chatClient.call(prompt);模板文件
推荐将模板放在 resources/prompts/ 目录下:
# resources/prompts/summary.st
Please summarize the following text in {{language}}.
Keep the summary within {{maxWords}} words.
Text: "{{text}}"
Summary:// 加载模板文件
PromptTemplate template = new PromptTemplate("classpath:/prompts/summary.st");
Prompt prompt = template.create(Map.of(
"language", "Chinese",
"maxWords", "100",
"text", longText
));
String summary = chatClient.call(prompt).getResult().getOutput().getContent();复杂模板示例
代码审查模板
# resources/prompts/code-review.st
You are a senior Java code reviewer. Review the following code.
Focus on: {{focusAreas}}
Code:
```java
{{code}}Please provide:
- Potential bugs (if any)
- Code style issues
- Performance suggestions
- Security concerns
Answer in .
```java
PromptTemplate template = new PromptTemplate("classpath:/prompts/code-review.st");
Prompt prompt = template.create(Map.of(
"focusAreas", "performance, security",
"code", sourceCode,
"language", "Chinese"
));
String review = chatClient.call(prompt).getResult().getOutput().getContent();SQL 生成模板
# resources/prompts/sql-gen.st
You are a SQL expert. Convert the following natural language query to {{dialect}} SQL.
Database schema:
{{schema}}
User request: {{userQuery}}
Rules:
- Return ONLY the SQL query, no explanations
- Use proper table aliases
- Add comments for complex logicPrompt 模板与 System Message 结合
String systemText = """
You are a {{role}} assistant.
Always answer in {{language}}.
Use {{tone}} tone.
""";
String userText = """
User question: {{question}}
""";
PromptTemplate systemTemplate = new PromptTemplate(systemText);
PromptTemplate userTemplate = new PromptTemplate(userText);
Prompt prompt = new Prompt(List.of(
new SystemMessage(systemTemplate.render(Map.of(
"role", "technical",
"language", "Chinese",
"tone", "professional"
))),
new UserMessage(userTemplate.render(Map.of(
"question", "What is Spring AI?"
)))
));默认系统 Prompt
在 Builder 中结合模板:
@Bean
public ChatClient chatClient(ChatClient.Builder builder) {
return builder
.defaultSystem("""
You are a {{role}} assistant.
Answer in {{language}}.
Be {{tone}} and concise.
""")
.build();
}小结
PromptTemplate使用{{var}}语法做变量替换,支持从String和classpath文件加载。- 模板文件放在
resources/prompts/下统一管理。 - 复杂场景可用 System + User 多个模板组合。
- 模板中可嵌入示例代码和结构化输出要求。
- 分离 Prompt 模板与 Java 代码,便于维护和调试。
上一节:ChatClient 基础 下一节:Message 类型与多轮对话
