LangChain 教程——提示詞模板

上篇文章學習了 LangChain 教程——LangChain 的基本使用,這篇文章我們學習 LangChain 教程——提示詞模板。

提示詞模板

提示詞模板提供了一種結構化的方式來構建和管理提示詞,可以將用戶輸入的內容格式化後傳遞給語言模型,幫助模型理解上下文並生成相關且連貫的輸出。

其格式爲:

固定文本{變量}

通過使用模板將實際值替換這些變量,動態生成最終的提示詞。

字符串提示詞模板

PromptTemplate 提示詞模板用於創建簡單的提示詞,可以內嵌任意數量的變量,通過變量值格式化模板內容。

主要是爲標準的文本生成任務設計的,用於生成非對話式的提示詞,可以用於各種文本生成任務,例如文本撰寫、摘要生成等。

其基礎語法格式如下:

PromptTemplate.from_template(
 "固定文本{變量}"
)

# 或
PromptTemplate(
 input_variables=[變量1,...],
 input_types={變量數據類型},
 partial_variables={部分填充},   # 預先填充(部分填充)模板中的某些變量
 template="固定文本:{變量1,...}"
)

示例代碼如下:

from langchain_core.prompts import PromptTemplate  # 引入字符串提示詞模板

# 定義提示詞模板
prompt_template = PromptTemplate.from_template(
    "給我介紹一下{content}是什麼?"
)

# 通過變量content變量格式化提示詞模板
prompt=prompt_template.format(content="langchain")
print(prompt)

運行結果爲:

給我介紹一下langchain是什麼?

聊天提示詞模板

ChatPromptTemplate 提示詞模板用於構建聊天對話型應用提示詞模板,爲對話系統設計,用於生成對話式的提示詞。

主要用於聊天機器人、對話模型等需要持續對話的場景。

其語法格式如下:

ChatPromptTemplate.from_messages([
 ("角色名","內容")
])

主要有三種角色:

示例代碼如下:

from langchain_core.prompts import ChatPromptTemplate  # 引入聊天提示詞模板

# 定義提示詞模板
prompt_template = ChatPromptTemplate.from_messages([
    ("system""你是一位人工智能助手,你的名字是{name}"),
    ("human""你好"),
    ("ai""謝謝"),
    ("human""{user_input}")
])
print(prompt_template.format_messages())

運行結果如下:

[SystemMessage(content='你是一位人工智能助手,你的名字是白巧克力', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='謝謝', additional_kwargs={}, response_metadata={}), HumanMessage(content='你的名字叫什麼', additional_kwargs={}, response_metadata={})]

在運行結果發現,角色 system、human、ai 分別對應着 SystemMessage、HumanMessage、AIMessage。

所以上面代碼可以改爲:

from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate  # 引入提示詞模板
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

# 定義提示詞模板
prompt_template = ChatPromptTemplate.from_messages([
 # 使用系統提示詞模板
    SystemMessagePromptTemplate.from_template("你是一位人工智能助手,你的名字是{name}"),
    HumanMessage(content="你好"),
    AIMessage(content="謝謝"),
    # 使用人工提示詞模板
    HumanMessagePromptTemplate.from_template("{user_input}")
])
print(prompt_template.format_messages())

當然 AI 提示詞模板也可以通過 AIMessagePromptTemplate 實現,這裏就不編寫了。

MessagesPlaceholder

MessagesPlaceholder 提示模板可以在特定位置添加內容,其語法格式如下:

MessagesPlaceholder("變量")

示例代碼如下:

from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, \
    MessagesPlaceholder  
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

# 定義提示詞模板
prompt_template = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("你是一位人工智能助手,你的名字是{name}"),
    MessagesPlaceholder('msgs'),  # 使用MessagesPlaceholder插入其他角色傳入的一組內容
    AIMessage(content="謝謝"),
    HumanMessagePromptTemplate.from_template("{user_input}")
])

print(prompt_template.invoke({"msgs":[HumanMessage(content="你好")],'name':"白巧克力"'user_input':"你的名字叫什麼"}))

運行結果如下:

[SystemMessage(content='你是一位人工智能助手,你的名字是白巧克力', additional_kwargs={}, response_metadata={}), HumanMessage(content='你好', additional_kwargs={}, response_metadata={}), AIMessage(content='謝謝', additional_kwargs={}, response_metadata={}), HumanMessage(content='你的名字叫什麼', additional_kwargs={}, response_metadata={})]

少樣本提示詞模板

少樣本提示詞模板(FewShotPromptTemplate)是指使用一組少量的示例來讓模型更好地理解用戶意圖,從而更好地回答或執行任務。

例如:

Q:什麼是白巧克力?
A:白巧克力是一種零食。

Q:什麼是sotnaldcnasfjsl
A:不知道

Q:什麼是語言模型?
A:

通過示例告訴模型:Q 是問題,A 是答案,按這種格式進行問答交互。

其基礎語法格式如下:

FewShotPromptTemplate(
    examples=示例,
    example_prompt=提示詞模板,
    suffix="Question:{input}",  #  提示詞模板最後追加的內容
    input_variables=['input']  #  定義suffix中包含的模板變量
)

示例代碼如下:

from langchain_core.prompts import PromptTemplate, FewShotPromptTemplate
# 示例
examples = [
    {
        "question""乾隆和曹操誰活得更久?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:乾隆去世時幾歲?
        中間答案:乾隆去世時87歲。
        追問:曹操去世時幾歲?
        中間答案:曹操去世時66歲。
        所以最終答案是:乾隆
        """,
    },
    {
        "question""小米手機的創始人什麼時候出生?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:小米手機的創始人是誰?
        中間答案:小米手機由雷軍創立。
        跟進:雷軍什麼時候出生?
        中間答案:雷軍出生於1969年12月16日。
        所以最終的答案是:1969年12月16日。
        """,
    },
    {
        "question""喬治·華盛頓的外祖父是誰?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:喬治·華盛頓的母親是誰?
        中間答案:喬治·華盛頓的母親是瑪麗·鮑爾·華盛頓。
        追問:瑪麗·鮑爾·華盛頓的父親是誰?
        中間答案:瑪麗·鮑爾·華盛頓的父親是約瑟夫·鮑爾
        """,
    }
]
# 提示詞模板
example_prompt = PromptTemplate(
    input_variables=["question""answer"], template="Question:{question}\n{answer}"
)
# 少樣本提示詞模板
prompt = FewShotPromptTemplate(
    examples=examples,   # 示例樣本
    example_prompt=example_prompt, # 提示詞模板
    suffix="Question:{input}",  # 提示詞模板最後追加的內容
    input_variables=['input']  # 定義suffix中包含的模板變量
)
print(prompt.format(input="喬治·華盛頓的外祖父是誰?"))

運行結果爲上面的示例 examples。

示例選擇器

在使用 FewShotPromptTemplate 時,把所有示例都提交給大模型,這顯然是不合理的,而且調用大模型的 token 是有限制的。

這時我們可以通過示例選擇器 ExampleSelector 中的 SemanticSimilarityExampleSelector 類來根據輸入的相似性選擇小樣本示例,避免把所有示例都提交給大模型。

SemanticSimilarityExampleSelector 使用了嵌入模型計算輸入和小樣本示例之間的相似性後,使用向量數據庫執行相似搜索,獲取與輸入相似的示例。

這裏我們使用了網絡上的文本嵌入模型,獲取方式在下面了,大家可以下載:

通過網盤分享的文件:ge-large-zh-v1.5
鏈接: https://pan.baidu.com/s/1NXsppUk6PjTASb43qno3KA?pwd=bqkl 提取碼: bqkl

需要安裝:

pip install chromadb
pip install sentence-transformers
pip install langchain_huggingface

其語法格式如下:

SemanticSimilarityExampleSelector.from_examples(
 # 可供選擇的示例列表
 examples,
 # 生成嵌入的嵌入類,用於衡量語義相似性
 embeddings,
 # 存儲嵌入和執行相似性搜索的VectorStore類
 Chroma,
 # 要生成示例數
 k=1
)

示例代碼如下:

from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.prompts.example_selector import SemanticSimilarityExampleSelector

# 示例
examples = [
    {
        "question""乾隆和曹操誰活得更久?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:乾隆去世時幾歲?
        中間答案:乾隆去世時87歲。
        追問:曹操去世時幾歲?
        中間答案:曹操去世時66歲。
        所以最終答案是:乾隆
        """,
    },
    {
        "question""小米手機的創始人什麼時候出生?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:小米手機的創始人是誰?
        中間答案:小米手機由雷軍創立。
        跟進:雷軍什麼時候出生?
        中間答案:雷軍出生於1969年12月16日。
        所以最終的答案是:1969年12月16日。
        """,
    },
    {
        "question""喬治·華盛頓的外祖父是誰?",
        "answer""""
        這裏是否需要跟進問題:是的。
        追問:喬治·華盛頓的母親是誰?
        中間答案:喬治·華盛頓的母親是瑪麗·鮑爾·華盛頓。
        追問:瑪麗·鮑爾·華盛頓的父親是誰?
        中間答案:瑪麗·鮑爾·華盛頓的父親是約瑟夫·鮑爾
        """,
    }
]

# 模型
embeddings_path = "F:\model\ge-large-zh-v1.5"
# 加載、預訓練模型生成文本嵌入類
embeddings = HuggingFaceEmbeddings(model_name=embeddings_path)

# 使用示例選擇器
example_selector = SemanticSimilarityExampleSelector.from_examples(
    examples,
    embeddings,
    Chroma,
    k=1
)
question = '小米手機的創始人是誰'
selected_examples = example_selector.select_examples({"question": question})
print(f"最相似的示例:{question}")
for exmaple in selected_examples:
    print("\\n")
    for k,v in exmaple.items():
        print(f'{k}:{v}')

運行結果如下:

這樣就可以獲取到最相似問題的示例。

接着就可以通過 FewShotPromptTemplate 將一組示例傳遞給模型,讓模型更好地理解用戶意圖,從而更好地回答或執行任務。

示例代碼如下:

from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# 提示詞模板
example_prompt = PromptTemplate(
    input_variables=["question""answer"], template="Question:{question}\n{answer}"
)

# 少樣本提示詞模板
prompt = FewShotPromptTemplate(
    example_selector=example_selector,        # 示例樣本
    example_prompt=example_prompt,  # 提示詞模板
    suffix="Question:{input}",     # 提示詞模板最後追加的內容
    input_variables=['input']      # 定義suffix中包含的模板變量
)

print(prompt.format(input="喬治·華盛頓的外祖父是誰?"))

好了,LangChain 教程——提示詞模板就講到這裏了,下一篇我們學習 LangChain 教程——輸出解析器。

公衆號:白巧克力 LIN

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/TBqpkYLRyLMQtU_V0_977Q