python中高效构建提示词

在做大模型应用项目时,经常需要处理system_prompt和user_prompt这两个提示词,对于样例、用户输入的query等需要填入。用最普通的拼接虽然很快,但是后期迭代会有些心智负担。

最近找了一个不错的方法,就是用python的.format方法,将内容动态填充到字符串中。

这个操作其实我们之前一定有过接触,就是形如类似的:

python 复制代码
name = "golemon"
print(f"I'm {name}")
print("I'm {}".format(name))

只需要在字符串中用{}包裹即可进行填充。

python 复制代码
name = "golemon"
age = 21
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)

print(greeting)

在提示词中会经常出现下面形式:

python 复制代码
请按照一下格式输出:{"score":"打出的分","reason":"给出这个分数的原因"}
...
例子如下:
	{...}
	{...}

在上面形式中,我们只是将{}包裹的当作字符串,而不是要填充的内容,这个时候可以用{``{}}进行包裹。{``{}}在我理解,就是先用{}进行包裹,再用{}进行填充,例如:

python 复制代码
name = "golemon"
age = 21
greeting = "Hello, my name is {} and I am {} years old.".format({name}, age)

print(greeting)
# Hello, my name is {'golemon'} and I am 21 years old.
python 复制代码
sentence = "输出格式:{{'score': 0.5, 'label': 'negative'}},输入的文本是:{}"
sentence = sentence.format("我今天很开心")
print(sentence)
# 输出格式:{'score': 0.5, 'label': 'negative'},输入的文本是:我今天很开心

字符串调用 .format()有非常多的使用方法,可以自行搜索了解。

在提示词构建中,通常用的是{xxx},xxx表示用其他变量动态填充到xxx这里。

python 复制代码
sentence = "输出格式:{{'score': 0.5, 'label': 'negative'}},输入的文本是:{text}"
sentence = sentence.format(text="我今天很开心")
print(sentence)
# 输出格式:{'score': 0.5, 'label': 'negative'},输入的文本是:我今天很开心

还有format_map方法:

python 复制代码
sentence = "输出格式:{{'score': 0.5, 'label': 'negative'}},输入的文本是:{text1}, {text2}"
data = {
    "text1": "我今天很开心",
    "text2": "我今天很难过"
}
sentence = sentence.format_map(data)
print(sentence)
# 输出格式:{'score': 0.5, 'label': 'negative'},输入的文本是:我今天很开心, 我今天很难过

f-string也可以用来表示,但是对于提示词构建来说不如format好使,毕竟少个啥没有被动态填充难以直观看出来(

python 复制代码
text = "我今天很开心"
sentence = f"输出格式:{{'score': 0.5, 'label': 'negative'}},输入的文本是:{text}"
print(sentence)
# 输出格式:{'score': 0.5, 'label': 'negative'},输入的文本是:我今天很开心
相关推荐
宠友信息几秒前
MySQL复合索引与Druid优化仿小红书源码个人主页查询链路
数据库·spring boot·websocket·mysql·uni-app
minji...23 分钟前
MySQL数据库 (十九) MySQL图像化界面,MySQL连接池
数据库·mysql·navicat·mysql workbench·mysql连接池·数据库图形化界面
想躺平的小羊37 分钟前
MySQL中LAST_DAY函数用法
数据库·mysql
cui_ruicheng1 小时前
Python从入门到实战(十三):模块、包与环境管理
开发语言·python
光影6271 小时前
MySQL基础入门
数据库·笔记·sql·学习·mysql·学习方法
程序员黑豆2 小时前
从零开始:编写第一个鸿蒙(HarmonyOS)程序
前端·harmonyos
qetfw2 小时前
CentOS 7 搭建 MariaDB 数据库服务
linux·数据库·centos·mariadb
lastknight2 小时前
CSS @layer
前端·css
李宸净2 小时前
Web自动化测试selenium+python
前端·python·selenium