跳转到内容

Chat ​

官方文档: https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create

Create chat completion ​

官方接口地址: POST https://api.openai.com/v1/chat/completions 对应Mishu接口地址: POST https://mishu.one/v1/chat/completions

----------------------------- ​

(注意: 下面只是部分翻译, 而且无法保证实时更新, 请时刻以openai官方文档为准)

Chat 聊天(部分翻译) ​

给定一组描述对话的消息列表,模型将返回一个回复。

1. Create chat completion ​

http
POST
https://mishu.one/v1/chat/completions

为给定的聊天对话创建模型响应。 Creates a model response for the given chat conversation.

请求演示:

http
curl https://mishu.one/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ]
  }'

响应:

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

Request body(入参详解)

  • messages (array,必填) 迄今为止描述对话的消息列表。 此参数比较复杂,为了便于理解,下面将分两种样式来描述,一种最简单的,一种最复杂的。

    最简单的如下:

    • role (string,必填) 此消息的作者角色。system 、user、assistant、tool、 或 function之一。也正是因为role可能有多种不同的角色,所以其参数也跟着会多很多,下面会在最复杂的情况下分别按不同的角色来描述。
    • content (string,必填) 消息的内容

    最复杂的如下:

    • System message object

      • role (string,必填) 消息作者的角色,在本例中为system.
      • content (string,必填) 消息的内容.
      • name (string,选填) 参与者的可选名称。提供模型信息以区分相同角色的参与者。
    • User message object

      • role (string,必填) 消息作者的角色,在本例中为user.
      • content (string or array,必填) 消息的内容.类型可能是string或array,下面分别描述
        • string类型 消息的文本内容。
        • array类型 具有已定义类型的内容部分的数组,传入图像时每个内容部分的类型可以是 text 或 image_url。您可以通过添加多个 image_url 内容部分来传递多个图像。仅当使用 gpt-4-visual-preview 模型时才支持图像输入。
          • Text content part object 如果是文本类型对象。
            • type (string,必填) 内容部分的类型。
            • text (string,必填) 文字内容。
          • Image content part object 如果是图片类型对象。
            • type (string,必填) 内容部分的类型。
            • image_url (object,必填)
              • url (object,必填) 图像的 URL 或 Base64 编码的图像数据。
              • detail (string,必填,Defaults to auto) 指定图像的细节级别。在愿景指南中了解更多信息。
      • name (string,选填) 参与者的可选名称。提供模型信息以区分相同角色的参与者。
    • Assistant message object

      • role (string,必填) 消息作者的角色,在本例中为assistant.
      • content (string or null,选填) 助理消息的内容。除非指定了 tool_calls 或 function_call,否则是必需的。
      • name (string,选填) 参与者的可选名称。提供模型信息以区分相同角色的参与者。
      • tool_calls (array,选填) 模型生成的工具调用,例如函数调用。
        • id (string,必填) 工具调用的 ID。
        • type (string,必填) 工具的类型。目前仅支持function 。
        • function (string,必填) 模型调用的函数。
          • name (string,必填) 要调用的函数的名称。
          • arguments (string,必填) 调用函数所用的参数,由模型以 JSON 格式生成。请注意,该模型并不总是生成有效的 JSON,并且可能会产生未由函数架构定义的参数。在调用函数之前验证代码中的参数。
      • function_call (已弃用,array,选填) 已弃用并由 tool_calls 取代。应调用的函数的名称和参数,由模型生成。
        • arguments (string,必填) 调用函数所用的参数,由模型以 JSON 格式生成。请注意,该模型并不总是生成有效的 JSON,并且可能会产生未由函数架构定义的参数。在调用函数之前验证代码中的参数。
        • name (string,必填) 要调用的函数的名称。
    • Tool message object

      • role (object,必填) 消息作者的角色,在本例中为tool.
      • content (object,必填) 消息的内容.
      • tool_call_id (object,必填) Tool call that this message is responding to.
    • Function message object

      • role (object,必填) 消息作者的角色,在本例中为function.
      • content (object,必填) 消息的内容.
      • name (object,必填) 要调用的函数的名称。
  • model (string,必填)

    要使用的模型ID。有关哪些模型适用于Chat API的详细信息,请查看 模型端点兼容性表

  • frequency_penalty (number,选填,Defaults to 0)

    介于-2.0和2.0之间的数字。正值会根据文本中新令牌的现有频率对其进行惩罚,从而降低模型重复相同行的可能性。

    请参阅有关频率和存在惩罚的更多信息

  • logit_bias (map,选填,Defaults to null)

    修改完成时指定标记出现的可能性。

    接受一个JSON对象,将标记(由分词器中的标记ID指定)映射到从 -100 到 100 的相关偏差值。在采样之前,模型生成的logits会加上这个偏差。确切的影响因模型而异,但是 -1 到 1 之间的值应该会减少或增加选择概率;像 -100 或 100 这样的值应该会导致相关标记被禁止或独占选择。

  • logprobs (number,选填,Defaults to 0)

    是否返回输出标记的对数概率。如果为 true,则返回消息内容中返回的每个输出标记的对数概率。此选项当前在 gpt-4-vision-preview 模型上不可用。

  • top_logprobs (number,选填,Defaults to 0)

    0 到 20 之间的整数,指定每个标记位置最有可能返回的标记数量,每个标记都有关联的对数概率。如果使用此参数,则 logprobs 必须设置为 true。

  • max_tokens (integer,选填,Defaults to inf)

    在聊天完成中生成的最大 tokens 数。

    输入令牌和生成的令牌的总长度受模型上下文长度的限制。

  • n (integer,选填,Defaults to 1)

    每个输入消息要生成多少聊天完成选项数

  • presence_penalty (number,选填,Defaults to 0)

    介于 -2.0 和 2.0 之间的数字。正值会根据它们是否出现在文本中迄今为止来惩罚新令牌,从而增加模型谈论新主题的可能性。

    请参阅有关频率和状态惩罚的更多信息

  • response_format (object,选填) 指定模型必须输出的格式的对象。与 GPT-4 Turbo 和所有比 gpt-3.5-turbo-1106 更新的 GPT-3.5 Turbo 型号兼容。 设置为 { "type": "json_object" } 启用 JSON 模式,这保证模型生成的消息是有效的 JSON。 重要提示:使用 JSON 模式时,您还必须通过系统或用户消息指示模型自行生成 JSON。如果没有这个,模型可能会生成无休止的空白流,直到生成达到令牌限制,从而导致长时间运行且看似“卡住”的请求。另请注意,如果 finish_reason="length",则消息内容可能会被部分截断,这表明生成超出了 max_tokens 或会话超出了最大上下文长度。 * type (string,选填,Defaults to text) 必须是 text 或 json_object 之一。

  • seed (integer,选填,Defaults to 1) 此功能处于测试阶段。如果指定,我们的系统将尽最大努力进行确定性采样,以便使用相同种子和参数的重复请求应返回相同的结果。不保证确定性,您应该参考system_fingerprint响应参数来监控后端的变化。

  • stop (string or array,选填,Defaults to null)

    最多生成4个序列,API将停止生成更多的标记。

  • stream (boolean,选填,Defaults to false)

    如果设置了,将发送部分消息增量,就像在 ChatGPT 中一样。令牌将作为数据 服务器推送事件 随着它们变得可用而被发送,流通过 data: [DONE] 消息终止。请参阅OpenAI Cookbook 以获取 示例代码。

  • temperature (number or null,选填,Defaults to 1)

    使用哪个采样温度,在 0和2之间。

    较高的值,如0.8会使输出更随机,而较低的值,如0.2会使其更加集中和确定性。

    我们通常建议修改这个(temperature )为 top_p 但两者不能同时存在,二选一。

  • top_p (number or null,选填,Defaults to 1)

    温度采样的替代方法称为核采样,其中模型考虑具有 top_p 概率质量的标记的结果。因此 0.1 意味着仅考虑包含前 10% 概率质量的标记。 我们通常建议更改此值或温度temperature,但不能同时更改两者。

  • tools (array,选填)

    模型可能调用的工具列表。目前,仅支持函数作为工具。使用它来提供模型可以为其生成 JSON 输入的函数列表。最多支持 128 个功能。

    • type (string,必填) 工具的类型。目前仅支持function 。
    • function (object,必填)
      • description (string,选填) 对函数功能的描述,模型使用它来选择何时以及如何调用该函数。
      • **name (string,必填) ** 要调用的函数的名称。必须是 a-z、A-Z、0-9,或包含下划线和破折号,最大长度为 64。
      • parameters (object,选填) 函数接受的参数,描述为 JSON Schema 对象。请参阅指南以获取示例,并参阅 JSON 架构参考以获取有关格式的文档。 省略parameters 定义了一个带有空参数列表的函数。
  • tool_choice (string or object,选填)

    控制模型调用哪个函数(如果有)。 none 表示模型不会调用函数而是生成消息。 auto 意味着模型可以在生成消息或调用函数之间进行选择。通过 {"type": "function", "function": {"name": "my_function"}} 指定特定函数会强制模型调用该函数。

    当不存在任何函数时,none 是默认值。如果存在函数,则 auto 是默认值。

    • **string **

      none 表示模型不会调用函数而是生成消息。 auto 意味着模型可以在生成消息或调用函数之间进行选择。

    • **object **

      指定模型应使用的工具。用于强制模型调用特定函数。

      • type (string,必填) 工具的类型。目前仅支持function。
      • function (object,必填) 工具的类型。目前仅支持function。
        • name (string,必填) 要调用的函数的名称。
  • user (string,选填)

    一个唯一的标识符,代表您的终端用户,可以帮助OpenAI监测和检测滥用。了解更多信息。

  • function_call (已弃用 string or object,选填)

    Deprecated in favor of tool_choice. 控制模型调用哪个函数(如果有)。 none 表示模型不会调用函数而是生成消息。 auto 意味着模型可以在生成消息或调用函数之间进行选择。通过 {"name": "my_function"} 指定特定函数会强制模型调用该函数。 当不存在任何函数时,none 是默认值。如果存在函数,则 auto 是默认值。

    • **string **

      none 表示模型不会调用函数而是生成消息。 auto 意味着模型可以在生成消息或调用函数之间进行选择。

    • **object **

      通过 {"name": "my_function"} 指定特定函数会强制模型调用该函数。 * name (string,必填) 要调用的函数的名称。

  • functions (已弃用 array,选填)

    Deprecated in favor of tools. 模型可以为其生成 JSON 输入的函数列表。

    • description (string,选填)

      对函数功能的描述,模型使用它来选择何时以及如何调用该函数。

    • name (string,必填)

      要调用的函数的名称。必须是 a-z、A-Z、0-9,或包含下划线和破折号,最大长度为 64。

    • parameters (object,选填)

      函数接受的参数,描述为 JSON Schema 对象。请参阅指南以获取示例,并参阅 JSON 架构参考以获取有关格式的文档。 省略parameters定义了一个带有空参数列表的函数。

示例0. default ​

python的:

js
from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ]
)

print(completion.choices[0].message)

node的:

js
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "gpt-3.5-turbo",
  });

  console.log(completion.choices[0]);
}

main();

返回:

js
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-3.5-turbo-0125",
  "system_fingerprint": "fp_44709d6fcb",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "\n\nHello there, how may I assist you today?",
    },
    "logprobs": null,
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 12,
    "total_tokens": 21
  }
}

示例1. image input ​

js
curl https://mishu.one/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4-vision-preview",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "What’s in this image?"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
            }
          }
        ]
      }
    ],
    "max_tokens": 300
  }'

python的:

js
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What’s in this image?"},
                {
                    "type": "image_url",
                    "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
                },
            ],
        }
    ],
    max_tokens=300,
)

print(response.choices[0])

node的:

js
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const response = await openai.chat.completions.create({
    model: "gpt-4-vision-preview",
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "What’s in this image?" },
          {
            type: "image_url",
            image_url:
              "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
          },
        ],
      },
    ],
  });
  console.log(response.choices[0]);
}
main();

示例2. streaming ​

js
curl https://mishu.one/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Hello!"
      }
    ],
    "stream": true
  }'

python的:

js
from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ],
  stream=True
)

for chunk in completion:
  print(chunk.choices[0].delta)

node的:

js
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
    ],
    stream: true,
  });

  for await (const chunk of completion) {
    console.log(chunk.choices[0].delta.content);
  }
}

main();

返回:

js
{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]}

{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}

....

{"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-3.5-turbo-0125", "system_fingerprint": "fp_44709d6fcb", "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]}

示例3. functions ​

js
curl https://mishu.one/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "user",
      "content": "What is the weather like in Boston?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}'

python的:

js
from openai import OpenAI
client = OpenAI()

tools = [
  {
    "type": "function",
    "function": {
      "name": "get_current_weather",
      "description": "Get the current weather in a given location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA",
          },
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["location"],
      },
    }
  }
]
messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]
completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=messages,
  tools=tools,
  tool_choice="auto"
)

print(completion)

node的:

js
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}];
  const tools = [
      {
        "type": "function",
        "function": {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA",
              },
              "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
          },
        }
      }
  ];

  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    messages: messages,
    tools: tools,
    tool_choice: "auto",
  });

  console.log(response);
}

main();

示例4. logprobs ​

js
curl https://mishu.one/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!"
      }
    ],
    "logprobs": true,
    "top_logprobs": 2
  }'

python的:

js
from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "user", "content": "Hello!"}
  ],
  logprobs=True,
  top_logprobs=2
)

print(completion.choices[0].message)
print(completion.choices[0].logprobs)

node的:

js
import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: "user", content: "Hello!" }],
    model: "gpt-3.5-turbo",
    logprobs: true,
    top_logprobs: 2,
  });

  console.log(completion.choices[0]);
}

main();

返回:

js
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1702685778,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "logprobs": {
        "content": [
          {
            "token": "Hello",
            "logprob": -0.31725305,
            "bytes": [72, 101, 108, 108, 111],
            "top_logprobs": [
              {
                "token": "Hello",
                "logprob": -0.31725305,
                "bytes": [72, 101, 108, 108, 111]
              },
              {
                "token": "Hi",
                "logprob": -1.3190403,
                "bytes": [72, 105]
              }
            ]
          },
          {
            "token": "!",
            "logprob": -0.02380986,
            "bytes": [
              33
            ],
            "top_logprobs": [
              {
                "token": "!",
                "logprob": -0.02380986,
                "bytes": [33]
              },
              {
                "token": " there",
                "logprob": -3.787621,
                "bytes": [32, 116, 104, 101, 114, 101]
              }
            ]
          },
          {
            "token": " How",
            "logprob": -0.000054669687,
            "bytes": [32, 72, 111, 119],
            "top_logprobs": [
              {
                "token": " How",
                "logprob": -0.000054669687,
                "bytes": [32, 72, 111, 119]
              },
              {
                "token": "<|end|>",
                "logprob": -10.953937,
                "bytes": null
              }
            ]
          },
          {
            "token": " can",
            "logprob": -0.015801601,
            "bytes": [32, 99, 97, 110],
            "top_logprobs": [
              {
                "token": " can",
                "logprob": -0.015801601,
                "bytes": [32, 99, 97, 110]
              },
              {
                "token": " may",
                "logprob": -4.161023,
                "bytes": [32, 109, 97, 121]
              }
            ]
          },
          {
            "token": " I",
            "logprob": -3.7697225e-6,
            "bytes": [
              32,
              73
            ],
            "top_logprobs": [
              {
                "token": " I",
                "logprob": -3.7697225e-6,
                "bytes": [32, 73]
              },
              {
                "token": " assist",
                "logprob": -13.596657,
                "bytes": [32, 97, 115, 115, 105, 115, 116]
              }
            ]
          },
          {
            "token": " assist",
            "logprob": -0.04571125,
            "bytes": [32, 97, 115, 115, 105, 115, 116],
            "top_logprobs": [
              {
                "token": " assist",
                "logprob": -0.04571125,
                "bytes": [32, 97, 115, 115, 105, 115, 116]
              },
              {
                "token": " help",
                "logprob": -3.1089056,
                "bytes": [32, 104, 101, 108, 112]
              }
            ]
          },
          {
            "token": " you",
            "logprob": -5.4385737e-6,
            "bytes": [32, 121, 111, 117],
            "top_logprobs": [
              {
                "token": " you",
                "logprob": -5.4385737e-6,
                "bytes": [32, 121, 111, 117]
              },
              {
                "token": " today",
                "logprob": -12.807695,
                "bytes": [32, 116, 111, 100, 97, 121]
              }
            ]
          },
          {
            "token": " today",
            "logprob": -0.0040071653,
            "bytes": [32, 116, 111, 100, 97, 121],
            "top_logprobs": [
              {
                "token": " today",
                "logprob": -0.0040071653,
                "bytes": [32, 116, 111, 100, 97, 121]
              },
              {
                "token": "?",
                "logprob": -5.5247097,
                "bytes": [63]
              }
            ]
          },
          {
            "token": "?",
            "logprob": -0.0008108172,
            "bytes": [63],
            "top_logprobs": [
              {
                "token": "?",
                "logprob": -0.0008108172,
                "bytes": [63]
              },
              {
                "token": "?\n",
                "logprob": -7.184561,
                "bytes": [63, 10]
              }
            ]
          }
        ]
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 9,
    "completion_tokens": 9,
    "total_tokens": 18
  },
  "system_fingerprint": null
}

Mishu · API 开发文档