# 介绍

## 预览

OpenAI API可应用于几乎任何涉及自然语言、代码或图像的任务。我们提供不同功率级别的模型，适用于不同的任务，同时还提供自定义模型的微调功能。这些模型可用于从内容生成到语义搜索和分类的各个方面。

## 关键概念

我们建议您完成我们的快速入门教程，通过一个互动的实例来熟悉关键概念。

### 提示

设计您的提示实质上是如何“编程”模型，通常通过提供一些指示或几个示例。这与大多数其他 NLP 服务不同，它们专为单个任务设计，例如情感分类或命名实体识别。相反，完成和聊天完成终点可以用于几乎任何任务，包括内容或代码生成、摘要、扩展、对话、创意写作、风格转移等。

## 标记

我们的模型通过将文本分解成标记来理解和处理文本。标记可以是单词或仅仅是字符块。例如，单词“汉堡包”被分解为标记“ham”、“bur”和“ger”，而像“梨”这样的短而常见的单词则是一个标记。许多标记以空格开头，例如“ hello”和“ bye”。

在给定的 API 请求中处理的标记数量取决于您的输入和输出的长度。粗略的经验法则是，对于英文文本，1 个标记约为 4 个字符或 0.75 个单词。需要记住的一个限制是，您的文本提示和生成的完成组合不能超过模型的最大上下文长度（对于大多数模型，这是 2048 个标记，或者约 1500 个单词）。请查看我们的标记工具，了解有关文本如何转换为标记的更多信息。

## 模型

该API由一组具有不同能力和价格点的模型驱动。GPT-4是我们最新且功能最强大的模型。GPT-3.5-Turbo是ChatGPT的动力模型，专为会话格式进行了优化。要了解有关这些模型和我们提供的其他内容的更多信息，请访问我们的模型文档。


# Quick Start

OpenAI训练了最先进的语言模型，这些模型在理解和生成文本方面非常出色。我们的API提供了访问这些模型的途径，并可用于解决几乎任何涉及处理语言的任务。

在这个快速入门教程中，您将构建一个简单的示例应用程序。在此过程中，您将学习到使用API解决任何任务所需的关键概念和技术，包括：

* 内容生成
* 摘要
* 分类、归类和情感分析
* 数据抽取
* 翻译
* 还有许多其他任务！

## 介绍

完成终点是我们API的核心，提供了一个非常灵活和强大的简单接口。您可以将一些文本作为提示输入，API将返回一个文本完成，试图匹配您给出的任何指令或上下文。

> 提示：为一个冰淇淋店写一个标语。

> 完成：我们每一勺都带来微笑！

您可以将此视为非常先进的自动完成功能——模型处理您的文本提示，尝试预测最有可能出现的下一个内容。

## 从第一条指示开始

想象一下，您想创建一个宠物名字生成器。从零开始想出名字是很难的！

首先，您需要一个明确表明您想要什么的提示。让我们从一条指示开始。提交此提示以生成您的第一个完成。

> 建议一个马的名字。

不错！现在，尝试让您的指示更具体一些。

> 为一匹黑马建议一个名字。

正如您所看到的，将一个简单的形容词添加到我们的提示中会改变生成的完成。设计您的提示实质上是如何“编程”模型。

## Make your first request

To make your first request, send an authenticated request to the pets endpoint. This will create a `pet`, which is nice.

## Create pet.

<mark style="color:green;">`POST`</mark> `https://api.myapi.com/v1/pet`

Creates a new pet.

#### Request Body

| Name                                   | Type   | Description                           |
| -------------------------------------- | ------ | ------------------------------------- |
| name<mark style="color:red;">\*</mark> | string | The name of the pet                   |
| owner\_id                              | string | The `id` of the user who owns the pet |
| species                                | string | The species of the pet                |
| breed                                  | string | The breed of the pet                  |

{% tabs %}
{% tab title="200 Pet successfully created" %}

```javascript
{
    "name"="Wilson",
    "owner": {
        "id": "sha7891bikojbkreuy",
        "name": "Samuel Passet",
    "species": "Dog",}
    "breed": "Golden Retriever",
}
```

{% endtab %}

{% tab title="401 Permission denied" %}

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Good to know:** You can use the API Method block to fully document an API method. You can also sync your API blocks with an OpenAPI file or URL to auto-populate them.
{% endhint %}

Take a look at how you might call this method using our official libraries, or via `curl`:

{% tabs %}
{% tab title="curl" %}

```
curl https://api.myapi.com/v1/pet  
    -u YOUR_API_KEY:  
    -d name='Wilson'  
    -d species='dog'  
    -d owner_id='sha7891bikojbkreuy'  
```

{% endtab %}

{% tab title="Node" %}

```javascript
// require the myapi module and set it up with your API key
const myapi = require('myapi')(YOUR_API_KEY);

const newPet = away myapi.pet.create({
    name: 'Wilson',
    owner_id: 'sha7891bikojbkreuy',
    species: 'Dog',
    breed: 'Golden Retriever',
})
```

{% endtab %}

{% tab title="Python" %}

```python
// Set your API key before making the request
myapi.api_key = YOUR_API_KEY

myapi.Pet.create(
    name='Wilson',
    owner_id='sha7891bikojbkreuy',
    species='Dog',
    breed='Golden Retriever',
)
```

{% endtab %}
{% endtabs %}


# OpenAI API 参考文档

<mark style="color:red;">**这里推荐一个国内的ChatGpt工具可以不用翻墙免费使用：**</mark>[AI工具商店](http://gpt.luojixiangliang.com/gpt)

<figure><img src="https://1729651231-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FRTh9v8N3FcUxKqutlgfk%2Fuploads%2FJCV2kNOmlm7gjlohYj9h%2Fimage.png?alt=media&amp;token=d783aacb-bfed-4d82-85d3-e67c10afc408" alt=""><figcaption></figcaption></figure>

欢迎来到 OpenAI API 参考文档！本文档提供了 OpenAI API 的详细信息，包括 API 方法、参数、返回值等等。通过使用这些 API，您可以轻松地将 OpenAI 的自然语言处理技术集成到自己的应用中，从而提高应用的性能和质量。

### 快速入门

在开始使用 OpenAI API 之前，您需要先注册并获取 API 密钥。您可以在[此处](https://beta.openai.com/signup/)注册并获取 API 密钥。如果您已经拥有 API 密钥，可以在[此处](https://beta.openai.com/settings/api-keys)查看和管理您的 API 密钥。

### API 方法

本文档列出了所有可用的 OpenAI API 方法。每个 API 方法都有自己的使用说明和示例代码，以帮助您更好地理解和使用这些方法。以下是一些常用的 API 方法：

* `davinci`: 通过使用 Davinci 模型，生成高质量的自然语言文本，用于各种任务，例如文本摘要、机器翻译、文章创作等等。
* `curie`: 通过使用 Curie 模型，生成高质量的自然语言文本，用于各种任务，例如对话生成、文章生成等等。
* `babbage`: 通过使用 Babbage 模型，生成高质量的自然语言文本，用于各种任务，例如文本分类、情感分析等等。

### 参数

每个 API 方法都有自己的参数列表，您需要在调用 API 方法时提供这些参数。以下是一些常用的参数：

* `model`: 指定要使用的模型，例如 `davinci`、`curie` 或 `babbage`。
* `prompt`: 提供一个输入文本，用于生成自然语言输出。
* `temperature`: 控制输出文本的多样性。
* `max_tokens`: 控制输出文本的长度。

### 返回值

每个 API 方法都会返回一个 JSON 格式的对象，其中包含了生成的自然语言文本。返回值的具体格式和内容取决于 API 方法和参数。

### 常见问题

如果您在使用 OpenAI API 时遇到任何问题，请查看[常见问题](https://beta.openai.com/docs/faq/)。如果您仍然无法解决问题，请联系 OpenAI 支持团队获取帮助。

### 故障排除

如果您遇到任何故障，请查看[故障排除指南](https://beta.openai.com/docs/troubleshooting/)。该指南包含了一些常见问题的解决方法，可以帮助您快速解决问题。如果您仍然无法解决问题，请联系 OpenAI 支持团队获取帮助。

总之，OpenAI API 是一项强大而灵活的自然语言处理技术，可以帮助您轻松地实现各种自然语言处理任务。如果您需要进一步了解 OpenAI API 或者需要帮助使用 OpenAI API，请查看本文档并联系 OpenAI 支持团队获取帮助。


# 介绍

您可以透过HTTP请求从任何语言与API进行交互，使用我们官方的Python绑定、官方的Node.js库或社区维护的库。

若想安装官方的Python绑定，请执行以下指令：

```python
pip install openai
```

若想安装官方的Node.js库，请在Node.js项目目录中执行以下指令：

```javascript
npm install openai
```


# 认证

OpenAI API使用API密钥进行身份验证。请访问您的API密钥页面以检索您将在请求中使用的API密钥。

请记住，您的API密钥是保密的！不要与他人分享它，也不要在任何客户端代码（浏览器、应用程序）中公开它。生产请求必须通过您自己的后端服务器进行路由，其中您的API密钥可以从环境变量或密钥管理服务中安全加载。

所有API请求都应在Authorization HTTP头中包含您的API密钥，如下所示：

```javascript
Authorization: Bearer OPENAI_API_KEY
```


# 请求组织

对于属于多个组织的用户，您可以传递一个标头来指定用于API请求的组织。从这些API请求的使用情况将计入指定组织的订阅配额。

使用curl命令的示例：

```shell
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Organization: YOUR_ORG_ID"
```

使用OpenAI Python包的示例：

```python
import os
import openai
openai.organization = "YOUR_ORG_ID"
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.list()
```

使用OpenAI Node.js包的示例：

```javascript
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
    organization: "YOUR_ORG_ID",
    apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listEngines();
```

组织ID可以在您的组织设置页面上找到。


# 发出请求

您可以将以下命令粘贴到终端中，以运行您的第一个API请求。确保将$ OPENAI\_API\_KEY替换为您的秘密API密钥。

```sh
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'
```

此请求查询`gpt-3.5-turbo`模型以完成从“Say this is a test”开始的文本。您应该收到一个类似于以下内容的响应：

```json
{
   "id":"chatcmpl-abc123",
   "object":"chat.completion",
   "created":1677858242,
   "model":"gpt-3.5-turbo-0301",
   "usage":{
      "prompt_tokens":13,
      "completion_tokens":7,
      "total_tokens":20
   },
   "choices":[
      {
         "message":{
            "role":"assistant",
            "content":"\n\nThis is a test!"
         },
         "finish_reason":"stop",
         "index":0
      }
   ]
}
```

现在，您已经生成了您的第一个聊天完成。我们可以看到`finish_reason`是`stop`，这意味着API返回了模型生成的完整完成。在上面的请求中，我们只生成了一条消息，但您可以将n参数设置为生成多个消息选项。在此示例中，`gpt-3.5-turbo`被用于更传统的<mark style="color:green;">**文本完成任务**</mark>。该模型也经过了<mark style="color:green;">**聊天应用程序**</mark>的优化。


# 模型

列出并描述API中可用的各种模型。您可以参考模型文档以了解可用的模型及其之间的区别。

### 获取支持的模型列表

```html
GET https://api.openai.com/v1/models
```

列出当前可用的模型，并提供有关每个模型的基本信息，例如所有者和可用性。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.list()

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listModels();

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "data": [
    {
      "id": "model-id-0",
      "object": "model",
      "owned_by": "organization-owner",
      "permission": [...]
    },
    {
      "id": "model-id-1",
      "object": "model",
      "owned_by": "organization-owner",
      "permission": [...]
    },
    {
      "id": "model-id-2",
      "object": "model",
      "owned_by": "openai",
      "permission": [...]
    },
  ],
  "object": "list"
}

```

{% endcode %}

### 检索模型详细信息

```
GET https://api.openai.com/v1/models/{model}
```

检索模型实例，提供有关模型的基本信息，例如所有者和权限。

#### 路径参数

model 字符串 必需&#x20;

用于此请求的模型的ID。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/models/text-davinci-003 \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.retrieve("text-davinci-003")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.retrieveModel("text-davinci-003");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "text-davinci-003",
  "object": "model",
  "owned_by": "openai",
  "permission": [...]
}
```

{% endcode %}


# 问答

根据提示，模型将返回一个或多个预测答案，并且还可以在每个位置返回替代令牌的概率。

### 创建问答

```
POST https://api.openai.com/v1/completions
```

为提供的提示和参数创建一个问答。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "text-davinci-003",
    "prompt": "Say this is a test",
    "max_tokens": 7,
    "temperature": 0
  }'
```

{% endcode %}
{% endtab %}

{% tab title="python" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Completion.create(
  model="text-davinci-003",
  prompt="Say this is a test",
  max_tokens=7,
  temperature=0
)

```

{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
  model: "text-davinci-003",
  prompt: "Say this is a test",
  max_tokens: 7,
  temperature: 0,
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="参数" lineNumbers="true" %}

```json
{
  "model": "text-davinci-003",
  "prompt": "Say this is a test",
  "max_tokens": 7,
  "temperature": 0,
  "top_p": 1,
  "n": 1,
  "stream": false,
  "logprobs": null,
  "stop": "\n"
}
```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
  "object": "text_completion",
  "created": 1589478378,
  "model": "text-davinci-003",
  "choices": [
    {
      "text": "\n\nThis is indeed a test",
      "index": 0,
      "logprobs": null,
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 5,
    "completion_tokens": 7,
    "total_tokens": 12
  }
}

```

{% endcode %}

#### 请求主体

* model：字符串 必需 要使用的模型的ID。您可以使用List models API查看所有可用模型，或者查看我们的模型概述以获取它们的描述。
* prompt：字符串或数组 可选的 默认值<|endoftext|> 要生成完成的提示，可编码为字符串、字符串数组、令牌数组或令牌数组数组。注意：<|endoftext|>该符号是模型所看到的文档分隔符，因此如果未指定提示，模型将生成好像从新文档的开头开始一样。
* max\_tokens：整数 可选的 默认为16 完成中生成的最大令牌数。

  您的提示的令牌数加上max\_tokens不能超过模型的上下文长度。大多数模型的上下文长度为2048个令牌（除了最新的支持4096个令牌的模型）。
* temperature：数字 可选的 默认为1 使用的采样温度，介于0和2之间。较高的值（例如0.8）将使输出更随机，而较低的值（例如0.2）将使其更加集中和确定性。

  我们通常建议更改这个或top\_p，但不要同时更改两个。
* top\_p：数字 可选的 默认为1 与采用温度进行采样的另一种方法称为nucleus采样，其中模型考虑具有top\_p概率质量的令牌的结果。因此，0.1表示仅考虑组成前10％概率质量的令牌。

  我们通常建议更改这个或temperature，但不要同时更改两个。
* n：整数 可选的 默认为1 每个提示要生成多少个完成。

  注意：由于此参数生成许多完成，因此可能会快速消耗您的令牌配额。请谨慎使用，并确保您的max\_tokens和stop设置合理。
* stream： 布尔值 可选的 默认为false 是否返回部分进度的流。如果设置，令牌将作为只含数据的服务器推送事件发送，一旦可用，流将由数据：\[DONE]消息终止。
* logprobs： 整数 可选的 默认为null 包括logprobs最有可能的令牌的对数概率，以及选择的令牌。例如，如果logprobs是5，则API将返回最有可能的5个令牌的列表。API将始终返回采样令牌的logprob，因此响应中可能有多达logprobs + 1个元素。

  logprobs的最大值为5。如果您需要更多，请通过我们的帮助中心与我们联系，并描述您的用例。
* echo： 布尔值 可选的 默认为false 除了完成之外，还回显提示。
* stop： 字符串或数组 可选的 默认为null 最多4个序列，其中API将停止生成更多的令牌。返回的文本将不包含停止序列。
* presence\_penalty： 数字 可选的 默认为0 -2.0至2.0之间的数字。正值会根据令牌在迄今为止的文本中是否出现来惩罚新令牌，从而增加模型谈论新主题的可能性。
* frequency\_penalty： 数字 可选的 默认为0 -2.0至2.0之间的数字。正值会根据令牌在迄今为止的文本中的现有频率来惩罚新令牌，从而降低模型按原样重复相同行的可能性。
* best\_of： 整数 可选的 默认为1 在服务器端生成best\_of完成并返回“最佳”（每个令牌的对数概率最高的完成）。结果无法被流式传输。

  当与n一起使用时，best\_of控制候选完成的数量，n指定要返回多少个-best\_of必须大于n。

  注意：由于此参数生成许多完成，因此可能会快速消耗您的令牌配额。请谨慎使用，并确保您的max\_tokens和stop设置合理。
* logit\_bias： 映射 可选的 默认为null 修改完成中指定令牌出现的可能性。

  接受将令牌（由其在GPT分词器中的令牌ID指定）映射到从-100到100的相关偏差值的json对象。您可以使用此分词器工具（适用于GPT-2和GPT-3）将文本转换为令牌ID。在数学上，在采样之前，将偏差添加到模型生成的对数概率中。确切的效果
* user： 字符串 可选的 代表您的终端用户的唯一标识符，可帮助OpenAI监视和检测滥用。了解更多。


# 对话

根据聊天会话，模型将返回聊天完成响应。

### 创建聊天完成

```
POST https://api.openai.com/v1/chat/completions
```

为聊天消息创建完成

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")

completion = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "user", "content": "Hello!"}
  ]
)

print(completion.choices[0].message)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const completion = await openai.createChatCompletion({
  model: "gpt-3.5-turbo",
  messages: [{role: "user", content: "Hello world"}],
});
console.log(completion.data.choices[0].message);

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "model": "gpt-3.5-turbo",
  "messages": [{"role": "user", "content": "Hello!"}]
}
```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}
```

{% endcode %}

#### 请求主体

* model 字符串 必需 要使用的模型的ID。有关哪些模型适用于Chat API的详细信息，请参见模型端点兼容性表。
* messages 数组 必需 要为其生成聊天完成的
* temperature： 数字 可选的 默认为1 使用的采样温度，介于0和2之间。较高的值（例如0.8）将使输出更随机，而较低的值（例如0.2）将使其更加集中和确定性。

  我们通常建议更改这个或top\_p，但不要同时更改两个。
* top\_p： 数字 可选的 默认为1 与采用温度进行采样的另一种方法称为nucleus采样，其中模型考虑具有top\_p概率质量的令牌的结果。因此，0.1表示仅考虑组成前10％概率质量的令牌。

  我们通常建议更改这个或temperature，但不要同时更改两个。
* n： 整数 可选的 默认为1 为每个输入消息生成多少个聊天完成选项。
* stream： 布尔值 可选的 默认为false 如果设置，将发送部分消息增量，就像在ChatGPT中一样。令牌将作为只含数据的服务器推送事件发送，一旦可用，流将由数据：\[DONE]消息终止。请参见OpenAI Cookbook的示例代码。
* stop： 字符串或数组 可选的 默认为null 最多4个序列，其中API将停止生成更多的令牌。
* max\_tokens： 整数 可选的 默认为inf 在聊天完成中生成的最大令牌数。

  输入令牌和生成令牌的总长度受模型上下文长度的限制。
* presence\_penalty： 数字 可选的 默认为0 -2.0至2.0之间的数字。正值会根据令牌在迄今为止的文本中是否出现来惩罚新令牌，从而增加模型谈论新主题的可能性。
* frequency\_penalty： 数字 可选的 默认为0 -2.0至2.0之间的数字。正值会根据令牌在迄今为止的文本中的现有频率来惩罚新令牌，从而降低模型按原样重复相同行的可能性。
* logit\_bias： 映射 可选的 默认为null 修改完成中指定令牌出现的可能性。

  接受将令牌（由其在分词器中的令牌ID指定）映射到从-100到100的相关偏差值的json对象。在数学上，在采样之前，将偏差添加到模型生成的对数概率中。确切的效果将因模型而异，但值在-1和1之间应减少或增加选择的可能性；值如-100或100应导致禁止或独占选择相关令牌。
* user： 字符串 可选的 代表您的终端用户的唯一标识符，可帮助OpenAI监视和检测滥用。了解更多。


# 编辑

给定提示和指令，模型将返回提示的编辑版本。

### 创建编辑

```
POST https://api.openai.com/v1/edits
```

为提供的输入、指令和参数创建新的编辑。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/edits \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "text-davinci-edit-001",
    "input": "What day of the wek is it?",
    "instruction": "Fix the spelling mistakes"
  }'

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Edit.create(
  model="text-davinci-edit-001",
  input="What day of the wek is it?",
  instruction="Fix the spelling mistakes"
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createEdit({
  model: "text-davinci-edit-001",
  input: "What day of the wek is it?",
  instruction: "Fix the spelling mistakes",
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "model": "text-davinci-edit-001",
  "input": "What day of the wek is it?",
  "instruction": "Fix the spelling mistakes",
}

```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "object": "edit",
  "created": 1589478378,
  "choices": [
    {
      "text": "What day of the week is it?",
      "index": 0,
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 32,
    "total_tokens": 57
  }
}
json
```

{% endcode %}

#### 请求主体

* model 字符串 必需 要使用的模型的ID。您可以在此端点中使用text-davinci-edit-001或code-davinci-edit-001模型。
* input 字符串 可选的 默认为'' 用作编辑起点的输入文本。
* instruction 字符串 必需 告诉模型如何编辑提示的指令。
* n 整数 可选的 默认为1 要为输入和指令生成多少个编辑。
* temperature 数字 可选的 默认为1 使用的采样温度，介于0和2之间。较高的值（例如0.8）将使输出更随机，而较低的值（例如0.2）将使其更加集中和确定性。

  我们通常建议更改这个或top\_p，但不要同时更改两个。
* top\_p： 数字 可选的 默认为1 与采用温度进行采样的另一种方法称为nucleus采样，其中模型考虑具有top\_p概率质量的令牌的结果。因此，0.1表示仅考虑组成前10％概率质量的令牌。

  我们通常建议更改这个或temperature，但不要同时更改两个。


# 图片

给定提示和/或输入图片，模型将生成一个新图片。

### 生成图片

```
POST https://api.openai.com/v1/images/generations
```

给定提示创建图片。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "prompt": "A cute baby sea otter",
    "n": 2,
    "size": "1024x1024"
  }'
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Edit.create(
  model="text-davinci-edit-001",
  input="What day of the wek is it?",
  instruction="Fix the spelling mistakes"
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createEdit({
  model: "text-davinci-edit-001",
  input: "What day of the wek is it?",
  instruction: "Fix the spelling mistakes",
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "prompt": "A cute baby sea otter",
  "n": 2,
  "size": "1024x1024"
}
```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "created": 1589478378,
  "data": [
    {
      "url": "https://..."
    },
    {
      "url": "https://..."
    }
  ]
}
```

{% endcode %}

#### 请求主体

* prompt：字符串 必需 所需图像的文本描述。最大长度为1000个字符。
* n：整数 可选的 默认为1 要生成的图像数量。必须介于1和10之间。
* size：字符串 可选的 默认为1024x1024 生成的图像大小。必须是256x256、512x512或1024x1024之一。
* response\_format： 字符串 可选的 默认为url 返回生成图像的格式。必须是url或b64\_json之一。
* user： 字符串 可选的 代表您的终端用户的唯一标识符，可帮助OpenAI监视和检测滥用。了解更多。

### 图片编辑

```
POST https://api.openai.com/v1/images/edits
```

给定原始图像和提示，创建编辑或扩展的图像。

#### 请求主体

* image： 字符串 必需 要编辑的图像。必须是有效的PNG文件，小于4MB且为正方形。如果未提供mask，则图像必须具有透明度，该透明度将用作mask。
* mask： 字符串 可选的 另一个图像，其中完全透明的区域（例如alpha为零的区域）表明应该在哪里编辑图片。必须是有效的PNG文件，大小不超过4MB，且尺寸与图片相同。
* prompt： 字符串 必需 最多1000个字符的图像描述文本。
* n：整数 可选的 默认为1 要生成的图像数量。必须在1和10之间。
* size：字符串 可选的 默认为1024x1024 生成的图像大小。必须为256x256、512x512或1024x1024之一。
* response\_format：字符串 可选的 默认为url 生成的图像返回的格式。必须是url或b64\_json之一。
* user：字符串 可选的 表示您的最终用户的唯一标识符，可以帮助OpenAI监视和检测滥用。了解更多信息。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/images/edits \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F image="@otter.png" \
  -F mask="@mask.png" \
  -F prompt="A cute baby sea otter wearing a beret" \
  -F n=2 \
  -F size="1024x1024"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Image.create_edit(
  image=open("otter.png", "rb"),
  mask=open("mask.png", "rb"),
  prompt="A cute baby sea otter wearing a beret",
  n=2,
  size="1024x1024"
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createImageEdit(
  fs.createReadStream("otter.png"),
  fs.createReadStream("mask.png"),
  "A cute baby sea otter wearing a beret",
  2,
  "1024x1024"
);

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "created": 1589478378,
  "data": [
    {
      "url": "https://..."
    },
    {
      "url": "https://..."
    }
  ]
}

```

{% endcode %}

### 创建图片变体

```
POST https://api.openai.com/v1/images/variations
```

生成一个给定图像的变体。

#### 请求体

* image 字符串 必需的 作为变化基础的图像。必须是有效的PNG文件，小于4MB，且为正方形。
* n 整数 可选的 默认为1 生成图像的数量。必须介于1和10之间。
* size 字符串 可选的 默认为1024x1024 生成图像的尺寸。必须是256x256、512x512或1024x1024之一。
* response\_format 字符串 可选的 默认为url 生成的图像返回的格式。必须是url或b64\_json之一。
* user 字符串 可选的 表示您的最终用户的唯一标识符，可帮助OpenAI监测和检测滥用。了解更多。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/images/variations \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F image="@otter.png" \
  -F n=2 \
  -F size="1024x1024"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Image.create_variation(
  image=open("otter.png", "rb"),
  n=2,
  size="1024x1024"
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createImageVariation(
  fs.createReadStream("otter.png"),
  2,
  "1024x1024"
);

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "created": 1589478378,
  "data": [
    {
      "url": "https://..."
    },
    {
      "url": "https://..."
    }
  ]
}

```

{% endcode %}


# 嵌入向量

嵌入向量是指一种向量表示法，可以对给定的输入进行向量化处理，以便机器学习模型和算法更容易地使用。  相关指南：Embeddings

### 创建嵌入向量

```
POST https://api.openai.com/v1/embeddings
```

创建一个嵌入向量来表示输入的文本。

#### 请求体

* model 字符串 必填项 要使用的模型的ID。您可以使用“列出模型API”查看所有可用的模型，或查看我们的模型概述以获取它们的描述。
* input 字符串或数组 必填项 要为其获取嵌入的输入文本，编码为字符串或令牌数组的数组。要在单个请求中获取多个输入的嵌入，传递一个字符串数组或令牌数组的数组。每个输入的长度不能超过8192个令牌。
* user 字符串 可选项 代表您的最终用户的唯一标识符，可以帮助OpenAI监视和检测滥用。了解更多信息。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/embeddings \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "input": "The food was delicious and the waiter...",
    "model": "text-embedding-ada-002"
  }
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Embedding.create(
  model="text-embedding-ada-002",
  input="The food was delicious and the waiter..."
)
```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createEmbedding({
  model: "text-embedding-ada-002",
  input: "The food was delicious and the waiter...",
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "model": "text-embedding-ada-002",
  "input": "The food was delicious and the waiter..."
}

```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "embedding": [
        0.0023064255,
        -0.009327292,
        .... (1536 floats total for ada-002)
        -0.0028842222,
      ],
      "index": 0
    }
  ],
  "model": "text-embedding-ada-002",
  "usage": {
    "prompt_tokens": 8,
    "total_tokens": 8
  }
}

```

{% endcode %}


# 音频

学习如何将音频转换成文字。 相关指南：语音转文字。

### 创建转录

```
POST https://api.openai.com/v1/audio/transcriptions
```

将音频转录成输入语言。

#### 请求体

* file 字符串 必填项 要转录的音频文件，格式为：mp3、mp4、mpeg、mpga、m4a、wav或webm。
* model 字符串 必填项 要使用的模型ID。目前只有whisper-1可用。
* prompt 字符串 可选项 可选的文本，用于指导模型的风格或继续前一个音频片段。提示应与音频语言匹配。
* response\_format 字符串 可选项 默认为json 转录输出的格式，可选择以下选项之一：json、text、srt、verbose\_json或vtt。
* temperature 数字 可选项 默认为0 采样温度，介于0和1之间。较高的值（如0.8）将使输出更随机，而较低的值（如0.2）将使其更具有针对性和确定性。如果设置为0，模型将使用对数概率自动增加温度，直到达到一定的阈值。
* language 字符串 可选项 输入音频的语言。以ISO-639-1格式提供输入语言将提高准确性和延迟。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/audio/transcriptions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: multipart/form-data" \
  -F file="@/path/to/file/audio.mp3" \
  -F model="whisper-1"
```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
audio_file = open("audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const resp = await openai.createTranscription(
  fs.createReadStream("audio.mp3"),
  "whisper-1"
);

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "file": "audio.mp3",
  "model": "whisper-1"
}

```

{% endcode %}

{% code title="返回值" lineNumbers="true" %}

```json
{
  "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that."
}

```

{% endcode %}

### 创建翻译

```
POST https://api.openai.com/v1/audio/translations
```

将音频翻译成英语。

#### 请求体

* file 字符串 必填 需要翻译的音频文件，格式可以是以下之一：mp3，mp4，mpeg，mpga，m4a，wav或webm。
* model 字符串 必填 要使用的模型的ID。目前只有whisper-1可用。
* prompt 字符串 可选 可用于指导模型的风格或继续前一个音频片段的可选文本。提示应该是英文。
* response\_format 字符串 可选 默认为json 转录输出的格式，可以是以下选项之一：json，text，srt，verbose\_json或vtt。
* temperature 数字 可选 默认为0 采样温度，介于0和1之间。较高的值（如0.8）将使输出更加随机，而较低的值（如0.2）将使其更加集中和确定性。如果设置为0，模型将使用对数概率自动增加温度，直到达到某些阈值。


# 文件

文件用于上传文档，可与优化等功能一起使用。

### 列出文件

```
GET https://api.openai.com/v1/files
```

返回属于用户组织的文件列表。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.list()

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listFiles();

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回值" lineNumbers="true" %}

```json
{
  "data": [
    {
      "id": "file-ccdDZrC3iZVNiQVeEA6Z66wf",
      "object": "file",
      "bytes": 175,
      "created_at": 1613677385,
      "filename": "train.jsonl",
      "purpose": "search"
    },
    {
      "id": "file-XjGxS3KTG0uNmNOK362iJua3",
      "object": "file",
      "bytes": 140,
      "created_at": 1613779121,
      "filename": "puppy.jsonl",
      "purpose": "search"
    }
  ],
  "object": "list"
}

```

{% endcode %}

### 上传文件

```
POST https://api.openai.com/v1/files
```

上传包含文件的文档，以供在各个端点/功能中使用。目前，一个组织上传的所有文件的大小可以达到1 GB。如果您需要增加存储限制，请与我们联系。

#### 请求体

* file 字符串 必需的 要上传的JSON行文件的名称。

  如果目的是“微调”，每行都是一个JSON记录，具有“提示”和“完成”字段，表示您的训练示例。
* purpose 字符串 必需的 上传文档的预期目的。

  使用“微调”进行微调。这可以让我们验证上传文件的格式。

#### 请求示

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/files \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F purpose="fine-tune" \
  -F file="@mydata.jsonl"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.create(
  file=open("mydata.jsonl", "rb"),
  purpose='fine-tune'
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const fs = require("fs");
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createFile(
  fs.createReadStream("mydata.jsonl"),
  "fine-tune"
);
```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回值" lineNumbers="true" %}

```json
{
  "id": "file-XjGxS3KTG0uNmNOK362iJua3",
  "object": "file",
  "bytes": 140,
  "created_at": 1613779121,
  "filename": "mydata.jsonl",
  "purpose": "fine-tune"
}

```

{% endcode %}

### 删除文件

```
DELETE https://api.openai.com/v1/files/{file_id}
```

删除一个文件。

#### 路径参数

* file\_id 字符串 必填项 用于此请求的文件ID。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/files/file-XjGxS3KTG0uNmNOK362iJua3 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.delete("file-XjGxS3KTG0uNmNOK362iJua3")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.deleteFile("file-XjGxS3KTG0uNmNOK362iJua3");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回值" lineNumbers="true" %}

```json
{
  "id": "file-XjGxS3KTG0uNmNOK362iJua3",
  "object": "file",
  "deleted": true
}

```

{% endcode %}

### 检索文件

```
GET https://api.openai.com/v1/files/{file_id}
```

返回关于特定文件的信息。

#### 路径参数

* file\_id 字符串 必填项 用于此请求的文件ID。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/files/file-XjGxS3KTG0uNmNOK362iJua3 \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.retrieve("file-XjGxS3KTG0uNmNOK362iJua3")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.retrieveFile("file-XjGxS3KTG0uNmNOK362iJua3");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回值" lineNumbers="true" %}

```json
{
  "id": "file-XjGxS3KTG0uNmNOK362iJua3",
  "object": "file",
  "bytes": 140,
  "created_at": 1613779657,
  "filename": "mydata.jsonl",
  "purpose": "fine-tune"
}
```

{% endcode %}

### 检索文件内容

```
GET https://api.openai.com/v1/files/{file_id}/content
```

返回指定文件的内容

#### 路径参数

* file\_id 字符串 必需的 用于此请求的文件的 ID。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/files/file-XjGxS3KTG0uNmNOK362iJua3/content \
  -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
content = openai.File.download("file-XjGxS3KTG0uNmNOK362iJua3")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.downloadFile("file-XjGxS3KTG0uNmNOK362iJua3");

```

{% endcode %}
{% endtab %}
{% endtabs %}


# 优化模型

管理精细调整工作，以使模型适应您特定的训练数据。  相关指南：精细调整模型

### 创建优化任务

```
POST https://api.openai.com/v1/fine-tunes
```

创建一个任务，从给定的数据集中微调指定模型。

响应包括已入队的任务的详细信息，包括任务状态和完成后微调模型的名称。

了解更多关于微调的内容。

#### 请求体

* training\_file string 必填项 上传的包含训练数据的文件的ID。

  请参阅上传文件以了解如何上传文件。

  您的数据集必须格式化为JSONL文件，其中每个训练示例都是一个具有“prompt”和“completion”键的JSON对象。此外，您必须以微调目的上传文件。

  请参阅微调指南以获取更多详细信息。
* validation\_file string 可选项 上传的包含验证数据的文件的ID。

  如果提供此文件，则在微调过程中会定期使用该数据生成验证指标。这些指标可以在微调结果文件中查看。您的训练和验证数据应该是互斥的。

  您的数据集必须格式化为JSONL文件，其中每个验证示例都是一个具有“prompt”和“completion”键的JSON对象。此外，您必须以微调目的上传文件。

  请参阅微调指南以获取更多详细信息。
* model string 可选项 默认为curie 要微调的基础模型的名称。您可以选择其中之一：“ada”，“babbage”，“curie”，“davinci”或2022-04-21之后创建的微调模型。要了解有关这些模型的更多信息，请参阅模型文档。
* n\_epochs integer 可选项 默认为4 用于训练模型的时期数。时期是指完整遍历训练数据集的一个周期。
* batch\_size integer 可选项 默认为null 用于训练的批处理大小。批处理大小是用于训练单个前向和后向传递的训练示例的数量。默认情况下，批处理大小将动态配置为训练集中示例数的约0.2％，上限为256-通常，我们发现较大的批处理大小 tend to work better for larger datasets。
* learning\_rate\_multiplier number 可选项 默认为null 用于训练的学习率乘数。微调学习率是用于预训练的原始学习率乘以此值。

  默认情况下，学习率乘数为0.05、0.1或0.2，具体取决于最终批处理大小（较大的批处理大小 tend to perform better with larger batch sizes）。我们建议尝试0.02到0.2范围内的值，以查看哪些值可以产生最佳结果。
* prompt\_loss\_weight number 可选项 默认为0.01 用于提示令牌丢失的权重。这控制模型尝试学习生成提示的程度（与始终具有1.0权重的完成进行比较），并且可以在完成很短时为训练添加稳定效果。

  如果提示非常长（相对于完成），则可能有意义降低此权重，以避免过度优先考虑学习提示。
* compute\_classification\_metrics boolean 可选项 默认为false 如果设置，我们使用验证集在每个时期结束时计算分类特定的指标，例如准确性和F-1分数。这些指标可以在结果文件中查看。

  为了计算分类指标，您必须提供validation\_file。此外，您必须为多类分类指定classification\_n\_classes或为二元分类指定classification\_positive\_class。
* classification\_n\_classes integer 可选项 默认为null 分类任务中的类数。

  对于多类分类，此参数是必需的。
* classification\_positive\_class string 可选项 默认为null 二元分类中的正类。

  进行二元分类时，此参数需要生成精度、召回率和F1指标。
* classification\_betas array 可选项 默认为null 如果提供此项，则在指定的beta值上计算F-beta分数。F-beta分数是F-1分数的概括。仅用于二元分类。

  对于beta值为1（即F-1分数），精度和召回率具有相同的权重。较大的beta分数将更多的权重放在召回上，而较少的beta分数将更多的权重放在精度上。
* suffix string 可选项 默认为null 最多40个字符的字符串，将添加到您的微调模型名称中。

  例如，“custom-model-name”的后缀将产生类似ada:ft-your-org:custom-model-name-2022-02-15-04-21-04的模型名称。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/fine-tunes \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "training_file": "file-XGinujblHPwGLSztz8cPS8XY"
  }'

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.create(training_file="file-XGinujblHPwGLSztz8cPS8XY")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createFineTune({
  training_file: "file-XGinujblHPwGLSztz8cPS8XY",
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
  "object": "fine-tune",
  "model": "curie",
  "created_at": 1614807352,
  "events": [
    {
      "object": "fine-tune-event",
      "created_at": 1614807352,
      "level": "info",
      "message": "Job enqueued. Waiting for jobs ahead to complete. Queue number: 0."
    }
  ],
  "fine_tuned_model": null,
  "hyperparams": {
    "batch_size": 4,
    "learning_rate_multiplier": 0.1,
    "n_epochs": 4,
    "prompt_loss_weight": 0.1,
  },
  "organization_id": "org-...",
  "result_files": [],
  "status": "pending",
  "validation_files": [],
  "training_files": [
    {
      "id": "file-XGinujblHPwGLSztz8cPS8XY",
      "object": "file",
      "bytes": 1547276,
      "created_at": 1610062281,
      "filename": "my-data-train.jsonl",
      "purpose": "fine-tune-train"
    }
  ],
  "updated_at": 1614807352,
}

```

{% endcode %}

### 优化任务列表

```
GET https://api.openai.com/v1/fine-tunes
```

列出您组织的微调任务。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/fine-tunes \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.list()

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listFineTunes();

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "object": "list",
  "data": [
    {
      "id": "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
      "object": "fine-tune",
      "model": "curie",
      "created_at": 1614807352,
      "fine_tuned_model": null,
      "hyperparams": { ... },
      "organization_id": "org-...",
      "result_files": [],
      "status": "pending",
      "validation_files": [],
      "training_files": [ { ... } ],
      "updated_at": 1614807352,
    },
    { ... },
    { ... }
  ]
}

```

{% endcode %}

### 获取优化任务信息

```
GET https://api.openai.com/v1/fine-tunes/{fine_tune_id}
```

获取有关微调工作的信息。

了解更多关于微调的内容。

#### 路径参数

* fine\_tune\_id 字符串 必填项 微调作业的ID

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/fine-tunes/ft-AF1WoRqd3aJAHsqc9NY7iL8F \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.retrieve(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.retrieveFineTune("ft-AF1WoRqd3aJAHsqc9NY7iL8F");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "ft-AF1WoRqd3aJAHsqc9NY7iL8F",
  "object": "fine-tune",
  "model": "curie",
  "created_at": 1614807352,
  "events": [
    {
      "object": "fine-tune-event",
      "created_at": 1614807352,
      "level": "info",
      "message": "Job enqueued. Waiting for jobs ahead to complete. Queue number: 0."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807356,
      "level": "info",
      "message": "Job started."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807861,
      "level": "info",
      "message": "Uploaded snapshot: curie:ft-acmeco-2021-03-03-21-44-20."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807864,
      "level": "info",
      "message": "Uploaded result files: file-QQm6ZpqdNwAaVC3aSz5sWwLT."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807864,
      "level": "info",
      "message": "Job succeeded."
    }
  ],
  "fine_tuned_model": "curie:ft-acmeco-2021-03-03-21-44-20",
  "hyperparams": {
    "batch_size": 4,
    "learning_rate_multiplier": 0.1,
    "n_epochs": 4,
    "prompt_loss_weight": 0.1,
  },
  "organization_id": "org-...",
  "result_files": [
    {
      "id": "file-QQm6ZpqdNwAaVC3aSz5sWwLT",
      "object": "file",
      "bytes": 81509,
      "created_at": 1614807863,
      "filename": "compiled_results.csv",
      "purpose": "fine-tune-results"
    }
  ],
  "status": "succeeded",
  "validation_files": [],
  "training_files": [
    {
      "id": "file-XGinujblHPwGLSztz8cPS8XY",
      "object": "file",
      "bytes": 1547276,
      "created_at": 1610062281,
      "filename": "my-data-train.jsonl",
      "purpose": "fine-tune-train"
    }
  ],
  "updated_at": 1614807865,
}

```

{% endcode %}

### 取消优化任务

```
POST https://api.openai.com/v1/fine-tunes/{fine_tune_id}/cancel
```

立即取消微调作业。

#### 路径参数

* fine\_tune\_id 字符串 必填 要取消的fine-tune作业的ID

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/fine-tunes/ft-AF1WoRqd3aJAHsqc9NY7iL8F/cancel \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.cancel(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.cancelFineTune("ft-AF1WoRqd3aJAHsqc9NY7iL8F");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "ft-xhrpBbvVUzYGo8oUO1FY4nI7",
  "object": "fine-tune",
  "model": "curie",
  "created_at": 1614807770,
  "events": [ { ... } ],
  "fine_tuned_model": null,
  "hyperparams": { ... },
  "organization_id": "org-...",
  "result_files": [],
  "status": "cancelled",
  "validation_files": [],
  "training_files": [
    {
      "id": "file-XGinujblHPwGLSztz8cPS8XY",
      "object": "file",
      "bytes": 1547276,
      "created_at": 1610062281,
      "filename": "my-data-train.jsonl",
      "purpose": "fine-tune-train"
    }
  ],
  "updated_at": 1614807789,
}

```

{% endcode %}

### 获取优化任务事件状态

```
GET https://api.openai.com/v1/fine-tunes/{fine_tune_id}/events
```

获取优化任务的详细状态更新。

#### 路径参数

* fine\_tune\_id 字符串 必需的 获取事件的微调作业的ID。

#### 查询参数

* stream 布尔值 可选的 默认为false 是否为微调作业流式传输事件。如果设置为true，则事件将作为数据传输服务器推送事件随时可用。当作业完成（成功、取消或失败）时，流将以数据：\[DONE]消息终止。

  如果设置为false，则仅返回到目前为止生成的事件。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/fine-tunes/ft-AF1WoRqd3aJAHsqc9NY7iL8F/events \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.list_events(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listFineTuneEvents("ft-AF1WoRqd3aJAHsqc9NY7iL8F");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "object": "list",
  "data": [
    {
      "object": "fine-tune-event",
      "created_at": 1614807352,
      "level": "info",
      "message": "Job enqueued. Waiting for jobs ahead to complete. Queue number: 0."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807356,
      "level": "info",
      "message": "Job started."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807861,
      "level": "info",
      "message": "Uploaded snapshot: curie:ft-acmeco-2021-03-03-21-44-20."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807864,
      "level": "info",
      "message": "Uploaded result files: file-QQm6ZpqdNwAaVC3aSz5sWwLT."
    },
    {
      "object": "fine-tune-event",
      "created_at": 1614807864,
      "level": "info",
      "message": "Job succeeded."
    }
  ]
}

```

{% endcode %}

### 删除优化的模型

```
DELETE https://api.openai.com/v1/models/{model}
```

删除一个精调过的模型。您必须在组织中具有所有者角色。

#### 路径参数

* model 字符串 必填项 要删除的模型

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/models/curie:ft-acmeco-2021-03-03-21-44-20 \
  -X DELETE \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Model.delete("curie:ft-acmeco-2021-03-03-21-44-20")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.deleteModel('curie:ft-acmeco-2021-03-03-21-44-20');

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "curie:ft-acmeco-2021-03-03-21-44-20",
  "object": "model",
  "deleted": true
}

```

{% endcode %}


# 内容审核

根据输入的文本，输出模型是否将其分类为违反OpenAI内容政策。  相关指南：Moderations

### 创建内容审核

```
POST https://api.openai.com/v1/moderations
```

判断文本是否违反OpenAI的内容政策

#### 请求体

* input 字符串或数组 必填项 需要分类的输入文本
* model 字符串 可选的 默认为text-moderation-latest 有两个内容审核模型可用：text-moderation-stable和text-moderation-latest。默认设置为text-moderation-latest，这将随着时间的推移自动升级。这确保您始终使用我们最准确的模型。如果您使用text-moderation-stable，我们将提前通知您更新模型。text-moderation-stable的准确性可能略低于text-moderation-latest。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/moderations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "input": "I want to kill them."
  }'

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Moderation.create(
  input="I want to kill them.",
)

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createModeration({
  input: "I want to kill them.",
});

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="请求参数" lineNumbers="true" %}

```json
{
  "input": "I want to kill them."
}

```

{% endcode %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "modr-5MWoLO",
  "model": "text-moderation-001",
  "results": [
    {
      "categories": {
        "hate": false,
        "hate/threatening": true,
        "self-harm": false,
        "sexual": false,
        "sexual/minors": false,
        "violence": true,
        "violence/graphic": false
      },
      "category_scores": {
        "hate": 0.22714105248451233,
        "hate/threatening": 0.4132447838783264,
        "self-harm": 0.005232391878962517,
        "sexual": 0.01407341007143259,
        "sexual/minors": 0.0038522258400917053,
        "violence": 0.9223177433013916,
        "violence/graphic": 0.036865197122097015
      },
      "flagged": true
    }
  ]
}

```

{% endcode %}


# 引擎

获取API支持的各种引擎的信息

{% hint style="warning" %}
此接口已被废弃，请改用它们的替代品——模型。[了解更多](/reference/openai-api-can-kao-wen-dang/mo-xing)。
{% endhint %}

### 获取引擎列表

```
GET https://api.openai.com/v1/engines
```

列出当前可用（非优化）的模型，并提供每个模型的基本信息，例如所有者和可用性。

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/engines \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Engine.list()

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.listEngines();

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "data": [
    {
      "id": "engine-id-0",
      "object": "engine",
      "owner": "organization-owner",
      "ready": true
    },
    {
      "id": "engine-id-2",
      "object": "engine",
      "owner": "organization-owner",
      "ready": true
    },
    {
      "id": "engine-id-3",
      "object": "engine",
      "owner": "openai",
      "ready": false
    },
  ],
  "object": "list"
}

```

{% endcode %}

### 获取引擎详细信息

```
GET https://api.openai.com/v1/engines/{engine_id}
```

检索模型实例，提供基本信息，例如所有者和可用性。

#### 路径参数

* engine\_id 字符串 必填项 此请求使用的引擎的ID

#### 请求示例

{% tabs %}
{% tab title="curl" %}
{% code lineNumbers="true" %}

```sh
curl https://api.openai.com/v1/engines/text-davinci-003 \
  -H "Authorization: Bearer $OPENAI_API_KEY"

```

{% endcode %}
{% endtab %}

{% tab title="python" %}
{% code lineNumbers="true" %}

```python
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Engine.retrieve("text-davinci-003")

```

{% endcode %}
{% endtab %}

{% tab title="node.js" %}
{% code lineNumbers="true" %}

```javascript
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.retrieveEngine("text-davinci-003");

```

{% endcode %}
{% endtab %}
{% endtabs %}

{% code title="返回结果" lineNumbers="true" %}

```json
{
  "id": "text-davinci-003",
  "object": "engine",
  "owner": "openai",
  "ready": true
}

```

{% endcode %}


# 参数详情

频率和存在惩罚

在Completions API中发现的频率和存在惩罚可以用来减少采样重复标记序列的可能性。它们通过直接向logits（未归一化的对数概率）添加一个加法项来进行修改。

```
mu[j] -> mu[j] - c[j] * alpha_frequency - float(c[j] > 0) * alpha_presence
```

### 解释

* mu\[j]是第j个令牌的对数概率
* c\[j]是在当前位置之前抽样到该令牌的频率
* float(c\[j]>0)是如果c\[j]>0，则为1，否则为0
* alpha\_frequency是频率惩罚系数
* alpha\_presence是存在惩罚系数

正如我们所看到的，存在惩罚是一次性的加法贡献，适用于所有已经被抽样至少一次的令牌，而频率惩罚是与特定令牌已经被抽样的次数成比例的贡献。

对于惩罚系数的合理值约为0.1到1，如果目的仅是稍微减少重复抽样的话。如果目的是强烈抑制重复，则可以将系数增加到2，但这可能会显着降低抽样质量。负值可用于增加重复的可能性。


