当前位置: 首页 > news >正文

LangChain - PromptTemplate

文章目录

    • 关于 Prompt
    • 关于 PromptTemplate
    • 基本创建
      • 无变量输入
      • 1个变量
      • 多变量
      • 使用 from_template 自动推断 input_variables
    • 聊天模板
        • 使用 from_template 方法构建
        • 使用 PromptTemplate 构建 MessagePromptTemplate
        • 使用一或多个 MessagePromptTemplates 构建一个 ChatPromptTemplate
        • 使用`ChatMessagePromptTemplate`,指定角色名称
      • MessagesPlaceholder 占位符
    • 模板格式 jinja2、f-string
    • 部分格式化提示模板
        • 使用字符串进行部分格式化
        • 函数部分化Partial With Functions
      • 验证模板
    • 自定义提示模板
    • FewShotPromptTemplate
    • PipelinePrompt 组合提示
    • 示例选择器
    • Chat模型的少样本示例
      • AIMessagePromptTemplate / HumanMessagePromptTemplate 交替
      • SystemMessagePromptTemplate
    • 输出的格式 Format output
        • 1、作为字符串
        • 2、作为`ChatPromptValue`
        • 3、作为消息对象列表:
    • 输出解析器
    • 序列化
      • 本地存储加载 json


本文整理改编自:
https://www.langchain.com.cn/modules/prompts/prompt_templates
https://python.langchain.com.cn/docs/modules/model_io/prompts/

代码基于 langchain 0.1.14 测试


关于 Prompt

编写模型的新方式是通过提示。
一个 提示(prompt) 指的是 输入模型 的内容。
这个输入通常由多个组件构成。
LangChain 提供了多个类和函数,使构建和处理提示变得简单。

  • 提示模板(Prompt templates): 为模型输入添加 参数
  • 示例选择器(Example selectors): 动态选择 在提示中 包含的示例

关于 PromptTemplate

它包含一个文本字符串(称为:模板,template),该字符串可以从最终用户那里 接收一组参数 并生成提示。

提示模板是生成语言模型提示的 预定义配方。


提示模板可能包含:

  • 对语言模型的指令,
  • 一组少量示例,以帮助语言模型生成更好的响应,
  • 适用于特定任务的特定上下文和问题

LangChain提供了创建和使用提示模板的工具。

LangChain致力于创建 与模型无关 的模板,以便在不同的语言模型之间 轻松重用现有模板。


基本创建


您可以使用 PromptTemplate 类创建简单的 硬编码提示。
提示模板可以接受任意数量的输入变量,并可以 格式化 生成提示。

示例1

from langchain import PromptTemplate 

template = '''I want you to act as a naming consultant for new companies.
What is a good name for a company that makes {product}?
'''

prompt = PromptTemplate(template = template,input_variables=['product'],
)

prompt 为:

    PromptTemplate(input_variables=['product'], output_parser=None, partial_variables={}, template='I want you to act as a naming consultant for new companies.\nWhat is a good name for a company that makes {product}?\n', template_format='f-string', validate_template=True)

prompt.format(product="colorful socks") 

    'I want you to act as a naming consultant for new companies.\nWhat is a good name for a company that makes colorful socks?\n'


手动指定 input_variables


无变量输入


no_input_prompt = PromptTemplate(input_variables=[], template="Tell me a joke.")
no_input_prompt.format()
#     'Tell me a joke.'

1个变量

one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.")one_input_prompt.format(adjective="funny")
#    'Tell me a funny joke.'

多变量

multiple_input_prompt = PromptTemplate(input_variables=["adjective", "content"], template="Tell me a {adjective} joke about {content}."
)

multiple_input_prompt.format(adjective="funny", content="chickens")
#  ->  'Tell me a funny joke about chickens.'

使用 from_template 自动推断 input_variables

根据传递的 template 自动推断 input_variables

template = "Tell me a {adjective} joke about {content}."prompt_template = PromptTemplate.from_template(template)
prompt_template.input_variables
# -> ['adjective', 'content']


prompt_template.format(adjective="funny", content="chickens")
# -> Tell me a funny joke about chickens.

聊天模板

聊天模型 以聊天消息列表作为输入 - 这个列表通常称为 prompt。
这些聊天消息与原始字符串不同(您会将其传递给 LLM 模型),因为每个消息都与一个 role 相关联。


要创建与角色相关联的消息模板,您可以使用 MessagePromptTemplate。

LangChain 提供了不同类型的 MessagePromptTemplate,其中最常用的是

  • AIMessagePromptTemplate, 创建 AI 消息
  • SystemMessagePromptTemplate , 系统消息
  • HumanMessagePromptTemplate,人类消息
  • ChatMessagePromptTemplate,允许用户指定角色名称

from langchain.prompts import (ChatPromptTemplate,PromptTemplate,SystemMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate,
)
from langchain.schema import (AIMessage,HumanMessage,SystemMessage
)

使用 from_template 方法构建
template="You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)

system_message_prompt

SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input_language', 'output_language'], output_parser=None, partial_variables={}, template='You are a helpful assistant that translates {input_language} to {output_language}.', template_format='f-string', validate_template=True), additional_kwargs={})

human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)human_message_prompt

HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=['text'], output_parser=None, partial_variables={}, template='{text}', template_format='f-string', validate_template=True), additional_kwargs={})

使用 PromptTemplate 构建 MessagePromptTemplate

更直接地构建MessagePromptTemplate:可以在外部创建一个 PromptTemplate,然后将其传递进去


prompt=PromptTemplate(template="You are a helpful assistant that translates {input_language} to {output_language}.",input_variables=["input_language", "output_language"],
)system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)
system_message_prompt_2

    SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=['input_language', 'output_language'], output_parser=None, partial_variables={}, template='You are a helpful assistant that translates {input_language} to {output_language}.', template_format='f-string', validate_template=True), additional_kwargs={})

assert system_message_prompt == system_message_prompt_2

使用一或多个 MessagePromptTemplates 构建一个 ChatPromptTemplate

可以使用ChatPromptTemplateformat_prompt方法 - 这将返回一个PromptValue
您可以将其转换为字符串或Message对象,具体取决于您是否想将格式化值用作llm或chat模型的输入。

chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

# get a chat completion from the formatted messages
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages()  

    [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),HumanMessage(content='I love programming.', additional_kwargs={}, example=False)]

使用ChatMessagePromptTemplate,指定角色名称
from langchain.prompts import ChatMessagePromptTemplateprompt = "May the {subject} be with you"chat_message_prompt = ChatMessagePromptTemplate.from_template(role="Jedi", template=prompt)chat_message_prompt.format(subject="force")

ChatMessage(content='May the force be with you', additional_kwargs={}, role='Jedi')

MessagesPlaceholder 占位符

当您不确定应该使用哪个消息提示模板的角色,或者希望在格式化期间插入消息列表时,这可能非常有用。

from langchain.prompts import MessagesPlaceholderhuman_prompt = "Summarize our conversation so far in {word_count} words."
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)chat_prompt = ChatPromptTemplate.from_messages([ MessagesPlaceholder( variable_name="conversation" ), human_message_template] ) 

human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(content="""\
1. Choose a programming language: Decide on a programming language that you want to learn. 2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")chat_prompt.format_prompt( conversation = [human_message, ai_message],  			 word_count="10").to_messages()

[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),AIMessage(content='1. Choose a programming language: Decide on a programming language that you want to learn.   2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures.  3. Practice, practice, practice: The best way to learn programming is through hands-on experience', additional_kwargs={}),HumanMessage(content='Summarize our conversation so far in 10 words.', additional_kwargs={})]

模板格式 jinja2、f-string

默认情况下,PromptTemplate 会将提供的模板作为 Python f-string 处理。您可以通过 template_format 参数指定其他模板格式:

目前,PromptTemplate 仅支持 jinja2f-string 模板格式。


运行这些之前,需要保证 jinja2 已安装
Make sure jinja2 is installed before running this

jinja2_template = "Tell me a {{ adjective }} joke about {{ content }}"jinja2_template
# ->  'Tell me a {{ adjective }} joke about {{ content }}'

prompt_template = PromptTemplate.from_template(template=jinja2_template, template_format="jinja2")  
prompt_template

    PromptTemplate(input_variables=['adjective', 'content'], output_parser=None, partial_variables={}, template='Tell me a {{ adjective }} joke about {{ content }}', template_format='jinja2', validate_template=True)

prompt_template.format(adjective="funny", content="chickens")
# -> Tell me a funny joke about chickens.

template = "I am learning langchain because {reason}."
# ->     'I am learning langchain because {reason}.'

部分格式化提示模板


使用字符串进行部分格式化

提示模板是具有.format方法的类,该方法接受键-值映射并返回字符串(提示),以传递给语言模型。

先获取某些变量

如:有一个需要两个变量foo和baz的提示模板。
如果在链条的早期就获取了foo值,但稍后才能获取了baz值,
那么等到在一个地方同时拥有两个变量 才将它们传递给提示模板可能会很麻烦。
相反,您可以使用foo值部分化提示模板,然后将部分化的提示模板传递下去,只需使用它即可。
代码如下:


prompt = PromptTemplate(template="{foo}{bar}", input_variables=["foo", "bar"])partial_prompt = prompt.partial(foo="foo");
partial_prompt

PromptTemplate(input_variables=['bar'], output_parser=None, partial_variables={'foo': 'foo'}, template='{foo}{bar}', template_format='f-string', validate_template=True)
partial_prompt.partial(foo="foo2") # 可移执行,修改无效;只能使用 partial,不能使用 format 

PromptTemplate(input_variables=['bar'], output_parser=None, partial_variables={'foo': 'foo2'}, template='{foo}{bar}', template_format='f-string', validate_template=True)
partial_prompt.format(bar="baz")

'foobaz'
partial_prompt.partial(foo="foo2") # 可移执行,修改无效;只能使用 partial,不能使用 format 

PromptTemplate(input_variables=['bar'], output_parser=None, partial_variables={'foo': 'foo2'}, template='{foo}{bar}', template_format='f-string', validate_template=True)
partial_prompt.format(bar="bar2") # 可以执行

'foobar2'
# 只使用部分变量初始化Prompt
prompt = PromptTemplate(template="{foo}{bar}", input_variables=["bar"], partial_variables={"foo": "foo"})prompt.format(bar="baz") 

foobaz

函数部分化Partial With Functions
from datetime import datetimedef _get_datetime():now = datetime.now()return now.strftime("%m/%d/%Y, %H:%M:%S")

prompt = PromptTemplate(template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective", "date"]
);partial_prompt = prompt.partial(date=_get_datetime) # 函数作为参数partial_prompt.format(adjective="funny") 

Tell me a funny joke about the day 04/07/2024, 14:08:22
# 使用部分变量初始化 Promptprompt = PromptTemplate(template="Tell me a {adjective} joke about the day {date}", input_variables=["adjective"],partial_variables={"date": _get_datetime}  # 
);prompt.format(adjective="funny")

'Tell me a funny joke about the day 04/07/2024, 14:09:11' 

验证模板

默认情况下,PromptTemplate 会通过检查 template 字符串中定义的变量是否与 input_variables 中的变量匹配来验证模板。
您可以通过将 validate_template 设置为 False 来禁用此行为。

prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"]) # ValueError due to extra variables

会报错: ValidationError: 1 validation error for PromptTemplate
因为设置需要校验


prompt_template = PromptTemplate(template=template, input_variables=["reason", "foo"],  validate_template=False) # 设置不校验,不会报错

    PromptTemplate(input_variables=['reason', 'foo'], output_parser=None, partial_variables={}, template='I am learning langchain because {reason}.', template_format='f-string', validate_template=False)

自定义提示模板

基本上有两种不同的提示模板可用-字符串提示模板和聊天提示模板。
字符串提示模板提供一个简单的字符串格式提示,而聊天提示模板生成一个更结构化的提示,可用于与聊天API一起使用。

在本指南中,我们将使用字符串提示模板创建自定义提示。


要创建一个自定义的字符串提示模板,需要满足两个要求:

  1. 它具有input_variables属性,公开了提示模板预期的输入变量。
  2. 它公开了一个format方法,该方法接受与预期的input_variables相对应的关键字参数,并返回格式化后的提示。

下例创建一个自定义的提示模板,它以函数名作为输入,并格式化提示以提供函数的源代码。
为了实现这一点,让我们首先创建一个根据函数名 返回 函数源代码的函数。

import inspectdef get_source_code(function_name):# Get the source code of the functionreturn inspect.getsource(function_name)

接下来,我们将创建一个自定义提示模板,该模板将函数名称作为输入,并格式化提示模板 以提供函数的源代码。

from langchain.prompts import StringPromptTemplate
from pydantic import BaseModel, validatorclass FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):"""A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function."""@validator("input_variables")def validate_input_variables(cls, v):"""Validate that the input variables are correct."""if len(v) != 1 or "function_name" not in v:raise ValueError("function_name must be the only input_variable.")return vdef format(self, **kwargs) -> str:# Get the source code of the functionsource_code = get_source_code(kwargs["function_name"])# Generate the prompt to be sent to the language modelprompt = f"""Given the function name and source code, generate an English language explanation of the function.Function Name: {kwargs["function_name"].__name__}Source Code:{source_code}Explanation:"""return promptdef _prompt_type(self):return "function-explainer"

使用它来为我们的任务生成提示

fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])# 为函数"get_source_code"生成一个提示
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)

FewShotPromptTemplate

from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplateexamples = [{"question": "Who lived longer, Muhammad Ali or Alan Turing?","answer": 
"""
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate answer: Alan Turing was 41 years old when he died.
So the final answer is: Muhammad Ali
"""},{"question": "When was the founder of craigslist born?","answer": 
"""
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
"""},{"question": "Who was the maternal grandfather of George Washington?","answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who was the mother of George Washington?
Intermediate answer: The mother of George Washington was Mary Ball Washington.
Follow up: Who was the father of Mary Ball Washington?
Intermediate answer: The father of Mary Ball Washington was Joseph Ball.
So the final answer is: Joseph Ball
"""},{"question": "Are both the directors of Jaws and Casino Royale from the same country?","answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who is the director of Jaws?
Intermediate Answer: The director of Jaws is Steven Spielberg.
Follow up: Where is Steven Spielberg from?
Intermediate Answer: The United States.
Follow up: Who is the director of Casino Royale?
Intermediate Answer: The director of Casino Royale is Martin Campbell.
Follow up: Where is Martin Campbell from?
Intermediate Answer: New Zealand.
So the final answer is: No
"""}
]

配置一个将少量示例 格式化为字符串的格式化程序。
该格式化程序应该是一个 PromptTemplate 对象。

example_prompt = PromptTemplate(input_variables=["question", "answer"], template="Question: {question}\n{answer}")print(example_prompt.format(**examples[0]))
    Question: Who lived longer, Muhammad Ali or Alan Turing?Are follow up questions needed here: Yes.Follow up: How old was Muhammad Ali when he died?Intermediate answer: Muhammad Ali was 74 years old when he died.Follow up: How old was Alan Turing when he died?Intermediate answer: Alan Turing was 41 years old when he died.So the final answer is: Muhammad Ali

将示例和格式化程序提供给 FewShotPromptTemplate

prompt = FewShotPromptTemplate(examples=examples, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"]
)print(prompt.format(input="Who was the father of Mary Ball Washington?"))

PipelinePrompt 组合提示

PipelinePrompt 由两个主要部分组成:

  • 最终提示: 返回的最终提示
  • 管道提示: 由一个字符串名称和一个提示模板组成的元组列表。
    每个提示模板将被格式化,然后作为相同名称的变量传递给未来的提示模板。
from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate
full_template = """{introduction}{example}{start}"""
full_prompt = PromptTemplate.from_template(full_template)
introduction_template = """You are impersonating {person}."""
introduction_prompt = PromptTemplate.from_template(introduction_template)
example_template = """Here's an example of an interaction: Q: {example_q}
A: {example_a}"""
example_prompt = PromptTemplate.from_template(example_template)
start_template = """Now, do this for real!Q: {input}
A:"""
start_prompt = PromptTemplate.from_template(start_template)
input_prompts = [("introduction", introduction_prompt),("example", example_prompt),("start", start_prompt)
]
pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)
pipeline_prompt.input_variables
# -> ['example_a', 'person', 'example_q', 'input']
print(pipeline_prompt.format(person="Elon Musk",example_q="What's your favorite car?",example_a="Telsa",input="What's your favorite social media site?"
))

    You are impersonating Elon Musk.Here's an example of an interaction: Q: What's your favorite car?A: TelsaNow, do this for real!Q: What's your favorite social media site?A:

示例选择器

我们不会直接将示例提供给 FewShotPromptTemplate 对象,而是将它们提供给一个 ExampleSelector 对象。

在本例中,我们将使用 SemanticSimilarityExampleSelector 类。该类根据输入与少量示例的相似性选择少量示例。
它使用嵌入模型计算输入与少量示例之间的相似性,以及向量存储执行最近邻搜索。

from langchain.prompts.example_selector import SemanticSimilarityExampleSelector
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddingsexample_selector = SemanticSimilarityExampleSelector.from_examples(# This is the list of examples available to select from.examples,# This is the embedding class used to produce embeddings which are used to measure semantic similarity.OpenAIEmbeddings(),# This is the VectorStore class that is used to store the embeddings and do a similarity search over.Chroma,# This is the number of examples to produce.k=1
)# Select the most similar example to the input.
question = "Who was the father of Mary Ball Washington?"
selected_examples = example_selector.select_examples({"question": question})
print(f"Examples most similar to the input: {question}")
for example in selected_examples:print("\n")for k, v in example.items():print(f"{k}: {v}")

示例选择器提供给 FewShotPromptTemplate
最后,创建一个 FewShotPromptTemplate 对象。该对象接受示例选择器和少量示例的格式化程序。

prompt = FewShotPromptTemplate(example_selector=example_selector, example_prompt=example_prompt, suffix="Question: {input}", input_variables=["input"]
)print(prompt.format(input="Who was the father of Mary Ball Washington?"))

Chat模型的少样本示例

AIMessagePromptTemplate / HumanMessagePromptTemplate 交替

from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.prompts.chat import (ChatPromptTemplate,SystemMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate,
)
from langchain.schema import AIMessage, HumanMessage, SystemMessage

chat = ChatOpenAI(temperature=0)template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = HumanMessagePromptTemplate.from_template("Hi")
example_ai = AIMessagePromptTemplate.from_template("Argh me mateys")
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, example_human, example_ai, human_message_prompt]
)
chain = LLMChain(llm=chat, prompt=chat_prompt)
# get a chat completion from the formatted messages
chain.run("I love programming.")
# -> "I be lovin' programmin', me hearty!"

SystemMessagePromptTemplate

template = "You are a helpful assistant that translates english to pirate."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
example_human = SystemMessagePromptTemplate.from_template("Hi", additional_kwargs={"name": "example_user"}
)
example_ai = SystemMessagePromptTemplate.from_template("Argh me mateys", additional_kwargs={"name": "example_assistant"}
)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, example_human, example_ai, human_message_prompt]
)
chain = LLMChain(llm=chat, prompt=chat_prompt)
# get a chat completion from the formatted messages
chain.run("I love programming.")
# -> "I be lovin' programmin', me hearty."









输出的格式 Format output

format_prompt方法的输出可以作为字符串、消息列表和ChatPromptValue使用。


1、作为字符串
output = chat_prompt.format(input_language="English", output_language="French", text="I love programming.")output
# -> 'System: You are a helpful assistant that translates English to French.\nHuman: I love programming.'

下面代码和上面等效

output_2 = chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_string()assert output == output_2

2、作为ChatPromptValue
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.")

    ChatPromptValue(messages=[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={}, example=False)])

3、作为消息对象列表:
chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages() 

[SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}), HumanMessage(content='I love programming.', additional_kwargs={})] 


输出解析器

https://www.langchain.com.cn/modules/prompts/output_parsers

输出解析器是帮助 结构化语言模型响应 的类。

有两种主要的方法,一个输出解析器必须实现:

  • get_format_instructions() -> str:一个方法,返回一个包含有关 如何格式化语言模型输出 的字符串。
  • parse(str) -> Any:一个方法,接受一个字符串(假定为语言模型的响应) 并将其解析为某个结构。

然后是一个可选的:

  • parse_with_prompt(str) -> Any:一个方法,它接受一个字符串(假设是语言模型的响应)和一个提示(假设是生成这样的响应的提示),并将其解析为某种结构。提示在此大多数情况下是为了提供信息以便OutputParser重新尝试或以某种方式修复输出。

序列化

在高层次上,序列化遵循以下设计原则:

  1. 支持JSON和YAML。我们希望支持人类在磁盘上可读的序列化方法,而YAML和JSON是其中最流行的方法之一。
    请注意,此规则适用于提示。对于其他资产,如示例,可能支持不同的序列化方法。
  2. 我们支持将所有内容都存储在一个文件中,或者将不同的组件(模板、示例等)存储在不同的文件中并进行引用。
    对于某些情况,将所有内容存储在一个文件中是最合理的,但对于其他情况,最好拆分一些资产(长模板、大型示例、可复用组件)。LangChain同时支持两种方式。

还有一个单一入口点可以从磁盘加载提示,这样可以轻松加载任何类型的提示。

更多本地存储示例,可见:https://python.langchain.com.cn/docs/modules/model_io/prompts/prompt_templates/prompt_serialization


本地存储加载 json

prompt_template.save("awesome_prompt.json")

查看文件

!cat awesome_prompt.json

内容如下

    {"input_variables": ["reason","foo"],"output_parser": null,"partial_variables": {},"template": "I am learning langchain because {reason}.","template_format": "f-string","validate_template": false,"_type": "prompt"}

from langchain.prompts import load_prompt
loaded_prompt = load_prompt("awesome_prompt.json")

loaded_prompt

    PromptTemplate(input_variables=['reason', 'foo'], output_parser=None, partial_variables={}, template='I am learning langchain because {reason}.', template_format='f-string', validate_template=False)

2024-04-08(一)

相关文章:

LangChain - PromptTemplate

文章目录 关于 Prompt关于 PromptTemplate基本创建无变量输入1个变量多变量使用 from_template 自动推断 input_variables 聊天模板使用 from_template 方法构建使用 PromptTemplate 构建 MessagePromptTemplate使用一或多个 MessagePromptTemplates 构建一个 ChatPromptTempla…...

spring cloud gateway openfeign 联合使用产生死锁问题

spring cloud gateway openfeign 联合使用产生死锁问题&#xff0c;应用启动的时候阻塞卡住。 spring.cloud 版本如下 <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><vers…...

【WPF应用37】WPF基本控件-DatePicker的详解与示例

WPF&#xff08;Windows Presentation Foundation&#xff09;是微软推出的一个用于构建桌面应用程序的图形子系统。在WPF中&#xff0c;DatePicker控件是一个常用的控件&#xff0c;用于用户选择日期。DatePicker控件提供了一个简洁直观的界面&#xff0c;使用户能够轻松选择日…...

GitHub教程:最新如何从GitHub上下载文件(下载单个文件或者下载整个项目文件)之详细步骤讲解(图文教程)

&#x1f42f; GitHub教程&#xff1a;最新如何从GitHub上下载文件(下载单个文件或者下载整个项目文件)之详细步骤讲解(图文教程) &#x1f4c1; 文章目录 &#x1f42f; GitHub教程&#xff1a;最新如何从GitHub上下载文件(下载单个文件或者下载整个项目文件)之详细步骤讲解(图…...

编译Nginx配置QUIC/HTTP3.0

1. 安装BoringSSL sudo apt update sudo apt install -y build-essential ca-certificates zlib1g-dev libpcre3 \ libpcre3-dev tar unzip libssl-dev wget curl git cmake ninja-build mercurial \ libunwind-dev pkg-configgit clone --depth1 https://github.com/google/b…...

【JavaWeb】Day38.MySQL概述——数据库设计-DQL

数据库设计——DQL 介绍 DQL英文全称是Data Query Language(数据查询语言)&#xff0c;用来查询数据库表中的记录。 查询关键字&#xff1a;SELECT 查询操作是所有SQL语句当中最为常见&#xff0c;也是最为重要的操作。在一个正常的业务系统中&#xff0c;查询操作的使用频次…...

如何使用Java和RabbitMQ实现延迟队列(方式二)?

前言 昨天写了一篇关于Java和RabbitMQ使用插件实现延迟队列功能的文章&#xff0c;今天来讲下另外一种方式&#xff0c;不需要RabbitMQ的插件。 前期准备&#xff0c;需要安装好docker、docker-compose的运行环境。 需要安装RabbitMQ的可以看下面这篇文章。 如何使用PHP和R…...

String.valueOf() 将各种数据类型的值转换为它们的字符串

String.valueOf() 是 Java 中 String 类的一个静态方法&#xff0c;用于将各种数据类型的值转换为它们的字符串表示形式。这个方法在多种情况下都非常有用&#xff0c;特别是当你需要将非字符串类型的值转换为字符串时。 方法签名 String.valueOf() 方法有多个重载版本&#…...

2024-04-08 NO.6 Quest3 自定义交互事件

文章目录 1 交互事件——更改 Cube 颜色2 交互事件——创建 Cube2.1 非代码方式2.2 代码方式 ​ 在开始操作前&#xff0c;我们导入上次操作的场景&#xff0c;相关介绍在 《2024-04-08 NO.5 Quest3 手势追踪进行 UI 交互-CSDN博客》 文章中。 1 交互事件——更改 Cube 颜色 …...

素描进阶:深入探索如何表现石膏像的质感

​素描进阶&#xff1a;深入探索如何表现石膏像的质感 素描&#xff0c;作为一种古老而经典的绘画方式&#xff0c;历来都被视为是艺术家们探索世界、理解形式与质感的重要工具。而在素描的过程中&#xff0c;如何精准地捕捉并表现物体的质感&#xff0c;是每位艺术家都需要深…...

flutter组件_AlertDialog

官方说明&#xff1a;A Material Design alert dialog. 翻译&#xff1a;一个材料设计警告对话框。 作者释义&#xff1a;显示弹窗&#xff0c;类似于element ui中的Dialog组件。 AlertDialog的定义 const AlertDialog({super.key,this.icon,this.iconPadding,this.iconColor,t…...

供应链领域主题:生产制造关键术语和系统

BOM&#xff08;Bill of Material&#xff09;物料清单 BOM&#xff08;Bill of Material&#xff09;物料清单&#xff0c;是计算机可以识别的产品结构数据文件&#xff0c;也是ERP的主导文件。BOM使系统识别产品结构&#xff0c;也是联系与沟通企业各项业务的纽带。ERP系统中…...

k8s_入门_kubelet安装

安装 在大致了解了一些k8s的基本概念之后&#xff0c;我们实际部署一个k8s集群&#xff0c;做进一步的了解 1. 裸机安装 采用三台机器&#xff0c;一台机器为Master&#xff08;控制面板组件&#xff09;两台机器为Node&#xff08;工作节点&#xff09; 机器的准备有两种方式…...

主干网络篇 | YOLOv5/v7 更换骨干网络之 HGNetv2 | 百度新一代超强主干网络

本改进已融入到 YOLOv5-Magic 框架。 论文地址:https://arxiv.org/abs/2304.08069 代码地址:https://github.com/PaddlePaddle/PaddleDetection 中文翻译:https://blog.csdn.net/weixin_43694096/article/details/131353118 文章目录 HGNetv2网络结构1.1 主干网络1.2 颈部…...

JUC:ScheduledThreadPoolExecutor 延迟任务线程池的使用

文章目录 ScheduledThreadPoolExecutortimer&#xff08;不建议用&#xff09;ScheduledThreadPoolExecutor处理异常应用 ScheduledThreadPoolExecutor timer&#xff08;不建议用&#xff09; timer也可以进行延迟运行&#xff0c;但是会有很多问题。 比如task1运行时间超过…...

js str字符串和arr数组互相转换

js str字符串和arr数组互相转换 字符串转为数组 1、split()方法 返回的是原字符串的数组 var str "hello"; var arr str.split(""); console.log(arr); //输出["h", "e", "l", "l", "o"]2、Ar…...

计算机网络——40各个层次的安全性

各个层次的安全性 安全电子邮件 Alice需要发送机密的报文m给Bob Alice 产生随机的对称秘钥&#xff0c; K s K_s Ks​使用 K s K_s Ks​对报文进行加密&#xff08;为了效率&#xff09;对 K s K_s Ks​使用Bob的公钥进行加密发送 K s ( m ) K_s(m) Ks​(m)和 K B ( K S ) K…...

OpenHarmony实战:Combo解决方案之W800芯片移植案例

本方案基于OpenHarmony LiteOS-M内核&#xff0c;使用联盛德W800芯片的润和软件海王星系列Neptune100开发板&#xff0c;进行开发移植。 移植架构采用Board与SoC分离方案&#xff0c;支持通过Kconfig图形化配置编译选项&#xff0c;增加玄铁ck804ef架构移植&#xff0c;实现了…...

【数据结构】数组(稀疏矩阵、特殊矩阵压缩、矩阵存储、稀疏矩阵的快速转置、十字链表)

稀疏矩阵、矩阵压缩、稀疏矩阵的快速转置、十字链表 目录 稀疏矩阵、矩阵压缩、稀疏矩阵的快速转置、十字链表1.数组2.数组的顺序表示和实现3.特殊矩阵的压缩存储&#xff08;1&#xff09;. 上三角矩阵—列为主序压缩存储&#xff08;2&#xff09;. 下三角矩阵—**行为主序压…...

nginx 配置访问地址和解决跨域问题(反向代理)

1、配置访问地址&#xff08;通过ip访问&#xff09; //配置ip访问地址 location ^~/auditApp{alias /usr/local/front-apps/cbd/auditApp;index index.html;if (!-e $request_filename) {rewrite ^/(.*) /auditApp/index.html last;break;}} 2、解决跨域问题&…...

支持向量机(SVM)白话之个人理解(学习记录)

本文仅有文字理解部分&#xff0c;没有相应的数学公式推导过程&#xff0c;便于新手理解。 一、什么是支持向量机 首先我们看下面这张图&#xff0c;在图中圆形和三角形分别代表不同的数据类型&#xff0c;如何画出一条直线使两者能够显著地区分开来呢&#xff1f; 答案可以多…...

【运输层】TCP 的可靠传输是如何实现的?

目录 1、发送和接收窗口&#xff08;滑动窗口&#xff09; &#xff08;1&#xff09;滑动窗口的工作流程 &#xff08;2&#xff09;滑动窗口和缓存的关系 &#xff08;3&#xff09;滑动窗口的注意事项 2、如何选择超时重传时间 &#xff08;1&#xff09;加权平均往返…...

K8s技术全景:架构、应用与优化

一、介绍 Kubernetes的历史和演进 Kubernetes&#xff08;简称K8s&#xff09;是一个开源的容器编排系统&#xff0c;用于自动化应用程序的部署、扩展和管理。它最初是由Google内部的Borg系统启发并设计的&#xff0c;于2014年作为开源项目首次亮相。 初始阶段 Kubernetes的诞生…...

Java的异常机制

异常机制 三种类型 检查型异常&#xff1a;程序员无法预见的运行时异常&#xff1a;在编译时会被忽略错误ERROR&#xff1a;错误在代码中被忽略&#xff0c;在编译时检查不到 异常处理机制 抛出异常捕获异常异常处理的五个关键字&#xff1a;try&#xff0c;catch&#xff…...

考虑预同步的虚拟同步机T型三电平逆变器并离网MATLAB仿真模型

微❤关注“电气仔推送”获得资料&#xff08;专享优惠&#xff09; 模型简介 三相 T 型三电平逆变器电路如图所示&#xff0c;逆变器主回路由三个单相 T 型逆变器组成。 直流侧输入电压为 UPV&#xff0c;直流侧中点电位 O 设为零电位&#xff0c;交流侧输出侧是三相三线制连…...

记一次k8s取证检材过期的恢复

复盘盘古石k8s的时候碰到了证书过期的问题&#xff0c;在此记录解决方法 报错信息&#xff1a;192.168.91.171:6443 was refused - did you specify the right host or port? 查看证书是否过期 kubeadm alpha certs check-expiration或 openssl x509 -in /etc/kubernetes/…...

【网站项目】自助购药小程序

&#x1f64a;作者简介&#xff1a;拥有多年开发工作经验&#xff0c;分享技术代码帮助学生学习&#xff0c;独立完成自己的项目或者毕业设计。 代码可以私聊博主获取。&#x1f339;赠送计算机毕业设计600个选题excel文件&#xff0c;帮助大学选题。赠送开题报告模板&#xff…...

Ubuntu22.04修改默认窗口系统为X11

Ubuntu22.04安装默认窗口系统为Wayland&#xff08;通过设置->关于可以看到&#xff09;。 一、用Ubuntu on Xorg会话登录 用户登录时&#xff0c;点“未列出”&#xff0c;输入用户名后&#xff0c;在登录界面底部的齿轮图标中&#xff0c;选择 "Ubuntu on Xorg&quo…...

延时队列实现实战:如何利用 RabbitMQ 实现延时队列,以满足特定延迟处理需求

实现延时队列&#xff0c;可以通过RabbitMQ的死信队列&#xff08;Dead-letter queue&#xff09;特性&#xff0c;“死信队列”是当消息过期&#xff0c;或者队列达到最大长度时&#xff0c;未消费的消息会被加入到死信队列。然后&#xff0c;我们可以对死信队列中的消息进行消…...

关于在Ubuntu上配置mysql踩的一些坑

最近准备换工作了&#xff0c;回顾了下学校时期做的那个webserver&#xff0c;又在linux下mysql踩了一些坑&#xff0c;特此记录下来 程序编译错误mysql.h: No such file or directory 云服务器缺少mysql必要的运行组件&#xff0c;安装&#xff1a; sudo apt-get install l…...