GPT 最佳实践

大部分搬运翻译自openai官方文档,持续补充。

GPT 函数调用

介绍

在 API 调用中,您可以描述要对 gpt-3.5-turbo-0613gpt-4-0613 进行的函数,并让模型智能选择输出包含调用这些函数参数的 JSON 对象。聊天完成 API 不会调用该函数,而是模型生成可以在您的代码中使用来调用函数的 JSON。

最新的模型( gpt-3.5-turbo-0613gpt-4-0613)已经经过微调,既可以检测到何时应该调用函数(取决于输入),又可以以符合函数签名的方式回复 JSON。但这种能力也存在潜在风险。我们强烈建议在代表用户执行可能影响世界的操作之前,在代码中构建用户确认流程(发送电子邮件、发布内容在线、进行购买等)。

在底层,函数以模型训练过的语法被注入到系统消息中。这意味着函数会消耗模型的上下文限制,并作为输入标记计费。如果遇到上下文限制,我们建议限制函数的数量或者减少提供给函数参数的文档长度。

函数调用允许您从模型中更可靠地获得结构化数据。例如,您可以:

  • 通过调用外部API创建能够回答问题的聊天机器人(例如 ChatGPT 插件)
    • 例如,定义类似于 send_email(to: string, body: string)get_current_weather(location: string, unit: 'celsius' | 'fahrenheit') 的函数
  • 将自然语言转换为API调用
    • 例如,将 “Who are my top customers?” 转换为 get_customers(min_revenue: int, created_before: string, limit: int)并调用内部 API
  • 从文本中提取结构化数据
    • 例如,定义一个名为 extract_data(name: string, birthday: string)sql_query(query: string)的函数

….

函数调用的基本步骤如下:

  1. 使用用户查询和在函数参数中定义的一组函数来调用模型。
  2. 模型可以选择调用一个函数;如果是这样,内容将是一个符合您自定义架构的字符串化 JSON 对象(注意:模型可能生成无效的 JSON 或产生虚构的参数)。
  3. 在您的代码中将字符串解析为 JSON,并根据提供的参数调用您的函数(如果存在)。
  4. 通过将函数响应作为新消息附加到模型中再次调用模型,并让模型将结果总结给用户。

示例

import openai
import json


# 示例虚拟函数硬编码返回相同的天气
# 在生产环境中,这可以是您的后端API或外部API
def get_current_weather(location, unit="fahrenheit"):
    """获取给定位置的当前天气"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)


def run_conversation():
    # Step 1: 将对话和可用函数发送给GPT
    messages = [{"role": "user", "content": "波士顿的天气如何?"}]
    functions = [
        {
            "name": "get_current_weather",
            "description": "获取给定位置的当前天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "请提供城市和州,例如:加利福尼亚州旧金山",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        }
    ]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=functions,
        function_call="auto",  # "auto" 是默认选项,但我们将明确指定
    )
    response_message = response["choices"][0]["message"]

    # Step 2: 检查GPT是否想要调用一个函数
    if response_message.get("function_call"):
        # Step 3: 调用该函数
        # Note: JSON响应可能并非始终有效,请确保处理错误
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # 在这个示例中只有一个函数,但是您可以拥有多个函数
        function_name = response_message["function_call"]["name"]
        fuction_to_call = available_functions[function_name]
        function_args = json.loads(response_message["function_call"]["arguments"])
        function_response = fuction_to_call(
            location=function_args.get("location"),
            unit=function_args.get("unit"),
        )

        # Step 4: 将函数调用的信息和函数响应发送给GPT
        messages.append(response_message)  # 扩展与助手回复的对话
        messages.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # 扩展对话与函数响应
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages,
        )  # 从GPT获取一个新的响应,其中可以查看函数的响应
        return second_response


print(run_conversation())

在函数调用中出现幻觉的输出通常可以通过系统消息来减轻。例如,如果你发现一个模型在生成函数调用时使用了没有提供的函数,尝试使用一个系统消息,如:”只使用您所提供的函数。”

在上面的示例中,我们将函数的响应发送回模型,让模型决定下一步的操作。它会以面向用户的消息作为回应,告诉用户波士顿的温度,但根据查询的内容,它可能会选择再次调用一个函数。

例如,如果你问模型“找出波士顿本周末的天气,预订周六晚上两个人的晚餐,并更新我的日历”,并提供相应的函数来处理这些查询,它可以选择连续调用它们,并只在最后生成一个面向用户的消息。

如果你想强制模型调用特定的函数,你可以设置 function_call: {“name”: “<插入函数名称>"}。你也可以通过设置 function_call: "none" 强制模型生成一个面向用户的消息。请注意,默认行为(function_call: "auto")是让模型自己决定是否调用一个函数,如果是的话,调用哪个函数。

相关参数文档

functions

array 可选 模型可能生成JSON输入的功能列表。

name

string 必填 要调用的函数名称。必须由小写字母a-z、大写字母A-Z、数字0-9或包含下划线和破折号构成,最长长度为64个字符。

description

string 可选 该函数的描述,由模型用于选择何时以及如何调用该函数。

parameters

object 必填 函数接受的参数,以JSON Schema对象的形式描述。请参考指南中的示例以及JSON Schema参考文档中的格式说明。

要描述一个不接受任何参数的函数,请提供值为{“type”: “object”, “properties”: {}}的对象。

function_call

string or object 可选 控制模型对函数调用的响应方式。”none” 表示模型不调用函数,并直接响应给最终用户。”auto” 表示模型可以选择是响应最终用户还是调用函数。通过 {“name”: “my_function”} 来指定特定函数会强制模型调用该函数。当没有函数存在时,默认为”none”。如果存在函数,则默认为”auto”。

六种获取更好结果的策略

请提供清晰的指示

GPT无法读取你的思维。如果输出太长,请要求简短回复。如果输出太简单,请要求专家级的写作。如果你不喜欢格式,请展示你想要看到的格式。GPT越少猜测你想要什么,你得到期望结果的可能性就越大

策略:在您的查询中包含详细信息以获得更相关的回答

为了获得高度相关的回应,请确保请求提供任何重要的细节或背景。否则,您将让模型猜测您的意思。

Worse Better
在Excel中如何相加数字? 在Excel中如何对一行美元金额进行求和?我想要自动为整个工作表的每一行进行求和,并且将所有的总和显示在右侧的名为”Total”的列中。
谁是总统? 2021年墨西哥的总统是谁,选举频率是多久一次?
写代码计算斐波那契数列。 用 TypeScript 编写高效计算斐波那契数列的函数,代码中要详细注释解释每个部分的作用和为什么这样编写。
总结会议记录。 总结会议记录为一个段落。然后编写一个markdown列表,包括每位发言人和他们的要点。最后,列出发言人建议的下一步或行动项,如果有的话。

策略:要求模型采用特定角色形象

可以使用系统消息来指定模型在回复中所采用的角色形象。

SYSTEM 当我请求帮助写作时,你会回复一个包含至少每段都有一个笑话或调侃的文件。 USER 给我的钢螺栓供应商写一封感谢信,感谢他们在短时间内准时送货。这使我们能够完成一份重要的订单。

策略:使用分隔符清晰地指示输入的不同部分

像三重引号、XML标签、章节标题等分隔符可以帮助标记文本的不同部分,以便进行不同处理。

USER
Summarize the text delimited by triple quotes with a haiku.

"""insert text here"""
SYSTEM
You will be provided with a pair of articles (delimited with XML tags) about the same topic. First summarize the arguments of each article. Then indicate which of them makes a better argument and explain why.

USER
<article> insert first article here </article>

<article> insert second article here </article>
SYSTEM
You will be provided with a thesis abstract and a suggested title for it. The thesis title should give the reader a good idea of the topic of the thesis but should also be eye-catching. If the title does not meet these criteria, suggest 5 alternatives.

USER
Abstract: insert abstract here

Title: insert title here

对于这样的简单任务,使用分隔符可能不会对输出质量产生影响。然而,任务越复杂,消除任务细节的歧义就越重要。不要让GPTs费力去理解你具体想要什么。

策略:确定完成任务所需的步骤

有些任务最好被指定为一系列步骤。将这些步骤明确地写出来可以让模型更容易遵循它们。

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"""
SYSTEM
使用以下逐步说明来回应用户输入。

Step 1 - 用户将以三重引号的形式为您提供文本,请用一个带有“Summary: ”前缀的句子进行总结。

Step 2 - 将第一步的摘要翻译成西班牙语,并在前面加上“Translation:”。


USER
"""insert text here"""

策略:提供示例

通常来说,提供适用于所有示例的一般指导比通过示例展示任务的各种变化更有效率,但在某些情况下,提供示例可能更容易。例如,如果你打算让模型复制一种难以明确描述的对用户查询作出回应的特定风格,这被称为“少样本”提示。

SYSTEM
Answer in a consistent style.

USER
Teach me about patience.

ASSISTANT
The river that carves the deepest valley flows from a modest spring; the grandest symphony originates from a single note; the most intricate tapestry begins with a solitary thread.

USER
Teach me about the ocean.
SYSTEM
以一致的风格回答。

USER
关于耐心的知识,请教我。

ASSISTANT
从一个谦逊的泉源涌出的河流开凿出最深的峡谷;最壮丽的交响乐从一声孤独的音符起源;最精巧的挂毯由一根孤立的线开始。

USER
关于海洋的知识,请教我。

策略:指定输出的期望长度

您可以要求模型生成特定长度的输出。目标输出长度可以根据单词、句子、段落、项目符号等来指定。但请注意,指示模型生成特定数量的单词并不具有高精度。模型可以更可靠地生成具有特定数量的段落或项目符号的输出。

USER
Summarize the text delimited by triple quotes in about 50 words.

"""insert text here"""
USER
Summarize the text delimited by triple quotes in 2 paragraphs.

"""insert text here"""
USER
Summarize the text delimited by triple quotes in 3 bullet points.

"""insert text here"""

提供参考文本

GPT在回答关于深奥话题、引用和URL的问题时,往往可以自信地编造虚假答案。就像一张笔记纸可以帮助学生在考试中表现更好一样,给GPT提供参考文本可以减少虚构的答案,并帮助它更好地回答问题。

策略:指导模型使用参考文本回答

如果我们能够为模型提供与当前查询相关的可信信息,我们可以指导模型使用提供的信息来组织其回答。

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>
SYSTEM
请使用三个引号括起来的提供的文章来回答问题。如果在文章中找不到答案,请写下“我找不到答案。”

USER
<插入文章,每篇文章由三个引号分隔>

Question: <这里插入问题>

鉴于GPT模型具有有限的上下文窗口,在应用这种策略时,我们需要一种动态查找与所提问问题相关信息的方法。嵌入可以用于实现高效的知识检索。有关如何实施此方法的详细信息,请参阅“使用基于嵌入的搜索来实现高效的知识检索”策略。

策略:指示模型使用参考文本中的引文回答

如果输入已经补充了相关知识,可以直接要求模型通过引用提供的文档中的段落来添加引文以回答问题。请注意,输出中的引文可以通过在提供的文档中进行字符串匹配来进行程序验证。

SYSTEM
You will be provided with a document delimited by triple quotes and a question. Your task is to answer the question using only the provided document and to cite the passage(s) of the document used to answer the question. If the document does not contain the information needed to answer this question then simply write: "Insufficient information." If an answer to the question is provided, it must be annotated with a citation. Use the following format for to cite relevant passages ({"citation": …}).

USER
"""<insert document here>"""

Question: <insert question here>
SYSTEM
您将获得一个由三个引号分隔的文档和一个问题。您的任务是仅使用提供的文档回答问题,并引用用于回答问题的文段。如果文档中没有包含回答此问题所需的信息,则简单地写上:“信息不足”。如果提供了问题的答案,则必须使用以下格式对其进行注释({"citation": ...})。

USER
"""<这里插入文档>"""

Question: <这里插入问题>

将复杂任务分解为简单子任务

就像在软件工程中将一个复杂系统拆分为一组模块化的组件是一种良好的实践一样,提交给GPT的任务也是如此。与简单任务相比,复杂任务往往具有更高的错误率。此外,复杂任务通常可以重新定义为一系列简单任务的工作流程,在其中前面任务的输出被用来构建后续任务的输入。

策略:使用意图分类来识别用户查询中最相关的指令

对于需要处理不同情况下大量独立指令集的任务,首先对查询类型进行分类,并利用该分类确定所需的指令可能是有益的。可以通过定义固定类别并硬编码与处理给定类别任务相关的指令来实现这一点。此过程也可以递归应用于将任务分解为一系列阶段。这种方法的优势在于每个查询只包含执行任务下一个阶段所需的指令,与使用单个查询执行整个任务相比,这可能导致较低的错误率。这也可能导致较低的成本,因为更大的提示会产生更多费用(请参阅定价信息)。 假设以客户服务应用程序为例,查询可以有以下有用的分类:

SYSTEM
You will be provided with customer service queries. Classify each query into a primary category and a secondary category. Provide your output in json format with the keys: primary and secondary.

Primary categories: Billing, Technical Support, Account Management, or General Inquiry.

Billing secondary categories:
- Unsubscribe or upgrade
- Add a payment method
- Explanation for charge
- Dispute a charge

Technical Support secondary categories:
- Troubleshooting
- Device compatibility
- Software updates

Account Management secondary categories:
- Password reset
- Update personal information
- Close account
- Account security

General Inquiry secondary categories:
- Product information
- Pricing
- Feedback
- Speak to a human


USER
I need to get my internet working again.

根据客户查询的分类,可以为GPT模型提供一组更具体的指示,以处理接下来的步骤。例如,假设客户需要“故障排除”方面的帮助。

SYSTEM
You will be provided with customer service inquiries that require troubleshooting in a technical support context. Help the user by:

- Ask them to check that all cables to/from the router are connected. Note that it is common for cables to come loose over time.
- If all cables are connected and the issue persists, ask them which router model they are using
- Now you will advise them how to restart their device:
-- If the model number is MTD-327J, advise them to push the red button and hold it for 5 seconds, then wait 5 minutes before testing the connection.
-- If the model number is MTD-327S, advise them to unplug and replug it, then wait 5 minutes before testing the connection.
- If the customer's issue persists after restarting the device and waiting 5 minutes, connect them to IT support by outputting {"IT support requested"}.
- If the user starts asking questions that are unrelated to this topic then confirm if they would like to end the current chat about troubleshooting and classify their request according to the following scheme:

<insert primary/secondary classification scheme from above here>

USER
I need to get my internet working again.

请注意,模型已被指示发出特殊字符串来指示对话状态的变化。这使得我们能够将系统转变为一个有状态的机器,其中状态决定了应该注入哪些指令。通过跟踪状态、确定在该状态下相关的指令,并可选地确定从该状态允许的状态迁移,我们可以为用户体验设置防护措施,这在采用更少结构化方法时很难实现。

策略:对于需要非常长对话的应用,可以对先前的对话进行总结或过滤

由于GPT具有固定的上下文长度,在用户和助手之间的对话中,如果整个对话都包含在上下文窗口中,则无法无限期地进行对话。 对此问题有各种解决方法,其中之一是对先前的对话进行总结。一旦输入的大小达到预定的阈值长度,这可能会触发一个查询,对对话的一部分进行总结,并将之前对话的总结作为系统消息的一部分包括进来。另一种选择是在整个对话期间异步地在后台对先前的对话进行总结。 另一种解决方案是动态选择与当前查询最相关的先前对话部分。请参考策略“使用基于嵌入式搜索来实现高效的知识检索”。

策略:分段摘要长文档并递归构建完整摘要

由于GPT模型有固定的上下文长度,因此无法在单个查询中用于摘要超过上下文长度减去已生成摘要长度的文本。 为了摘要非常长的文档,例如一本书,我们可以使用一系列查询来对每个部分进行摘要。将部分摘要连接起来,并进行再次摘要,从而产生摘要的摘要。这个过程可以递归进行,直到整个文档被摘要。如果需要使用先前部分的信息才能理解后续部分,那么在摘要当前内容时,包含一个之前文本的运行摘要可能是有用的技巧。关于此摘要方法在摘要书籍方面的有效性,OpenAI 以 GPT-3 的变体进行了相关研究

给GPT一些时间来”思考”

如果让你计算17乘以28,你可能不会立刻知道答案,但是在一段时间内你可以计算出来。同样地,当GPT尝试立即回答问题而不是花点时间计算时,它会产生更多的推理错误。在得到答案之前,要求GPT给出推理过程的链条可以帮助它更可靠地通过推理找到正确答案。

策略:在匆忙得出结论之前,指导模型自行解决问题

有时候,我们明确指导模型在得出结论之前从基本原理进行推理,可以获得更好的结果。例如,假设我们想要让一个模型评估学生对数学问题的解决方案。最直接的方法是询问模型学生的解决方案是否正确。

SYSTEM
Determine if the student's solution is correct or not.


USER
Problem Statement: I'm building a solar power installation and I need help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost me a flat $100k per year, and an additional $10 / square foot
What is the total cost for the first year of operations as a function of the number of square feet.

Student's Solution: Let x be the size of the installation in square feet.
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000


ASSISTANT
The student's solution is correct.

但是学生的解决方案实际上是不正确的!我们可以通过提示模型先生成自己的解决方案来成功地让模型注意到这一点。

SYSTEM
First work out your own solution to the problem. Then compare your solution to the student's solution and evaluate if the student's solution is correct or not. Don't decide if the student's solution is correct until you have done the problem yourself.


USER
Problem Statement: I'm building a solar power installation and I need help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost me a flat $100k per year, and an additional $10 / square foot
What is the total cost for the first year of operations as a function of the number of square feet.

Student's Solution: Let x be the size of the installation in square feet.
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000


ASSISTANT
Let x be the size of the installation in square feet.
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 10x
Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000

The student's solution is incorrect. They made an error in the maintenance cost calculation, using 100x instead of 10x. The correct total cost for the first year of operations is 360x + 100,000.

策略:使用内心独白或一系列问题来隐藏模型的推理过程

前面的策略表明,模型在回答具体问题之前,有时需要对问题进行详细推理是很重要的。对于某些应用程序来说,模型达到最终答案所使用的推理过程可能不适合与用户分享。例如,在辅导应用程序中,我们可能希望鼓励学生自己解决问题,但模型关于学生解决方案的推理过程可能会向学生透露答案。 内心独白是一种可以用来减轻这种情况的策略。内心独白的想法是指示模型将应该对用户隐藏的部分输出放入结构化格式,以便容易解析。然后,在向用户呈现输出之前,对输出进行解析,只有部分输出可见。

SYSTEM
Follow these steps to answer the user queries.

Step 1 - First work out your own solution to the problem. Don't rely on the student's solution since it may be incorrect. Enclose all your work for this step within triple quotes (""").

Step 2 - Compare your solution to the student's solution and evaluate if the student's solution is correct or not. Enclose all your work for this step within triple quotes (""").

Step 3 - If the student made a mistake, determine what hint you could give the student without giving away the answer. Enclose all your work for this step within triple quotes (""").

Step 4 - If the student made a mistake, provide the hint from the previous step to the student (outside of triple quotes). Instead of writing "Step 4 - ..." write "Hint:".


USER
Problem Statement: <insert problem statement>

Student Solution: <insert student solution>

另外,这也可以通过一系列查询来实现,其中除了最后一个查询以外的所有输出都对最终用户隐藏。 首先,我们可以要求模型独立解决问题。由于这个初始查询不需要学生的解决方案,因此可以省略它。这带来了额外的好处,即模型的解决方案不会被学生尝试的解决方案所偏倚。

USER
<insert problem statement>

Next, we can have the model use all available information to assess the correctness of the student’s solution.

SYSTEM
Compare your solution to the student's solution and evaluate if the student's solution is correct or not.


USER
Problem statement: """<insert problem statement>"""

Your solution: """<insert model generated solution>"""

Student’s solution: """<insert student's solution>"""

Finally, we can let the model use its own analysis to construct a reply in the persona of a helpful tutor.

SYSTEM
You are a math tutor. If the student made an error, offer a hint to the student in a way that does not reveal the answer. If the student did not make an error, simply offer them an encouraging comment.


USER
Problem statement: """<insert problem statement>"""

Your solution: """<insert model generated solution>"""

Student’s solution: """<insert student's solution>"""

Analysis: """<insert model generated analysis from previous step>"""

策略:询问模型之前是否遗漏了任何内容

假设我们正在使用一个模型来列出与特定问题相关的源文摘。在列出每个文摘后,模型需要确定是继续写下一个还是停止。如果源文件很大,模型经常会过早停止并未列出所有相关的文摘。在这种情况下,通过提示模型进行跟进查询以找到其先前遗漏的文摘,通常可以获得更好的性能。

SYSTEM
You will be provided with a document delimited by triple quotes. Your task is to select excerpts which pertain to the following question: "What significant paradigm shifts have occurred in the history of artificial intelligence."

Ensure that excerpts contain all relevant context needed to interpret them - in other words don't extract small snippets that are missing important context. Provide output in JSON format as follows:

[{"excerpt": "..."},
...
{"excerpt": "..."}]


USER
"""<insert document here>"""


ASSISTANT
[{"excerpt": "the model writes an excerpt here"},
...
{"excerpt": "the model writes another excerpt here"}]


USER
Are there more relevant excerpts? Take care not to repeat excerpts. Also ensure that excerpts contain all relevant context needed to interpret them - in other words don't extract small snippets that are missing important context.

使用外部工具

通过将其他工具的输出提供给GPT来弥补其不足之处。例如,文本检索系统可以告诉GPT相关的文件信息。代码执行引擎可以帮助GPT进行数学计算和代码运行。如果一个任务可以通过工具而不是GPT更可靠或更高效地完成,可以将其转移到该工具上,以充分发挥双方的优势。

策略:使用基于嵌入的搜索来实现高效的知识检索

如果作为输入的一部分提供外部信息,模型可以利用这些信息。这有助于模型生成更具见解和更新的回应。例如,如果用户问一个关于特定电影的问题,将关于电影的高质量信息(如演员、导演等)添加到模型的输入中可能会很有用。嵌入可以用来实现高效的知识检索,以便在运行时动态地将相关信息添加到模型输入中。

文本嵌入是一个可以衡量文本字符串相关性的向量。相似或相关的字符串将比不相关的字符串更接近。这个事实以及快速向量搜索算法的存在意味着可以使用嵌入来实现高效的知识检索。特别是,可以将文本语料库分成多个块,并对每个块进行嵌入和存储。然后,可以对给定的查询进行嵌入和向量搜索,以找到与查询最相关(即在嵌入空间中最接近)的语料库中的嵌入文本块。

示例实现可以在 OpenAI Cookbook 中找到。请参考“指导模型使用检索的知识回答查询”这个策略,了解如何使用知识检索来最大程度地减少模型编造错误事实的可能性。

策略:使用代码执行来进行更准确的计算或调用外部API

GPT无法单独准确地执行算术或长时间的计算。在需要进行这种计算的情况下,可以指示模型编写和运行代码,而不是进行自己的计算。特别是,可以指示模型将要运行的代码放入指定的格式中,比如三个反引号。生成输出后,可以提取并运行代码。最后,如果需要,可以将代码执行引擎(例如Python解释器)的输出作为下一个查询的输入提供给模型。

SYSTEM
You can write and execute Python code by enclosing it in triple backticks, e.g. ```code goes here```. Use this to perform calculations.


USER
Find all real-valued roots of the following polynomial: 3*x**5 - 5*x**4 - 3*x**3 - 7*x - 10.

代码执行的另一个很好的用例是调用外部 API。如果模型被指导正确使用 API,它可以编写利用该 API 的代码。您可以通过提供文档和/或代码示例来教会模型如何使用 API。

SYSTEM
You can write and execute Python code by enclosing it in triple backticks. Also note that you have access to the following module to help users send messages to their friends:

```python
import message
message.write(to="John", message="Hey, want to meetup after work?")```

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

策略:给模型提供特定函数的访问权限

Chat Completions API允许在请求中传递一系列函数描述。这使得模型能够根据提供的模式生成函数参数。生成的函数参数以JSON格式由API返回,并可以用于执行函数调用。函数调用提供的输出可以在以下请求中反馈给模型,从而闭环操作。这是使用GPT模型调用外部函数的推荐方法。要了解更多信息,请参阅我们介绍性GPT指南中的函数调用部分,以及OpenAI Cookbook中更多的函数调用示例。

系统地测试变化

如果能量化改进的表现,就更容易提高性能。在某些情况下,对提示进行修改可能会在一些孤立的示例上获得更好的性能,但在更具代表性的示例集上导致整体性能较差。因此,为了确保变化对性能的净增益,可能需要定义一个全面的测试套件(也称为“评估”)。