我正在参加「豆包MarsCode AI练中学体验活动」详情请看:掘金小册上线 AI练中学功能 | 你的 AI 编程助教喊你免费领小册啦!
提示词模板
提示词模板(PromptTemplate类)提供了可重用(重复用)提示词的机制。用户通过传递一组参数给模板,实例化图一个提示词。一个提示模板可以包含:
- A 对语言模型的指令
- B 一组少样本示例,以帮助语言模型生成更好的回复
- C 向语言模型提出的问题
提示词模板
from langchain import PromptTemplate
template = """
你精通多种语言,是专业的翻译官。你负责{src_lang}到{dst_lang}的翻译工作。
"""
prompt = PromptTemplate.from_template(template)
prompt.format(src_lang="英文", dst_lang="中文")
类似类似
multiple_input_prompt = PromptTemplate(
input_variables=["color", "animal"],
template="A {color} {animal} ."
)
multiple_input_prompt.format(color="black", animal="bear")
PromptTemplate(提示词模板)类是 LangChain 提供的模版基础类,它接收两个参数:
- input_variables - 输入变量
- template - 模版
聊天提示词模板
from langchain.prompts import (
ChatPromptTemplate,
PromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
system_template="You are a professional translator that translates {src_lang} to {dst_lang}."system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)
human_template="{user_input}"human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chat_prompt.format_prompt(
src_lang="English",
dst_lang="Chinese",
user_input="Did you eat in this morning?"
).to_messages()
SystemMessagePromptTemplate是基于系统级的提示词,用于命令AI要做什么,不要做什么。此处担任翻译官,将英文翻译成中文。 HumanMessagePromptTemplate是用户输入的提示词。 然后用to_messages()用于跟ChatGPT的交互
样本选择器
LangChain 提供了样本选择器的基础接口类 BaseExampleSelector,每个选择器类必须实现的函数为 select_examples。
LangChain 实现了若干基于不同应用场景或算法的选择器:
- LengthBasedExampleSelector
- MaxMarginalRelevanceExampleSelector
- NGramOverlapExampleSelector
- SemanticSimilarityExampleSelector 以基于长度的样本选择器(输入越长,选择的样本越少;输入越短,选择的样本越多) LengthBasedExampleSelector 为例:
from langchain.prompts import PromptTemplatefrom langchain.prompts import FewShotPromptTemplatefrom langchain.prompts.example_selector import LengthBasedExampleSelector# These are a lot of examples of a pretend task of creating antonyms.examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"},
{"input": "energetic", "output": "lethargic"},
{"input": "sunny", "output": "gloomy"},
{"input": "windy", "output": "calm"},
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}",
)
example_selector = LengthBasedExampleSelector(
# 可选的样本数据examples=examples,
# 提示词模版example_prompt=example_prompt,
# 格式化的样本数据的最大长度,通过get_text_length函数来衡量max_length=25
)
dynamic_prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
prefix="Give the antonym of every input",
suffix="Input: {adjective}\nOutput:",
input_variables=["adjective"],
)