回到首页

输入关键词,多个关键词用空格分隔。

【AI Work】07 OpenAI 官方文档学习笔记

约 15 分钟

摘要

2023 年 10 月的 OpenAI 官方文档学习笔记:GPT 最佳实践(细节、人设、分隔符、步骤、样例、输出长度、参考文本、拆分任务、推理、反思、外部工具、系统测试)、API 文档通读(Chat completions、Function calling、Embeddings、Moderation、FAQ、产品与安全最佳实践)、官方示例及对应的 Prompt。

本页目录

2023 年 10 月 20 日,我学习 OpenAI 官方文档时记录了一份笔记。这是一份快速通读,目的是了解 GPT 最佳实践、API 接口和官方示例,而不是深度教程。

这是从 2023 年 10 月的笔记整理而来的。文中涉及的模型名、API 接口和产品特性都是当时的记录,今天的 API 可能已更新。

GPT 最佳实践

一个 GPT-4 进行数据分析的例子,参考 这里。

Write clear instructions

The less GPTs have to guess at what you want, the more likely you'll get it。

省流:需求描述越清楚,得到的结果越准确,不同技巧组合使用效果更佳。

包含更多细节

  • 坏:How do I add numbers in Excel?
    • 好:How do I add up a row of dollar amounts in Excel? I want to do this automatically for a whole sheet of rows with all the totals ending up on the right in a column called "Total".
  • 坏:Who's president?
    • 好:Who was the president of Mexico in 2021, and how frequently are elections held?
  • 坏:Write code to calculate the Fibonacci sequence.
    • 好:Write a TypeScript function to efficiently calculate the Fibonacci sequence. Comment the code liberally to explain what each piece does and why it's written that way.
  • 坏:Summarize the meeting notes.
    • 好:Summarize the meeting notes in a single paragraph. Then write a markdown list of the speakers and each of their key points. Finally, list the next steps or action items suggested by the speakers, if any.

给定人设

Ask the model to adopt a persona. The system message can be used to specify the persona used by the model in its replies.

SYSTEM
When I ask for help to write something, you will reply with a document that contains at least one joke or playful comment in every paragraph.
USER
Write a thank you note to my steel bolt vendor for getting the delivery in on time and in short notice. This made it possible for us to deliver an important order.

善用分隔符

Use delimiters to clearly indicate distinct parts of the input。Delimiters like triple quotation marks, XML tags, section titles, etc. can help demarcate sections of text to be treated differently。

Summarize the text delimited by triple quotes with a haiku.

"""insert text here"""

列出步骤

Specify the steps required to complete a task。Some tasks are best specified as a sequence of steps. Writing the steps out explicitly can make it easier for the model to follow them。

SYSTEM
Use the following step-by-step instructions to respond to user inputs.

Step 1 - The user will provide you with text in triple quotes. Summarize this text in one sentence with a prefix that says "Summary: ".

Step 2 - Translate the summary from Step 1 into Spanish, with a prefix that says "Translation: ".

USER
"""insert text here"""

提供样例

Providing general instructions that apply to all examples is generally more efficient than demonstrating all permutations of a task by example, but in some cases providing examples may be easier。This is known as "few-shot" prompting。

省流:Few-Shot

指定输出长度

You can ask the model to produce outputs that are of a given target length。The targeted output length can be specified in terms of the count of words, sentences, paragraphs, bullet points, etc。Note however that instructing the model to generate a specific number of words does not work with high precision。The model can more reliably generate outputs with a specific number of paragraphs or bullet points。

Provide reference text

GPTs can confidently invent fake answers, especially when asked about esoteric topics or for citations and URLs。Providing reference text to GPTs can help in answering with fewer fabrications。

使用参考文本回答

SYSTEM
Use the provided articles delimited by triple quotes to answer questions. If the answer cannot be found in the articles, write "I could not find an answer."

USER
<insert articles, each delimited by triple quotes>

Question: <insert question here>

引用参考文本回答

If the input has been supplemented with relevant knowledge, it's straightforward to request that the model add citations to its answers by referencing passages from provided documents。Note that citations in the output can then be verified programmatically by string matching within the provided documents。

省流:后续可以通过字符串匹配看是否真的引用了原文。

Split complex tasks into simpler subtasks

Just as it is good practice in software engineering to decompose a complex system into a set of modular components, the same is true of tasks submitted to GPTs。Complex tasks tend to have higher error rates than simpler tasks。

省流:复杂任务往往比简单任务具有更高的错误率,分而治之。

意图分类

Use intent classification to identify the most relevant instructions for a user query。

省流:每个查询只包含执行任务下一阶段所需的指令,与使用单个查询执行整个任务相比,可以降低错误率,也可以降低成本。

长对话要摘要

For dialogue applications that require very long conversations, summarize or filter previous dialogue。

省流:针对长对话,第一个方法是对先前的对话进行总结。一旦输入的大小达到预定的阈值长度,可以触发一个查询,对对话的部分进行总结,并将以前对话的摘要作为系统消息的一部分。第二个解决方案是动态选择与当前查询最相关的先前对话部分(基于 embedding 的方式)。

逐段摘要

Summarize long documents piecewise and construct a full summary recursively。

省流:针对一本书,我们可以先摘要,然后再生成摘要的摘要。

Give GPTs time to "think"

If asked to multiply 17 by 28, you might not know it instantly,but can still work it out with time。Similarly,GPTs make more reasoning errors when trying to answer right away,rather than taking time to work out an answer。Asking for a chain of reasoning before an answer can help GPTs reason their way toward correct answers more reliably。

让模型推导结果

Sometimes we get better results when we explicitly instruct the model to reason from first principles before coming to a conclusion。

实例:直接问是否正确,实际上无法得到正确答案。

省流:让模型先独立推导,再与用户答案对比,比直接问对错可靠。

用内心独白来隐藏推理过程

Use inner monologue or a sequence of queries to hide the model's reasoning process。Inner monologue is a tactic that can be used to mitigate this。The idea of inner monologue is to instruct the model to put parts of the output that are meant to be hidden from the user into a structured format that makes parsing them easy。Then before presenting the output to the user, the output is parsed and only part of the output is made visible。

省流:配合上一个技巧,就可以在模型按照自行推理的方式运作,但最终不会直接展示推理过程给用户。

让模型自己反思

Ask the model if it missed anything on previous passes。

省流:向模型提示后续查询以找到之前处理过程中遗漏的摘录,通常可以获得更好的表现。

Use external tools

Compensate for the weaknesses of GPTs by feeding them the outputs of other tools。If a task can be done more reliably or efficiently by a tool rather than by a GPT, offload it to get the best of both。

省流:如果一个任务可以通过工具而不是 GPT 更可靠或更高效地完成,将其转移出去以发挥双方的优势。

基于嵌入的知识检索

Use embeddings-based search to implement efficient knowledge retrieval。A text embedding is a vector that can measure the relatedness between text strings。

省流:可以将文本语料库分成多个块,并对每个块进行嵌入和存储。然后,可以对给定的查询进行嵌入,并执行向量搜索,以找到与查询最相关的文本块嵌入(即在嵌入空间中最接近的块)。

用代码做计算

Use code execution to perform more accurate calculations or call external APIs。GPTs cannot be relied upon to perform arithmetic or long calculations accurately on their own。In cases where this is needed, a model can be instructed to write and run code instead of making its own calculations。

省流:指示模型将要运行的代码放入指定的格式,例如三个反引号。在生成输出后,可以提取并运行代码。

警告!执行模型生成的代码并不是绝对安全的,在任何试图执行代码的应用程序中都应该采取预防措施。特别是,需要使用沙盒式的代码执行环境来限制不受信任的代码可能造成的危害。

使用函数调用

The Chat completions API allows passing a list of function descriptions in requests。This enables models to generate function arguments according to the provided schemas。

省流:要调用 API,就用 Function Calling,具体参考 这里。

Test changes systematically

Improving performance is easier if you can measure it。In some cases a modification to a prompt will achieve better performance on a few isolated examples but lead to worse overall performance on a more representative set of examples。

省流:要系统地测试,构造自己的测试集。

好的评估程序具备以下特点:

  1. 代表真实世界的使用情况(或至少具备多样性)
  2. 包含许多测试案例以获得更强的统计能力
  3. 易于自动化或重复执行

在不同的差异值下,为了获得95%的置信度所需的样本大小:

  • 当差异值为30%时,大约需要10个样本
  • 当差异值为10%时,大约需要100个样本
  • 当差异值为3%时,大约需要1,000个样本
  • 当差异值为1%时,大约需要10,000个样本

可以使用开源的 OpenAI Evals 构造自动测试。

和标准答案对比

Evaluate model outputs with reference to gold-standard answers。Suppose it is known that the correct answer to a question should make reference to a specific set of known facts。Then we can use a model query to count how many of the required facts are included in the answer。

API 文档通读

Chat Completions API

Chat models take a list of messages as input and return a model-generated message as output。Although the chat format is designed to make multi-turn conversations easy, it’s just as useful for single-turn tasks without any conversation。

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Who won the world series in 2020?"},
        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
        {"role": "user", "content": "Where was it played?"}
    ]
)

Because the models have no memory of past requests, all relevant information must be supplied as part of the conversation history in each request。如果遇到很长的,考虑进行压缩。

System message helps set the behavior of the assistant。The system message is optional and the model’s behavior without a system message is likely to be similar to using a generic message such as "You are a helpful assistant."

省流:在 System 中,可以给定 GPT 的"人设",我们去构造各种 agent 的能力就需要基于这个设定。

返回格式:

{
  "choices": [{ "finish_reason": "stop", "index": 0, "message": { "content": "...", "role": "assistant" } }],
  "created": 1677664795,
  "id": "chatcmpl-...",
  "model": "gpt-3.5-turbo-0613",
  "object": "chat.completion",
  "usage": { "completion_tokens": 17, "prompt_tokens": 57, "total_tokens": 74 }
}

可以用 response['choices'][0]['message']['content'] 获取返回的内容。

每个返回都会包含 finish_reason,这里的信息很重要,表示为什么结束:

  • stop: 【返回完成】API returned complete message
  • length: 【长度限制】Incomplete model output due to max_tokens parameter
  • function_call: 【调用函数】The model decided to call a function
  • content_filter: 【内容过滤】Omitted content due to a flag from our content filters
  • null: 【还没结束】API response still in progress or incomplete

Function Calling

In an API call, you can describe functions to gpt-3.5-turbo-0613 and gpt-4-0613, and have the model intelligently choose to output a JSON object containing arguments to call those functions。

在这两个模型中,可以生成调用函数的参数,供系统调用(ChatGPT 本身不会调用,需要自己写代码处理)。

【函数的文档也算 token,还不能太长】 Under the hood, functions are injected into the system message。Functions count against the model's context limit and are billed as input tokens。

常用场景:

  • 【调用外部接口】Create chatbots that answer questions by calling external APIs
  • 【自然语言变成 API 调用】Convert natural language into API calls
  • 【从文本中获取结构化数据】Extract structured data from text

Embeddings

OpenAI 的文本嵌入可以衡量文本字符串之间的相关性。嵌入通常用于以下方面:

  1. 搜索(根据与查询字符串相关性对结果进行排序)
  2. 聚类(根据相似性将文本字符串分组)
  3. 推荐(推荐具有相关文本字符串的项目)
  4. 异常检测(识别与相关性较小的异常值)
  5. 多样性测量(分析相似性分布)
  6. 分类(根据最相似的标签对文本字符串进行分类)

嵌入是由浮点数构成的向量(列表)。两个向量之间的距离衡量它们之间的相关性。较小的距离表示高相关性,较大的距离表示低相关性。

OpenAI 提供了大量使用 Embedding 的姿势说明,参考 这里。

Moderation

可以通过调用 OpenAI 接口,判断内容是否属于极端情绪的范畴(比如仇恨、威胁、自杀、性、暴力等)。

这一部分开箱即用(免费),有不少替代品,就不展开说。

FAQ

  • 为什么模型输出不一致? The API is non-deterministic by default. Setting temperature to 0 will make the outputs mostly deterministic。省流:就是会不一样。
  • 如何设置 temperature? Lower values for temperature result in more consistent outputs, while higher values generate more diverse and creative results。省流:越小越确定。
  • 最新模型可微调吗? Yes,for some。目前,只能微调 gpt-3.5-turbo 和 babbage-002 和 davinci-002。省流:部分模型可微调。
  • 是否存储输入 API 数据? As of March 1st, 2023, we retain your API data for 30 days。省流:从 2023.03.01 起,API 数据会保留 30 天。
  • 如何让应用更安全? 可以添加 moderation 层。省流:可以筛查内容。
  • 应该用 ChatGPT 还是 API? ChatGPT 自带增强功能,想要更灵活就用 API。

产品最佳实践

可以通过如下方法降低 token 的消耗:

  1. 设置更低的 max_tokens 参数
  2. 包含 stop sequences
  3. 设置更低的 n 和 best_of 参数

安全最佳实践

  • 使用免费 Moderation API
  • 对抗性测试(红队测试)
  • 人机协同(HITL)
  • 提示工程
  • 了解你的客户(KYC)
  • 限制用户输入和输出令牌数量
  • 允许用户报告问题
  • 了解并沟通局限性
  • 最终用户 ID

官方示例及对应的 Prompt

以下示例为官方示例及对应的 Prompt 速查。

语法检查

SYSTEM
You will be provided with statements, and your task is to convert them to standard English.
USER
She no went to the market.

解析非结构化数据

SYSTEM
You will be provided with unstructured data, and your task is to parse it into CSV format.
USER
There are many fruits that were found on the recently discovered planet Goocrux. There are neoskizzles that grow there, which are purple and taste like candy. There are also loheckles, which are a grayish blue fruit and are very tart, a little bit like a lemon. Pounits are a bright green color and are more savory than sweet. There are also plenty of loopnovas which are a neon pink flavor and taste like cotton candy. Finally, there are fruits called glowls, which have a very sour and bitter taste which is acidic and caustic, and a pale orange tinge to them.

关键词抽取

SYSTEM
You will be provided with a block of text, and your task is to extract a list of keywords from it.
USER
Black-on-black ware is a 20th- and 21st-century pottery tradition developed by the Puebloan Native American ceramic artists in Northern New Mexico. Traditional reduction-fired blackware has been made for centuries by pueblo artists. Black-on-black ware of the past century is produced with a smooth surface, with the designs applied through selective burnishing or the application of refractory slip. Another style involves carving or incising designs and selectively polishing the raised areas. For generations several families from Kha'po Owingeh and P'ohwhóge Owingeh pueblos have been making black-on-black ware with the techniques passed down from matriarch potters. Artists from other pueblos have also produced black-on-black ware. Several contemporary artists have created works honoring the pottery of their ancestors.

Python Bug 修复

SYSTEM
You will be provided with a piece of Python code, and your task is to find and fix bugs in it.
USER
import Random
a = random.randint(1,12)
b = random.randint(1,12)
for i in range(10):
    question = "What is "+a+" x "+b+"? "
    answer = input(question)
    if answer = a*b
        print (Well done!)
    else:
        print("No.")

构建随机 CSV 数据

USER
Create a two-column CSV of top science fiction movies along with the year of release.

推特(短文本)情感分析

SYSTEM
You will be provided with a tweet, and your task is to classify its sentiment as positive, neutral, or negative.
USER
I loved the new Batman movie!

翻译

SYSTEM
You will be provided with a sentence in English, and your task is to translate it into French.
USER
My name is Jane. What is yours?

自然语言转换成 SQL

SYSTEM
Given the following SQL tables, your job is to write queries given a user's request.

CREATE TABLE Orders (
  OrderID int,
  CustomerID int,
  OrderDate datetime,
  OrderTime varchar(8),
  PRIMARY KEY (OrderID)
);

CREATE TABLE OrderDetails (
  OrderDetailID int,
  OrderID int,
  ProductID int,
  Quantity int,
  PRIMARY KEY (OrderDetailID)
);

CREATE TABLE Products (
  ProductID int,
  ProductName varchar(50),
  Category varchar(50),
  UnitPrice decimal(10, 2),
  Stock int,
  PRIMARY KEY (ProductID)
);

CREATE TABLE Customers (
  CustomerID int,
  FirstName varchar(50),
  LastName varchar(50),
  Email varchar(100),
  Phone varchar(20),
  PRIMARY KEY (CustomerID)
);
USER
Write a SQL query which computes the average total order value for all orders on 2023-04-01.

参考链接


注:本文保留了 2023 年 10 月 OpenAI 官方文档学习笔记的原文和立场,发布时整理为标准 Markdown。原笔记是学习笔记,不是多篇整理稿,因此保留原始日期 2023-10-20。笔记中的模型名、API 接口和产品特性是当时的记录,今天的 API 可能已更新,未对 Prompt 做验证。

本文 Markdown 版本机器可读站点索引:llms.txt

相关文章