【OpenAI API】Chat

Chat

Given a chat conversation, the model will return a chat completion response.

例子

請(qǐng)求

curl

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

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)

Node

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);

響應(yīng)

{
  "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
  }
}

Create chat completion

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

Creates a completion for the chat message

Request body

model

  • string
  • Required

ID of the model to use. Currently, only gpt-3.5-turbo and gpt-3.5-turbo-0301 are supported.

messages

  • array
  • Required

The messages to generate chat completions for, in the chat format.

聊天模型將一系列的消息作為輸入,并返回一個(gè)由模型生成的消息作為輸出。

盡管聊天格式的設(shè)計(jì)旨在使多輪對(duì)話容易進(jìn)行,但它同樣適用于沒(méi)有任何對(duì)話的單輪任務(wù)(例如以前由指令跟隨模型(如text-davinci-003)服務(wù)的任務(wù))。

Input format

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai

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?"}
    ]
)

系統(tǒng)消息有助于設(shè)置助手的行為。在上面的例子中,助手被指示為"You are a helpful assistant."(“你是一個(gè)有用的助手”)。

消息必須是消息對(duì)象的數(shù)組,其中每個(gè)對(duì)象都有角色(可以是“系統(tǒng)”、“用戶”或“助手”)和內(nèi)容(消息內(nèi)容)。對(duì)話可能很短,僅有1條消息,也可能填滿很多頁(yè)面。

一般情況下,對(duì)話的格式是先顯示系統(tǒng)消息,然后是用戶和助手的交替消息。

系統(tǒng)消息有助于設(shè)置助手的行為方式。在上面的示例中,使用“你是一個(gè)有用的助手”進(jìn)行指導(dǎo)。

gpt-3.5-turbo-0301 并不總是對(duì)系統(tǒng)消息給予足夠的關(guān)注。未來(lái)的模型將會(huì)接受更強(qiáng)的訓(xùn)練來(lái)關(guān)注系統(tǒng)消息。

用戶信息有助于指導(dǎo)助手。它們可以由應(yīng)用程序的最終用戶生成,也可以由開發(fā)人員設(shè)置為指導(dǎo)。

助手信息有助于存儲(chǔ)先前的回復(fù)。它們也可以由開發(fā)人員編寫,以幫助給出所需行為的示例。

包括對(duì)話歷史記錄有助于用戶指令涉及先前的消息時(shí)。在上面的例子中,“它是在哪里播放的?”用戶的最終問(wèn)題只有在2020年世界大賽的先前消息的背景下才有意義。由于模型沒(méi)有記錄過(guò)去的請(qǐng)求,所有相關(guān)信息必須通過(guò)對(duì)話提供。如果對(duì)話不能適應(yīng)模型的令牌限制,它將需要以某種方式縮短。

Response format

An example API response looks as follows:

{
 'id': 'chatcmpl-6p9XYPYSTTRi0xEviKjjilqrWU2Ve',
 'object': 'chat.completion',
 'created': 1677649420,
 'model': 'gpt-3.5-turbo',
 'usage': {'prompt_tokens': 56, 'completion_tokens': 31, 'total_tokens': 87},
 'choices': [
   {
    'message': {
      'role': 'assistant',
      'content': 'The 2020 World Series was played in Arlington, Texas at the Globe Life Field, which was the new home stadium for the Texas Rangers.'},
    'finish_reason': 'stop',
    'index': 0
   }
  ]
}

在Python中,助手的回復(fù)可以使用 response['choices'][0]['message']['content'] 來(lái)提取。

每個(gè)回復(fù)都會(huì)包括一個(gè) finish_reason。finish_reason的可能值如下:

  • stop: API返回完整的模型輸出
  • length: 由于max_tokens參數(shù)或標(biāo)記限制而導(dǎo)致模型輸出不完整
  • content_filter: 由于我們內(nèi)容過(guò)濾器中的一個(gè)標(biāo)志而省略的內(nèi)容
  • null: API響應(yīng)仍在進(jìn)行或不完整

temperature

  • number
  • Optional
  • Defaults to 1

采樣溫度在0和2之間,應(yīng)選擇何種值?像0.8這樣較高的值會(huì)使輸出更加隨機(jī),而較低的值,例如0.2,則會(huì)使其更加集中和確定性。

我們通常建議更改此值或 top_p,但不要同時(shí)更改兩個(gè)值。

top_p

  • number
  • Optional
  • Defaults to 1

一種替代使用溫度進(jìn)行取樣的方法叫做"核心取樣"(nucleus sampling),在這種方法中,模型只考慮具有 top_p 概率質(zhì)量的令牌的結(jié)果。例如,當(dāng) top_p 設(shè)置為 0.1 時(shí),意味著只有占前 10% 概率質(zhì)量的令牌被考慮。

我們通常建議只改變這兩種方法中的一種,而不是同時(shí)改變兩種。

n

  • integer
  • Optional
  • Defaults to 1

為每條輸入消息生成多少條聊天選項(xiàng)。

stream

  • boolean
  • Optional
  • Defaults to false

如果設(shè)置了,將會(huì)發(fā)送部分消息增量,就像 ChatGPT 一樣。令牌將作為僅數(shù)據(jù)的服務(wù)器推送事件在可用時(shí)發(fā)送,通過(guò)數(shù)據(jù):[DONE] 消息終止流。

stop

  • string or array
  • Optional
  • Defaults to null

API 最多生成4個(gè)序列,將停止生成的令牌。

max_tokens

  • integer
  • Optional
  • Defaults to inf

生成的答案允許的最大令牌數(shù)。默認(rèn)情況下,模型可以返回的令牌數(shù)為(4096-提示令牌數(shù))。

presence_penalty

  • number
  • Optional
  • Defaults to 0

-2.0和2.0之間的數(shù)字。正數(shù)懲罰基于在文本中出現(xiàn)的新標(biāo)記,增加模型談?wù)撔轮黝}的可能性。

請(qǐng)參閱有關(guān)頻率和存在懲罰的更多信息。

frequency_penalty

  • number
  • Optional
  • Defaults to 0

在-2.0和2.0之間的數(shù)字。正值會(huì)根據(jù)單詞在文本中的現(xiàn)有頻率對(duì)新單詞進(jìn)行懲罰,降低模型重復(fù)完全相同語(yǔ)句的可能性。

See more information about frequency and presence penalties.

logit_bias

  • map
  • Optional
  • Defaults to null

修改完成時(shí)特定標(biāo)記出現(xiàn)的可能性。

接受一個(gè)json對(duì)象,將標(biāo)記(通過(guò)標(biāo)記器中的標(biāo)記ID指定)映射到從-100到100的相關(guān)偏差值。數(shù)學(xué)上,在采樣之前,模型生成的logits會(huì)增加偏差。具體效果因模型而異,但-1到1之間的值應(yīng)該會(huì)降低或增加選擇的可能性;像-100或100這樣的值應(yīng)該會(huì)導(dǎo)致相關(guān)標(biāo)記被禁止或者是唯一的選擇。

user

  • string
  • Optional

A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. Learn more

End-user IDs

在您的請(qǐng)求中發(fā)送最終用戶 ID 可能是一個(gè)有用的工具,幫助 OpenAI 監(jiān)測(cè)和檢測(cè)濫用。這使得 OpenAI 可以在我們檢測(cè)到您的應(yīng)用程序中有任何政策違規(guī)時(shí),向您的團(tuán)隊(duì)提供更具操作性的反饋。

這些 ID 應(yīng)該是一個(gè)能唯一標(biāo)識(shí)每個(gè)用戶的字符串。我們建議對(duì)他們的用戶名或電子郵件地址進(jìn)行哈希處理,以避免向我們發(fā)送任何識(shí)別信息。如果您向非登錄用戶提供產(chǎn)品預(yù)覽,您可以發(fā)送會(huì)話 ID。

您可以通過(guò) user 參數(shù)在您的 API 請(qǐng)求中包含最終用戶 ID,如下所示:

curl https://api.openai.com/v1/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
  "model": "text-davinci-003",
  "prompt": "This is a test",
  "max_tokens": 5,
  "user": "user123456"
}'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容