LangChain4j Prompt 提示词工程

26 阅读2分钟

提示词工程

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

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

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

  • SystemMessage
  • UserMessage
  • AiMessage
  • ToolExecutionResultMessage
  • CustomMessage

SystemMessage

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

UserMessage

这是来自用户的消息。

AiMessage

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

Response<Image> response = wanxImageModel.generate("大帅哥");

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

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

ToolExecutionResultMessage

来自 ToolExecutionRequest 的消息

CustomMessage

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

使用方式一

新建 CodeAssistant

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

PromptController

@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);
    }
}

使用方式二

新建提示词模板类

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

编写 AI 服务接口

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

PromptController

@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);
    }
}

使用方式三

@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) {}
            });
        });
    }
}