【LangChain4J】提示词工程

git地址

官方对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();
    }
posted @ 2025-12-21 00:38  爱吃鱼的大灰狼  阅读(6)  评论(0)    收藏  举报