【大模型应用开发极简入门】提示工程一:1. 通过context、task、role文本结构设计有效的提示词、 2. OpenAI的提示词任务示例

本文主要是介绍【大模型应用开发极简入门】提示工程一:1. 通过context、task、role文本结构设计有效的提示词、 2. OpenAI的提示词任务示例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一. chat_completion函数
  • 二. 设计有效的提示词
    • 1.上下文
      • 1.1. 更多细节的上下文
      • 1.2. 让GPT改进上下文
    • 2.任务
      • 2.1. 提供足够的任务信息
      • 2.2. OpenAI的任务示例
        • 语法纠正
        • 总结
        • TL;DR概要
        • Python转自然语言
        • 计算时间复杂度
        • 修复Python bug
        • 产生python函数
    • 3.角色

了解LLM和OpenAI API的基础知识,之后我们就可以了解一些更高阶的知识,比如提示工程、零样本学习、少样本学习到为特定任务微调模型,接下来我们将要了解提供开发LLM驱动型应用程序所需的一切知识。

一. chat_completion函数

先来回顾一下chat_completion函数

def chat_completion(prompt, model="gpt-4", temperature=0):res = openai.ChatCompletion.create(model=model,messages=[{"role": "user", "content": prompt}],temperature=temperature,)print(res["choices"][0]["message"]["content"])

 
model和temperature是两个可选特征,分别被默认设置为gpt-4和0。

 

为了说明提示工程的原理,我们使用示例文本“As Descartes said, I think therefore”(正如笛卡儿所说,我思故)。如果将此文本输入GPT-4,那么模型自然会通过迭代式地添加最可能出现的标记来补全句子:

chat_completion("As Descartes said, I think therefore")

模型的输出消息如下所示:

I am. This famous philosophical statement, also known as "Cogito, ergo
sum," emphasizes the existence of the self through the act of thinking
or doubting. Descartes used this statement as a foundational principle
in his philosophy, arguing that one's own existence is the most certain
and indubitable fact that can be known.

 

需要注意的是:

  • 提示工程可能会影响OpenAI API的使用成本。
    该成本与你发送给OpenAI并从其接收的标记数成正比。如所述,我们强烈建议使用max_tokens参数,以避免费用超出预期。
  • 另外在openai库的方法中使用不同的参数,因为如果使用temperature、top_p和max_tokens等参数,那么即使使用相同的提示词,你也可能得到截然不同的结果。

 

二. 设计有效的提示词

很多任务可以通过提示词来完成,包括摘要、文本分类、情感分析和问题回答。在所有这些任务中,我们通常需要在提示词中定义三大要素:角色、上下文和任务,如下图。

在这里插入图片描述

这三大要素并非都是必需的,它们的顺序也不是固定的。不过,如果能够构造好提示词的结构并明确定义这三大要素,你就能够得到不错的结果。

请注意,即使使用了这三大要素,对于复杂的任务,你也可能需要采用更高级的技巧,如零样本学习、少样本学习和微调。

 

1.上下文

提示词的第一大要素是上下文。在为LLM编写输入文本时,必须尽可能详细地描述上下文。为了说明这一点,假设我们想使用GPT-4创建一个应用程序,用于推荐午餐的主菜。

1.1. 更多细节的上下文

接下来,我们将比较在两个上下文中获得的结果。第一个上下文提供较少的细节,第二个上下文则提供较多的细节。假设使用以下较短的提示词:

chat_completion("Give me a suggestion for the main course for
today's lunch.")

我们得到以下输出消息:

Grilled chicken with roasted vegetables and quinoa.

现在,在提示词中加入更多上下文信息:

prompt = """
Context: I do 2 hours of sport a day. I am vegetarian, and I don't
like green vegetables. I am conscientious about eating healthily.
Task: Give me a suggestion for a main course for today's lunch."""
chat_completion(prompt)

我们得到以下输出消息:


For today's lunch, you can try a Chickpea and Sweet Potato Curry
served with Quinoa. This dish is packed with protein, fiber, and
essential nutrients, while also being vegetarian and not relying
on green vegetables. The curry can be made with chickpeas, sweet
potatoes, tomatoes, onions, garlic, and a blend of spices like
turmeric, cumin, and coriander. Cook the quinoa separately and
serve it alongside the curry for a delicious and healthy meal.

在第二个例子中,由于提示词含有更多上下文,因此模型给出的句子更详细:它推荐了一道富含蛋白质的健康素食菜肴。

 

1.2. 让GPT改进上下文

为了找到可改进之处,你可以请GPT-4提些意见。

在下面的示例中,我们修改提示词,不再要求模型回答问题,而是指示它以增强补全效果为目标来向我们提出关于上下文的问题。使用以下提示词:

prompt = """
Context: I do 2 hours of sport a day. I am vegetarian and I don't
like green vegetables. I am very careful to eat healthily.
Task: Give me a suggestion for a main course for today's lunch? Do
not perform the requested task! Instead, can you ask me questions
about the context so that when I answer, you can perform the
requested task more efficiently?
"""
chat_completion(prompt)

GPT-4向我们提出以下问题:


Sure, I have a few questions to help me suggest a suitable main
course for you:
1. What type of sport do you do, and do you have any specific nutritional requirements related to it?
2. Are there any other vegetables or ingredients that you particularlyenjoy or dislike?
3. Do you prefer a hot or cold meal for lunch?
4. Are you open to trying new recipes or do you prefer sticking tofamiliar dishes?

模型提出的问题通常与提示词相关。根据这些问题,我们可以在提示词中更新上下文。

总之,我们建议你在构建提示词时经常使用这个技巧。

 

2.任务

任务定义了你对GPT-4模型的用法,并且应该明确且具体。你应该提供足够的任务信息,并在提示词中使用合适的短语来引导模型给出你所期望的结果。

2.1. 提供足够的任务信息

在前面的例子中,任务是让模型为午餐推荐一道主菜。我们可以为该任务添加细节,以说明我们想要的内容。在本例中,我们要求模型添加一张表格,列出每种食材所需的克数

prompt = """
Context: I do 2 hours of sport a day. I am vegetarian, and I don't
like green vegetables. I am conscientious about eating healthily.
Task: Give me a suggestion for a main course for today's lunch. With
this suggestion, I also want a table with two columns where each row
contains an ingredient from the main course. The first column of the
table is the name of the ingredient. The second column of the table
is the number of grams of that ingredient needed for one person. Do
not give the recipe for preparing the main course.
"""
chat_completion(prompt)

模型给出以下输出结果:

Suggestion for today's lunch: Stuffed Bell Peppers with Quinoa and
Black Beans
| Ingredient          | Grams per person |
|---------------------|------------------|
| Bell peppers        | 200g             |
| Quinoa              | 60g              |
| Black beans         | 75g              |
| Onion               | 50g              |
| Garlic              | 5g               |
| Olive oil           | 10g              |
| Tomato sauce        | 50g              |
| Cumin               | 1g               |
| Chili powder        | 1g               |
| Salt                | 1g               |
| Pepper              | 1g               |
| Shredded cheese     | 30g              |

 

2.2. OpenAI的任务示例

OpenAI API示例页面列出了48个任务示例。这些示例展示了GPT模型可以执行的任务,其中每个示例都配有相关的提示词和演示。见官网: Prompt examples

虽然这些示例使用了GPT-3模型和Completion端点,但对于ChatCompletion端点来说,原理是相同的,并且这些示例很好地说明了如何给OpenAI模型指派任务。

语法纠正

纠正句子中的语病,并将其修改为标准的英语句子。

from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system","content": "You will be provided with statements, and your task is to convert them to standard English."},{"role": "user","content": "She no went to the market."}],temperature=0.7,max_tokens=64,top_p=1
)

 

总结

给二年级学生概括一下

from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system","content": "Summarize content you are provided with for a second-grade student."},{"role": "user","content": "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass one-thousandth that of the Sun, but two-and-a-half times that of all the other planets in the Solar System combined. Jupiter is one of the brightest objects visible to the naked eye in the night sky, and has been known to ancient civilizations since before recorded history. It is named after the Roman god Jupiter.[19] When viewed from Earth, Jupiter can be bright enough for its reflected light to cast visible shadows,[20] and is on average the third-brightest natural object in the night sky after the Moon and Venus."}],temperature=0.7,max_tokens=64,top_p=1
)

 

TL;DR概要

TL;DR是“too long; didn’t read”的首字母缩写,意为“太长了,没读”。有人发现,只需在文本末尾添加Tl;dr,即可请求模型对文本进行总结。

提示词示例如下。

A neutron star [...] atomic nuclei. Tl;dr

 

Python转自然语言

用自然语言解释一段Python代码。

from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-4",messages=[{"role": "system","content": "You will be provided with a piece of code, and your task is to explain it in a concise way."},{"role": "user","content": "class Log:\n        def __init__(self, path):\n            dirname = os.path.dirname(path)\n            os.makedirs(dirname, exist_ok=True)\n            f = open(path, \"a+\")\n    \n            # Check that the file is newline-terminated\n            size = os.path.getsize(path)\n            if size > 0:\n                f.seek(size - 1)\n                end = f.read(1)\n                if end != \"\\n\":\n                    f.write(\"\\n\")\n            self.f = f\n            self.path = path\n    \n        def log(self, event):\n            event[\"_event_id\"] = str(uuid.uuid4())\n            json.dump(event, self.f)\n            self.f.write(\"\\n\")\n    \n        def state(self):\n            state = {\"complete\": set(), \"last\": None}\n            for line in open(self.path):\n                event = json.loads(line)\n                if event[\"type\"] == \"submit\" and event[\"success\"]:\n                    state[\"complete\"].add(event[\"id\"])\n                    state[\"last\"] = event\n            return state"}],temperature=0.7,max_tokens=64,top_p=1
)

 

计算时间复杂度

计算一个函数的时间复杂度。

from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "system","content": "You will be provided with Python code, and your task is to calculate its time complexity."},{"role": "user","content": "def foo(n, k):\n        accum = 0\n        for i in range(n):\n            for l in range(k):\n                accum += i\n        return accum"}],temperature=0.7,max_tokens=64,top_p=1
)

 

修复Python bug

修复含有bug的Python代码。

from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-4",messages=[{"role": "system","content": "You will be provided with a piece of Python code, and your task is to find and fix bugs in it."},{"role": "user","content": "import Random\n    a = random.randint(1,12)\n    b = random.randint(1,12)\n    for i in range(10):\n        question = \"What is \"+a+\" x \"+b+\"? \"\n        answer = input(question)\n        if answer = a*b\n            print (Well done!)\n        else:\n            print(\"No.\")"}],temperature=0.7,max_tokens=64,top_p=1
)

SQL请求
构建简单的SQL查询。提示词示例如下。

Create a SQL request to find all users who live in California and
have over 1000 credits.

 

产生python函数
from openai import OpenAI
client = OpenAI()response = client.chat.completions.create(model="gpt-4",messages=[{"role": "user","content": "Write a Python function that takes as input a file path to an image, loads the image into memory as a numpy array, then crops the rows and columns around the perimeter if they are darker than a threshold value. Use the mean value of rows and columns to decide if they should be marked for deletion."}],temperature=0.7,max_tokens=64,top_p=1
)

 

3.角色

在撰写提示词时,影响模型的最后一种方式是赋予其一个角色。当然,角色和上下文可以独立使用,但同时使用可以加强对模型输出的控制

在以下示例中,我们赋予模型运动营养专家的角色:

prompt = """
# Role: You are a nutritionist designing healthy diets for high-performance athletes. You take into account the nutrition needed for a good recovery.
# Context: I do 2 hours of sport a day. I am vegetarian, and I don't like green vegetables. I am conscientious about eating healthily.
# Task: Based on your expertise defined in your role, give me a suggestion for a main course for today's lunch. With this suggestion, I also want a table with two columns where each row in the table contains an ingredient from the main course. The first column of the table is the name of the ingredient. The second column of the table is the number of grams of that ingredient needed for one person. Do not give the recipe for preparing the main course.
"""
chat_completion(prompt)

 
我们得到以下结果:

Main Course Suggestion: Quinoa and Chickpea Stuffed Bell Peppers
Ingredient Table:
| Ingredient          | Grams per Person |
|---------------------|------------------|
| Quinoa              | 60               |
| Chickpeas           | 100              |
| Bell Peppers        | 200              |
| Olive Oil           | 10               |
| Onion               | 50               |
| Garlic              | 5                |
| Tomato              | 100              |
| Feta Cheese         | 30               |
| Kalamata Olives     | 20               |
| Fresh Basil         | 5                |
| Salt                | 2                |
| Black Pepper        | 1                |

 
提示词可用于调整像GPT模型这样的LLM的概率分布集。它们可以被视为模型指南,引导模型生成特定类型的结果。

 

注意,上述提到的上下文、任务、角色的提示词格式,只是一种方法,你完全可以创建不明确定义这些要素的提示词。不要受限于“上下文−任务−角色”框架,而应将其视为帮助你有效设计提示词的工具。

 

这篇关于【大模型应用开发极简入门】提示工程一:1. 通过context、task、role文本结构设计有效的提示词、 2. OpenAI的提示词任务示例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1056076

相关文章

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

RedHat运维-Linux文本操作基础-AWK进阶

你不用整理,跟着敲一遍,有个印象,然后把它保存到本地,以后要用再去看,如果有了新东西,你自个再添加。这是我参考牛客上的shell编程专项题,只不过换成了问答的方式而已。不用背,就算是我自己亲自敲,我现在好多也记不住。 1. 输出nowcoder.txt文件第5行的内容 2. 输出nowcoder.txt文件第6行的内容 3. 输出nowcoder.txt文件第7行的内容 4. 输出nowcode

一份LLM资源清单围观技术大佬的日常;手把手教你在美国搭建「百万卡」AI数据中心;为啥大模型做不好简单的数学计算? | ShowMeAI日报

👀日报&周刊合集 | 🎡ShowMeAI官网 | 🧡 点赞关注评论拜托啦! 1. 为啥大模型做不好简单的数学计算?从大模型高考数学成绩不及格说起 司南评测体系 OpenCompass 选取 7 个大模型 (6 个开源模型+ GPT-4o),组织参与了 2024 年高考「新课标I卷」的语文、数学、英语考试,然后由经验丰富的判卷老师评判得分。 结果如上图所

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

零基础STM32单片机编程入门(一)初识STM32单片机

文章目录 一.概要二.单片机型号命名规则三.STM32F103系统架构四.STM32F103C8T6单片机启动流程五.STM32F103C8T6单片机主要外设资源六.编程过程中芯片数据手册的作用1.单片机外设资源情况2.STM32单片机内部框图3.STM32单片机管脚图4.STM32单片机每个管脚可配功能5.单片机功耗数据6.FALSH编程时间,擦写次数7.I/O高低电平电压表格8.外设接口

公共筛选组件(二次封装antd)支持代码提示

如果项目是基于antd组件库为基础搭建,可使用此公共筛选组件 使用到的库 npm i antdnpm i lodash-esnpm i @types/lodash-es -D /components/CommonSearch index.tsx import React from 'react';import { Button, Card, Form } from 'antd'

大语言模型(LLMs)能够进行推理和规划吗?

大语言模型(LLMs),基本上是经过强化训练的 n-gram 模型,它们在网络规模的语言语料库(实际上,可以说是我们文明的知识库)上进行了训练,展现出了一种超乎预期的语言行为,引发了我们的广泛关注。从训练和操作的角度来看,LLMs 可以被认为是一种巨大的、非真实的记忆库,相当于为我们所有人提供了一个外部的系统 1(见图 1)。然而,它们表面上的多功能性让许多研究者好奇,这些模型是否也能在通常需要系

有效利用MRP能为中小企业带来什么?

在离散制造企业,主流的生产模式主要为面向订单生产和面向库存生产(又称为预测生产),在中小企业中,一般为面向订单生产,也有部分面向库存和面向订单混合的生产方式(以面向订单为主,面向库存为辅),主要是应对市场需求的波动,对生产稳定性造成影响。 制定资源计划至关重要,但很多中小企业目前依赖人工、Excel表格等传统方式做各种记录、统计分析。时常会遇到: 生产任务无法统筹安排, 采购不及时, 订单

ps基础入门

1.基础      1.1新建文件      1.2创建指定形状      1.4移动工具          1.41移动画布中的任意元素          1.42移动画布          1.43修改画布大小          1.44修改图像大小      1.5框选工具      1.6矩形工具      1.7图层          1.71图层颜色修改          1

C++入门01

1、.h和.cpp 源文件 (.cpp)源文件是C++程序的实际实现代码文件,其中包含了具体的函数和类的定义、实现以及其他相关的代码。主要特点如下:实现代码: 源文件中包含了函数、类的具体实现代码,用于实现程序的功能。编译单元: 源文件通常是一个编译单元,即单独编译的基本单位。每个源文件都会经过编译器的处理,生成对应的目标文件。包含头文件: 源文件可以通过#include指令引入头文件,以使