1. 概念提示词模板就是一个可复用的提示词蓝图它允许我们动态地生成提示词而不是每次都手动编写完整的提示词。它类似于编程中的字符串格式化功能。你创建一个带有“占位符”的模板然后在运行时用具体的值变量填充这些占位符从而生成一个最终发送给 LLM 的完整提示词。提示词模板解决了以下几个核心问题可复用性 只需定义一个模板就可以用于无数个类似的查询。关注点分离 将提示词的结构和逻辑工程与具体的内容和数据分离开。提示工程师可以专注于优化模板而应用程序则负责提供变量值。一致性 确保发送给LLM的提示词结构统一这有助于获得更稳定、可预测的输出结果。可维护性 如果需要修改提示词的风格或结构只需修改一个模板文件而不用在代码的无数个地方进行修改。2. 文本提示词模板LangChain 提供了 PromptTemplate 类来轻松实现这一功能。PromptTemplate 实现了标准的Runnable 接口。方式一创建类fromlangchain_core.promptsimportPromptTemplate,ChatPromptTemplate# 定义文本提示词模板 Runnable实例# 方式一创建类prompt_templatePromptTemplate(template介绍{city}的历史,input_variables[city],)# # 调用--将模板实例化print(prompt_template.invoke({city:北京}))输出结果text介绍北京的历史方式二直接调用内部方法fromlangchain_core.promptsimportPromptTemplate,ChatPromptTemplate# 定义文本提示词模板 Runnable实例# # 方式二直接调用内部方法prompt_templatePromptTemplate.from_template(将文本从{language_from}翻译为{language_to})# # 调用--将模板实例化print(prompt_template.invoke({language_from:英文,language_to:中文}))输出结果text将文本从英文翻译为中文3. 聊天消息提示词模板fromlangchain.chat_modelsimportinit_chat_modelfromlangchain_core.promptsimportChatPromptTemplate modelinit_chat_model(modeldeepseek-chat,model_providerdeepseek)# 定义聊天消息的模板chat_prompt_templateChatPromptTemplate([(system,将文本从{language_from}翻译为{language_to}),# 系统提示词(user,{text},)# 用户提示词# (ai, ) # AI提示词])# 实例化messageschat_prompt_template.invoke({language_from:英文,language_to:中文,text:Artificial intelligence is transforming the world.})model.invoke(messages).pretty_print()输出结果Ai Message人工智能正在改变世界。4. 消息占位符fromlangchain.chat_modelsimportinit_chat_modelfromlangchain_core.messagesimportHumanMessage,AIMessagefromlangchain_core.promptsimportPromptTemplate,ChatPromptTemplate,MessagesPlaceholder modelinit_chat_model(modeldeepseek-chat,model_providerdeepseek)chat_prompt_templateChatPromptTemplate([(system,将文本从{language_from}翻译为{language_to}),MessagesPlaceholder(msgs),# 消息占位符(user,{text}),# (ai, )])messages_placeholder[HumanMessage(contenthi, what is your name?),AIMessage(content你好你叫什么名字)]messageschat_prompt_template.invoke({language_from:英文,language_to:中文,text:hi, what is your age?,msgs:messages_placeholder,})print(messages)输出结果messages[SystemMessage(content将文本从英文翻译为中文,additional_kwargs{},response_metadata{}),HumanMessage(contenthi, what is your name?,additional_kwargs{},response_metadata{}),AIMessage(content你好你叫什么名字,additional_kwargs{},response_metadata{},tool_calls[],invalid_tool_calls[]),HumanMessage(contenthi, what is your age?,additional_kwargs{},response_metadata{})]