LangChain4j Prompt 提示词工程

提示词工程

提示词工程(Prompt Engineering) 是一门设计和优化输入提示词的技术,目的是让大语言模型更准确、更可靠地输出你想要的结果。

简单说就是:教你怎么跟AI说话,它才能更好地帮你干活。

LangChain4j 提供了 5 种消息类型,可以在 ChatMessageType 中查看。

  • SystemMessage
  • UserMessage
  • AiMessage
  • ToolExecutionResultMessage
  • CustomMessage

SystemMessage

这是来自系统的消息。通常,作为开发人员,你应该定义这条消息的内容。比如编写关于 LLM 在这次对话中的角色、表现形式、回答风格等指令。SystemMessage 是非常重要的消息,最好不要给用户自由访问权限以及避免用户自定义 SystemMessage 消息。通常,此类消息位于对话的开始。

UserMessage

这是来自用户的消息。

AiMessage

这是由 AI 生成的消息,通常是对 UserMessage 的响应,例如

java 复制代码
Response<Image> response = wanxImageModel.generate("大帅哥");

generate 方法返回一个包裹在 Response 中的 AiMessage

AiMessage 可以包含文本响应(String),或者执行工具请求(ToolExecutionRequest)。

ToolExecutionResultMessage

来自 ToolExecutionRequest 的消息

CustomMessage

自定义消息,这种消息类型只能由支持它的 ChatModel 实现使用。(目前只有 Ollama)

使用方式一

新建 CodeAssistant

java 复制代码
public interface CodeAssistant {
    @SystemMessage("""
            你是一位专业的编程领域大师,只回答与代码编程相关的问题。
            输出限制:对于其他领域的问题禁止回答,直接返回"这不是我的领域范围,我没法回答你的问题。"
            """)
    @UserMessage("请回答以下问题:{{question}}, 字数控制在 {{length}} 内。")
    Flux<String> chat(@V("question") String question, @V("length") int length);
}

PromptController

java 复制代码
@RestController
@RequestMapping("prompt")
@CrossOrigin
public class PromptController {
    @Resource
    private CodeAssistant codeAssistant;

    @GetMapping("/qwen/chat3")
    public Flux<String> chat3(@RequestParam(value = "question", defaultValue = "你是谁?") String question) {
		return codeAssistant.chat(question, 200);
    }
}

使用方式二

新建提示词模板类

java 复制代码
@Data
@StructuredPrompt("请回答以下问题:{{question}}, 字数控制在 {{length}} 内。")
public class CodePrompt {
    private String question;
    private int length;
}

编写 AI 服务接口

java 复制代码
public interface CodeAssistant {
    @SystemMessage("""
            你是一位专业的编程领域大师,只回答与代码编程相关的问题。
            输出限制:对于其他领域的问题禁止回答,直接返回"这不是我的领域范围,我没法回答你的问题。"
            """)
    Flux<String> chat(CodePrompt codePrompt);
}

PromptController

java 复制代码
@RestController
@RequestMapping("prompt")
@CrossOrigin
public class PromptController {
    @Resource
    private CodeAssistant codeAssistant;

    @GetMapping("/qwen/chat3")
    public Flux<String> chat3(@RequestParam(value = "question", defaultValue = "你是谁?") String question) {
        CodePrompt codePrompt = new CodePrompt();
        codePrompt.setQuestion(question);
        codePrompt.setLength(200);
        return codeAssistant.chat(codePrompt);
    }
}

使用方式三

java 复制代码
@RestController
@RequestMapping("prompt")
@CrossOrigin
public class PromptController {
    @Resource
    private StreamingChatModel streamingChatModel;

    @GetMapping("/qwen/chat3")
    public Flux<String> chat3(@RequestParam(value = "question", defaultValue = "你是谁?") String question) {
        String role = "java";

        PromptTemplate template = PromptTemplate.from("你是一个 {{role}} 高手,请问 {{question}} 怎么办?");
        Prompt prompt = template.apply(Map.of("role", role, "question", question));
        UserMessage userMessage = prompt.toUserMessage();
        
        return Flux.create(e -> {
            streamingChatModel.chat(List.of(userMessage), new StreamingChatResponseHandler() {
                @Override
                public void onPartialResponse(String s) { e.next(s); }
                @Override
                public void onCompleteResponse(ChatResponse chatResponse) {}
                @Override
                public void onError(Throwable throwable) {}
            });
        });
    }
}
相关推荐
IT_陈寒1 小时前
SpringBoot自动配置的坑,我的API突然就404了
前端·人工智能·后端
ServBay2 小时前
为什么说 MCP 是 2026 年开发者必须掌握的黄金协议?
后端·mcp
程序员夏洛2 小时前
Spring Boot 多模块项目中 IDEA 提示 Cannot resolve symbol 的一次排查记录
后端
子兮曰2 小时前
OpenMontage 深度解剖:你的 AI 编程助手,其实是个视频工作室
前端·后端·ai编程
子兮曰2 小时前
前端工具链的「Rust 化」:一场没有赢家的军备竞赛?
前端·后端·rust
爱勇宝3 小时前
从 Ctrl+CV 到 Enter:程序员正在失去什么
前端·后端·程序员
码事漫谈4 小时前
EdgeOne Makers + WorkBuddy:零基础也能快速搭建可上线的 AI 智能体(附图文教程)
后端
像我这样帅的人丶你还4 小时前
Java 后端详解(四):分页与搜索
java·javascript·后端
她的男孩4 小时前
数据权限为什么不能只靠注解?Forge 的 Mapper 层 SQL 改写源码拆解
java·后端·架构
烤代码的吐司君5 小时前
Redis 数据结构 ZSet, BIT, HyperLogLog,Geo 空间数据
redis·后端