官方對2種ChatMessage的解釋
- SystemMessage這是系統發送的消息。通常,作為開發人員,您應該定義此消息的內容。一般來説,您會在此處編寫指令,説明 LLM 在此對話中的角色、行為方式、回覆風格等等。LLM 經過訓練,會更加關注SystemMessage此類消息,因此請務必謹慎,最好不要讓最終用户隨意定義或向消息中添加任何內容SystemMessage。通常,此消息位於對話的開頭。
- UserMessage這是一條來自用户的消息。用户可以是應用程序的最終用户(人),也可以是應用程序本身。消息內容可以包含:
contents():消息的內容。根據 LLM 支持的模態,它可以只包含單個文本(String),或其他模態)。
name()用户名。並非所有模型提供商都支持此功能。
attributes():附加屬性:這些屬性不會發送到模型,而是存儲在ChatMemory。
第一種,面向註解
public interface EducationAssistant {
@SystemMessage("你是一位專業的教育領域專家,只回答教育領域的問題。" +
"輸出限制:對於其他領域的問題禁止回答,直接返回‘抱歉,我只能回答教育相關問題’")
@UserMessage("請回答以下教育問題:{{question}},字數控制在{{length}}以內,以{{format}}格式輸出")
String educationQuestion(@V("question") String question,@V("length") String length,@V("format") String format);
}
@GetMapping("/chat/prompt1")
public String chatPrompt1(){
String result = educationAssistant.educationQuestion("教育的本質是什麼", "2000", "html");
String result2 = educationAssistant.educationQuestion("什麼是西瓜", "2000", "html");
return result + " <br> \n\n" + result2;
}
第二種,面向對象
public interface EducationAssistant {
@SystemMessage("你是一位專業的教育領域專家,只回答教育領域的問題。" +
"輸出限制:對於其他領域的問題禁止回答,直接返回‘抱歉,我只能回答教育相關問題’")
String educationQuestionByStructuredPrompt(EducationPrompt educationPrompt);
}
@Data
@StructuredPrompt("請針對{{age}}歲孩子,回答以下問題:{{question}}") //需要在實體類上加上這個註解
public class EducationPrompt {
private String age;
private String question;
}
@GetMapping("/chat/prompt2")
public String chatPrompt2(){
EducationPrompt educationPrompt = new EducationPrompt();
educationPrompt.setAge("8");
educationPrompt.setQuestion("孩子興趣班如何安排");
String result = educationAssistant.educationQuestionByStructuredPrompt(educationPrompt);
return result;
}
第三種,使用Prompt
@GetMapping("/chat/prompt3")
public String chatPrompt3(){
PromptTemplate template = PromptTemplate.from("根據教育相關知識,回答以下問題:{{it}}");
Prompt apply = template.apply(Map.of("it", "幼兒孩子生長中需要注意什麼"));
UserMessage userMessage = apply.toUserMessage();
ChatResponse chatResponse = chatModel.chat(userMessage);
return chatResponse.aiMessage().text();
}
本文章為轉載內容,我們尊重原作者對文章享有的著作權。如有內容錯誤或侵權問題,歡迎原作者聯繫我們進行內容更正或刪除文章。