丹东市元宝区女人街优质靠谱女装店高性价比防踩雷推荐
2026/7/26 20:50:10
当需要重复使用固定格式的提示词(仅动态内容变化)时,可通过 PromptTemplate 标准化提示词结构,避免重复编写模板内容,提升开发效率。适用于批量生成问题、标准化指令场景(如批量生成产品描述、统一格式的客服回复)。
from langchain_core.prompts import PromptTemplate from langchain_ollama import ChatOllama # 定义提示词模板({变量名}为动态参数) template = "请为{product}写一句宣传语,风格{style}" prompt = PromptTemplate.from_template(template) # 填充动态参数 formatted_prompt = prompt.format(product="无线耳机", style="科技感") # 初始化大模型 llm =ChatOllama( model="qwen3:4b", base_url = "http://127.0.0.1:11434", temperature=0.7, ) print(llm.invoke(formatted_prompt).content)from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.messages import HumanMessage, AIMessage from langchain_ollama import ChatOllama # 定义包含占位符的模板 template = [ ("system", "基于历史对话回答用户新问题"), MessagesPlaceholder(variable_name="history"), # 动态插入历史消息 ("human", "{question}") ] chat_prompt = ChatPromptTemplate.from_messages(template) # 准备历史消息 history = [ HumanMessage(content="推荐一部科幻电影"), AIMessage(content="《星际穿越》很经典") ] # 填充参数(替换占位符) formatted_prompt = chat_prompt.format_messages( history=history, question="再推荐一部类似的" ) # 初始化大模型 llm =ChatOllama( model="qwen3:4b", base_url = "http://127.0.0.1:11434", temperature=0.7, ) print(llm.invoke(formatted_prompt).content)通过提供少量示例(Few-Shot)引导大模型学习特定格式或逻辑,适用于需要标准化输出(如固定格式的分类、翻译、摘要)的场景,帮助模型快速理解任务要求。
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate from langchain_ollama import ChatOllama # 定义示例 examples = [ {"input": "苹果", "output": "水果"}, {"input": "菠萝", "output": "水果"} ] # 示例模板 example_template = "输入: {input}\n输出: {output}" example_prompt = PromptTemplate.from_template(example_template) # 构建FewShot提示 few_shot_prompt = FewShotPromptTemplate( examples=examples, example_prompt=example_prompt, prefix="请按照示例格式分类:", suffix="输入: {input}\n输出:", input_variables=["input"] ) # 生成提示并调用 prompt = few_shot_prompt.format(input="香蕉") # 初始化大模型 llm =ChatOllama( model="qwen3:4b", base_url = "http://127.0.0.1:11434", temperature=0.7, ) print(llm.invoke(prompt).content) # 预期输出:水果from langchain_core.prompts import FewShotChatMessagePromptTemplate from langchain_core.messages import HumanMessage, AIMessage from langchain_core.prompts import ChatPromptTemplate from langchain_ollama import ChatOllama # 示例(多轮消息对) examples = [ { "messages": [ HumanMessage(content="推荐一首中文歌"), AIMessage(content="周杰伦的《晴天》很经典") ] }, { "messages": [ HumanMessage(content="再推荐一首"), AIMessage(content="林俊杰的《江南》") ] } ] # 构建FewShot对话模板 few_shot_prompt = FewShotChatMessagePromptTemplate( examples=examples, example_messages_key="messages" # 指定示例中消息列表的键名 ) # 组装最终对话模板 final_prompt = ChatPromptTemplate.from_messages([ ("system", "你需要根据示例推荐中文歌曲"), few_shot_prompt, # 插入示例 ("human", "{question}") # 用户当前问题 ]) # 生成提示并调用 formatted = final_prompt.format_messages(question="再求一首") # 初始化大模型 llm =ChatOllama( model="qwen3:4b", base_url = "http://127.0.0.1:11434", temperature=0.7, ) print(llm.invoke(formatted).content)