摘要: 本文介紹了langchain.prompts中基礎的提示詞模板的用法,包括基礎的文本模板、對話模板、小樣本模板、以及主要兩種樣本選擇器的用法。
文章目錄
- 1. prompts介紹?
- 2. 提示詞模板體系 Prompt Templates
- 2.1 基礎文本模板 PromptTemplate
- 2.2 對話模板 ChatPromptTemplate
- 2.3 小樣本提示模板Few-shot
- 2.4 示例選擇器Example Selector
- 2.4.1 按長度選擇 LengthBasedExampleSelector
- 2.4.2 按相似度選擇 LengthBasedExampleSelector
1. prompts介紹?
-
提示詞:就是輸入給LLM的內容。包括我們和LLM對話的內容,
-
LangChain的Prompts模塊是構建對話系統的核心組件,它通過結構化模板實現精準的提示工程管理。該模塊將自然語言指令轉化為大模型可解析的標準化輸入,顯著提升AI交互質量。
2. 提示詞模板體系 Prompt Templates
LangChain 提供了 PromptTemplates,可以讓用戶根據輸入動態地修改提示;提示詞模板是一種預定義的文本結構,其中包含變量和固定文本部分,用于引導語言模型生成特定類型的輸出。這些模板可以幫助模型更準確地理解上下文,并生成符合預期的響應。
? ?提示詞模板(Prompt Template)在自然語言處理和生成任務中,是設計和優化模型輸入的一種方法。提示詞模板可以幫助大型語言模型(LLM)更好地理解和生成目標內容。以下是提示詞模板的介紹及其
在不同場景中的應用。
通常提示詞模板包含兩部分:
- 靜態部分:用于提供上下文,背景或引導語等用于控制LLM的大的方向。
- 動態部分:根據具體輸入替換,在模板中用占位符表示變量。
2.1 基礎文本模板 PromptTemplate
from langchain_core.prompts import PromptTemplate# 定義含變量的模板
template = "請為{product}寫廣告語,突出{feature}特點"
prompt = PromptTemplate(input_variables=["product", "feature"],template=template
)# 填充變量生成最終提示
filled_prompt = prompt.format(product="智能手表", feature="健康監測")# 輸出:請為智能手表寫廣告語,突出健康監測特點
print(filled_prompt)
輸出:
請為智能手表寫廣告語,突出健康監測特點
使用partial_variables提前固定部分參數:
# 預設置部分變量
partial_prompt = prompt.partial(product="電動汽車")
print(partial_prompt.format(feature="續航能力"))
# 輸出:請為電動汽車寫廣告語,突出續航能力特點
2.2 對話模板 ChatPromptTemplate
用于對結構化的聊天消息管理,支持區分角色區分。
from langchain.prompts import ChatPromptTemplatechat_template = ChatPromptTemplate.from_messages([("system", "你是一位{role}"),("human", "請分析:{question}")
])
filled_chat = chat_template.format_messages(role="金融顧問", question="當前股市走勢"
)print(filled_chat)
[SystemMessage(content='你是一位金融顧問', additional_kwargs={}, response_metadata={}), HumanMessage(content='請分析:當前股市走勢', additional_kwargs={}, response_metadata={})]
我們可以看到它返回一個BaseMessage類型,可以直接傳給聊天模型
response = model.invoke(prompt)
2.3 小樣本提示模板Few-shot
Few-shot examples 是一組可幫助語言模型生成更好響應的示例。要生成具有 few-shot examples 的 prompt,可以使用 FewShotPromptTemplate。該類接受一個 PromptTemplate 和一組 few-shot examples。然后,它使用這些 few-shot examples 格式化成 prompt 模板。
示例:輸入一個情緒的詞,要返回對應情緒的表現;我們根據提示詞,告訴模型,什么是“情緒的表現”。
'''
創建大模型LLM
'''
from langchain.chat_models import ChatOpenAI
# 定義模型調用API URL
base_url = "https://api.deepseek.com/v1"
# 定義模型調用API KEY(實際應用會放到環境變量中,避免明文暴露)
api_key = "你自己的api key"
# 定義模型名稱(對應DeepSeek-V3)
model='deepseek-chat'
llm= ChatOpenAI(base_url=base_url,api_key=api_key,model=model)'''
創建小樣本提示詞模板
'''
from langchain import FewShotPromptTemplate# 示例樣本
examples = [{"input": "高興", "output": "笑容滿面"}, {"input": "悲傷", "output": "淚流滿面"}]# 創建提示詞模板
example_template = "輸入:{input}\n輸出:{output}"example_prompt = PromptTemplate.from_template(example_template)# 小樣本提示詞模板
few_shot_prompt = FewShotPromptTemplate(examples=examples,example_prompt=example_prompt,prefix="請給出每個輸入的情感進行分析,給出對應的表現。",suffix="輸入:{text}\n輸出:",input_variables=["text"]
)# 格式化提示詞
prompt_text = few_shot_prompt.format(text="憤怒")'''
調用模型
'''
response = llm.invoke(prompt_text)
print("LLM 輸出:")
print(response.content)
輸出:
LLM 輸出:
怒目圓睜
2.4 示例選擇器Example Selector
在大量示例情況下,因為大量的示例會浪費token,還可能超出token限制。Example Selector可以從大量的示例中,自動選擇最合適的部分示例納入到提示詞中。
主要兩種方式選擇:
- 按長度: 較長的輸入,選擇較少示例;反之,較短輸入,選擇更多示例。
- 按相似度: 查找與輸入具有最大余弦相似度的嵌入示例。
2.4.1 按長度選擇 LengthBasedExampleSelector
他可以根據輸入文本長度自動增減示例數量,短輸入時提供更多上下文示例,長輸入時減少示例以避免超出模型上下文窗口限制。通過預設的max_length參數確保提示總長度不超過模型處理上限。
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.example_selectors import LengthBasedExampleSelector# 定義示例集
examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "fast", "output": "slow"},{"input": "wind", "output": "calm"}
]# 創建示例模板
example_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}"
)# 初始化選擇器
selector = LengthBasedExampleSelector(examples=examples,example_prompt=example_prompt,max_length=10 # 假設模型上下文窗口為30字符
)# 構建動態提示
dynamic_prompt = FewShotPromptTemplate(example_selector=selector,example_prompt=example_prompt,prefix="生成反義詞",suffix="Input: {adjective}\nOutput:",input_variables=["adjective"]
)# 測試不同長度輸入
print(dynamic_prompt.format(adjective="big")) # 顯示全部3個示例
print(dynamic_prompt.format(adjective="extremely and huge and massive")) # 可能只顯示1個示例
2.4.2 按相似度選擇 LengthBasedExampleSelector
以下是一個根據為輸入,提供一個反義詞的例子,當輸入一個詞時選擇器會根據語義選擇相近的例子;本例中,輸入“red”,選擇器選擇了和顏色相關的示例作為輸出。
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain.embeddings import OllamaEmbeddings
from langchain_community.vectorstores import FAISS# 初始化嵌入模型embedings
model = "nomic-embed-text:latest" # 模型名稱
base_local_url = "http://localhost:11434" # 本地部署模型
embedings = OllamaEmbeddings( # ①base_url=base_local_url,model=model
)# 定義示例集
examples = [{"input": "happy", "output": "sad"},{"input": "tall", "output": "short"},{"input": "fast", "output": "slow"},{"input": "wind", "output": "calm"},{"input": "black", "output": "white"},{"input": "Light", "output": "Dark"},{"input": "Bright", "output": "Dull"},{"input": "Rainy", "output": "Dry"},{"input": "Warm", "output": "Cool"},{"input": "Summer", "output": "Winter"}
]# 創建示例模板
example_prompt = PromptTemplate(input_variables=["input", "output"],template="Input: {input}\nOutput: {output}"
)# 初始化選擇器
selector = SemanticSimilarityExampleSelector.from_examples(examples=examples,embeddings=embedings, vectorstore_cls=FAISS, # 使用Faiss作為矢量庫k=3,# 選擇三個相似的示例input_keys=["input"]
)# 構建動態提示
dynamic_prompt = FewShotPromptTemplate(example_selector=selector,example_prompt=example_prompt,prefix="生成反義詞",suffix="Input: {input}\nOutput:",input_variables=["input"]
)# 測試不同長度輸入
print(dynamic_prompt.format(input="red"))
輸出:
生成反義詞Input: Bright
Output: DullInput: black
Output: whiteInput: Light
Output: DarkInput: red
Output:
注:① 本例中使用本地部署一個Ollama框架Embedding模型,Ollama后續文章介紹。
**Embedding Model:**嵌入模型是一種將離散的高維數據(如單詞、句子、圖片等)映射到連續的低維向量空間的技術;嵌入模型的主要目的是捕捉輸入數據中的語義或特征信息,使得相似的輸入在嵌入空間中距離更近。嵌入模型通常計算高效,適合用于大規模數據的相似性搜索和分類任務。
嵌入模型適用場景:
- 文本相似度計算:比較兩個文本的嵌入向量,計算相似度。
- 信息檢索:通過嵌入向量進行高效的相似性搜索。
- 分類和聚類:使用嵌入向量進行文本或圖像的分類和聚類。