System 角色设定
在 Spring AI 中,System 角色设定是一种强大的功能,允许您为 AI 模型定义行为准则和角色定位。
什么是 System 角色?
System 角色是三种消息角色之一(System、User、Assistant),用于设置 AI 助手的行为模式、个性特征和功能范围。
在 Spring AI 中使用 System 角色
基本用法
@Service
public class RoleBasedService {
private final ChatClient chatClient;
public RoleBasedService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String getTechnicalResponse(String userMessage) {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("""
你是一个资深的 Java 架构师,专门负责解答技术问题。
你需要:
1. 提供准确的技术信息
2. 给出最佳实践建议
3. 用专业的术语解释概念
""");
Prompt prompt = new Prompt(
List.of(
systemPromptTemplate.create(),
new UserMessage(userMessage)
)
);
return chatClient.call(prompt).getResult().getOutput().getContent();
}
}
动态角色设定
@Service
public class DynamicRoleService {
private final ChatClient chatClient;
public DynamicRoleService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String getResponseByRole(String role, String userMessage) {
SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("""
你是一个 {role},请以该角色的专业知识回答问题。
""");
Prompt prompt = new Prompt(
List.of(
systemPromptTemplate.create(Map.of("role", role)),
new UserMessage(userMessage)
)
);
return chatClient.call(prompt).getResult().getOutput().getContent();
}
}
常见的角色设定模式
1. 技术专家角色
你是一个经验丰富的 {technology} 专家,擅长解决复杂的技术问题。
请用专业但易懂的方式回答问题,并提供实际的代码示例。
2. 教学导师角色
你是一个耐心的编程导师,正在指导一名初学者学习 {topic}。
请用简单明了的语言解释概念,并提供循序渐进的示例。
3. 客服代表角色
你是一个友好的客服代表,正在帮助客户解决 {product} 使用问题。
请保持礼貌和耐心,提供清晰的步骤指导。
最佳实践
1. 明确定义角色边界
清楚地界定 AI 助手的能力范围和限制,避免给出不准确的信息。
2. 保持一致性
在整个对话过程中维持角色的一致性,提供连贯的用户体验。
3. 结合上下文
根据具体的使用场景动态调整角色设定,提供更贴切的服务。
通过合理使用 System 角色设定,可以让您的 Spring AI 应用更加智能化和个性化。