2-LangChain提示词工程应用实践

在这里插入图片描述

在这里插入图片描述

提示词模版

在这里插入图片描述
在这里插入图片描述

使用函数进行部分化

另一个常见用例是使用函数进行部分化。这种情况下的用例是,当您知道您希望以常见方式获取变量时。这种情况的一个典型示例是日期或时间。想象一下,您有一个提示,您始终希望包含当前日期。您不能在提示中硬编码它,并将其与其他输入变量一起传递有点麻烦。在这种情况下,能够使用始终返回当前日期的函数部分化提示非常方便。

from datetime import datetime


def _get_datetime():
    now = datetime.now()
    return now.strftime("%m/%d/%Y, %H:%M:%S")

prompt1 = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}",
    input_variables=["adjective", "date"],
)
partial_prompt = prompt1.partial(date=_get_datetime)
print(partial_prompt.format(adjective="funny"))



您还可以使用部分化的变量初始化提示,这在这种工作流程中通常更有意义。

# 您还可以使用部分化的变量初始化提示,这在这种工作流程中通常更有意义
prompt = PromptTemplate(
    template="Tell me a {adjective} joke about the day {date}",
    input_variables=["adjective"],
    partial_variables={
   "date": _get_datetime},
)
print(prompt.format(adjective="funny"))

最简单的提示词模版

from langchain_core.prompts import (ChatPromptTemplate, HumanMessagePromptTemplate)
from langchain_core.messages import SystemMessage

# 用于创建一个 ChatPromptTemplate 实例。
# 参数是一个包含消息类型和内容的列表
promptTemplate = ChatPromptTemplate.from_messages([
    SystemMessage(content="你是世界级的技术专家, 你的名字是{name}"),
    HumanMessagePromptTemplate.from_template("{input}")

])
# 用于填充模板中的变量(如 {name} 和 {input})。
# 返回一个包含填充后消息的列表。
messages = promptTemplate.format_messages(name="张三", input="你的名字叫什么?")

print(messages)
# 打印结果
for message in messages:
    print(message)


多个角色

from langchain_core.prompts import ChatPromptTemplate


# 用于创建一个 ChatPromptTemplate 实例。
# 参数是一个包含消息类型和内容的列表
promptTemplate = ChatPromptTemplate.from_messages([
    ("system", "你是世界级的技术专家, 你的名字是{name}"),
    ("human", "你好!"),
    ("ai", "我很好,谢谢!"),
    ("human", "{input}"),
])
# 用于填充模板中的变量(如 {name} 和 {input})。
# 返回一个包含填充后消息的列表。
messages = promptTemplate.format_messages(name="张三", input="你的名字叫什么?")

print(messages)
# 打印结果
for message in messages:
    print(message)


使用类

from langchain_core.prompts import (ChatPromptTemplate, HumanMessagePromptTemplate)
from langchain_core.messages import SystemMessage

# 用于创建一个 ChatPromptTemplate 实例。
# 参数是一个包含消息类型和内容的列表
promptTemplate = ChatPromptTemplate.from_messages([
    SystemMessage(content="你是世界级的技术专家, 你的名字是{name}"),
    HumanMessagePromptTemplate.from_template("{input}")

])
# 用于填充模板中的变量(如 {name} 和 {input})。
# 返回一个包含填充后消息的列表。
messages = promptTemplate.format_messages(name="张三", input="你的名字叫什么?")

print(messages)
# 打印结果
for message in messages:
    print(message)


MessagesPlaceholder 在特定位置添加消息列表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值