OpenAI 大模型应用实践-Chat Completions API使用

494 阅读1分钟

参考文档 platform.openai.com/docs/guides…

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.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?"}
  ]
)

一个 Chat Completions API 响应示例如下:

  • 其中包括token的计数
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The 2020 World Series was played in Texas at Globe Life Field in Arlington.",
        "role": "assistant"
      },
      "logprobs": null
    }
  ],
  "created": 1677664795,
  "id": "chatcmpl-7QyqpwdfhqwajicIEznoc6Q47XAyW",
  "model": "gpt-3.5-turbo-0613",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 17,
    "prompt_tokens": 57,
    "total_tokens": 74
  }
}

返回的choices 是一个队列的形式

参数解释 每个响应都包含一个 reason:

  • stop: API returned complete message, or a message terminated by one of the stop sequences provided via the stop parameter
  • Stop: API 返回完整的消息,或者通过 stop 参数提供的某个停止序列终止的消息
  • length: Incomplete model output due to max_tokens parameter or token limit
  • Length: 由于 max _ tokens 参数或令牌限制而导致的不完整模型输出
  • function_call: The model decided to call a function
  • Function _ call: 模型决定调用函数
  • content_filter: Omitted content due to a flag from our content filters
  • Content _ filter: 由于内容过滤器的标志而省略的内容
  • null: API response still in progress or incomplete
  • Null: API 响应仍在进行中或不完整