如何用 Python 调用 OpenAI API?

用Python调用OpenAI 的API是非常简单的,因为chatGPT提供的有官方的Python包,安装方式:

pip install openai

安装后可以使用以下代码调用chatGPT的接口:

import openai

# 设置 API Key,申请地址:https://platform.openai.com/account/api-keys
openai.api_key = 'sk-你的密钥' 
# 实现接口函数
def get_completion(prompt, model="gpt-3.5-turbo", temperature=1):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

prompt = "你好,chatGPT"
response = get_completion(prompt)
print(response)
提示1:安装后除了Python开发,也可以直接使用 openai指令调用,有兴趣的可以在命令终端输入 openai -h查看使用帮助。
提示2:目前对国内普通用户来说,困难的是怎么注册账号,否则没有API KEY就没法调用API,但对程度员来说应该不是难事。另一个困难是,2023年3月后API也被限制访问了,你得会魔法解决访问问题。而且不幸的消息是最新注册的账号可能没有免费API额度,而又不能用国内的信用卡,这对很多小伙伴来说就难搞了。
提示3: 2023年3月1日API升级,增加了gpt-3.5-turbo模型,至此API和网页版同步,变的一样强大了(更智能,支持上下文和指定角色),而且收费也变以前的1/10 了。
提示4: 2023年3月14日API增加了gpt-4gpt-4-32k模型,至此API最大支持32768 tokens,生成超长内容不再是问题 ,但gpt-4很贵,而且不是谁都能申请到。
提示5:2023年6月13日API更新加了 gpt-3.5-turbo-16k 模型,这样普通接口的回调长度增加了4倍,另外增加了函数调用能力,也就是你可以在API上开发插件啦,比如联网调用最新的数据,调用自己的内部数据。

除了Python调用 , 也可以用命令行调用,如新建一个内容如下的chat.cmd放到windows目录,然后在系统环境变量中加上OPENAI_API_KEY配置你的密钥,就可以直接在命令行调用:

关于密钥的重要说明

注册账号后,需要在以下网址申请密钥:

OpenAI API​platform.openai.com/account/api-keys

另外要看看你的账号有没有余额:

https://platform.openai.com/account/usage​platform.openai.com/account/usage

Python调用API的简单示例:

最新gpt-3.5和gpt-4模型

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

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

print(completion.choices[0].message)

注意:这里指定了角色,system指定chatGPT的身份,user是用户发的内容,assistant是chatGPT回答的内容,把消息用这个顺序组合就实现了角色指定和上下文会话关联。

原3.0模型

import openai

# 设置 API Key
openai.api_key = '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'
# 设置组织
openai.organization = "org-731BUwkIVAz6b1eBzWDCOpnc"
# 请求模型
model_engine = "text-davinci-002"

prompt = "Hello, how are you today?"

completions = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

# 输出结果
message = completions.choices[0].text
print(message)

Python API

下面具体介绍Python的使用方法,并补充模型相关介绍。

模型接口

模型是chatGPT的灵魂,主要包括GPT-*Codex二大类,一类处理人类语言,一类处理计算机代码。

GPT-3模型可以理解并生成自然语言,包括4种主要的模型,Davinci最强,Ada最快。

LATEST MODELMAX REQUESTTRAINING DATA
text-davinci-0034,000 tokensUp to Jun 2021
text-curie-0012,048 tokensUp to Oct 2019
text-babbage-0012,048 tokensUp to Oct 2019
text-ada-0012,048 tokensUp to Oct 2019

Codex模型是GPT-3模型的后代,可以理解和生成代码。Codex模型的训练数据包含自然语言和来自GitHub的数十亿行公共代码,最精通Python,还精通包括JavaScript、Go、Perl、PHP、Ruby、Swift、TypeScript、SQL和Shell等十几种语言。

LATEST MODELMAX REQUESTTRAINING DATA
code-davinci-0028,000 tokensUp to Jun 2021
code-cushman-001Up to 2,048 tokens

注意:2023年3月1日更新增加了GPT-3.5模型,3月14日更新增加了GPT-4模型,最新模型如下:

新增模型的训练数据依然截止2021年,只是更智能,而且支持的内容更长:

GPT-4 模型

GPT-3.5模型最大支持4096 tokens,2023年6月13日开放的GPT-3.5的16K模型,最大支持16384 tokens,GPT-4模型支持8192 tokens,GPT-4-32K支持32768 tokens。

关于token可以理解为分词,但并不是简单的按单词划分,比如hello world,abcdefg一共19个字符,被分为6个token,分别是hello、world、,、abc、def、g,而汉字是使用unicode编码计算,差不多一个汉字占2个token

如果有兴趣,你可以访问以下页面测试token细节:

API Reference - OpenAI API​platform.openai.com/tokenizer

获取模型列表

openai.Model.list()

结果:

<OpenAIObject list at 0x2d08856a090> JSON: {
  "data": [
    {
      "created": 1649358449,
      "id": "babbage",
      "object": "model",
      "owned_by": "openai",
      "parent": null,
      "permission": [
        {
          "allow_create_engine": false,
          "allow_fine_tuning": false,
          "allow_logprobs": true,
          "allow_sampling": true,
          "allow_search_indices": false,
          "allow_view": true,
          "created": 1669085501,
          "group": null,
          "id": "modelperm-49FUp5v084tBB49tC4z8LPH5",
          "is_blocking": false,
          "object": "model_permission",
          "organization": "*"
        }
      ],
      "root": "babbage"
    },
    {
      "created": 1649357491,
      "id": "ada",
      "object": "model",
      "owned_by": "openai",
      "parent": null,
      "permission": [
        {
          "allow_create_engine": false,
          "allow_fine_tuning": false,
          "allow_logprobs": true,
          "allow_sampling": true,
          "allow_search_indices": false,
          "allow_view": true,
          "created": 1669087301,
          "group": null,
          "id": "modelperm-xTOEYvDZGN7UDnQ65VpzRRHz",
          "is_blocking": false,
          "object": "model_permission",
          "organization": "*"
        }
      ],
      "root": "ada"
    },
    {
      "created": 1649359874,
      "id": "davinci",
      "object": "model",
      "owned_by": "openai",
      "parent": null,
      "permission": [
        {
          "allow_create_engine": false,
          "allow_fine_tuning": false,
          "allow_logprobs": true,
          "allow_sampling": true,
          "allow_search_indices": false,
          "allow_view": true,
          "created": 1669066355,
          "group": null,
          "id": "modelperm-U6ZwlyAd0LyMk4rcMdz33Yc3",
          "is_blocking": false,
          "object": "model_permission",
          "organization": "*"
        }
      ],
      "root": "davinci"
    },
........
  ],
  "object": "list"
}

API的模型很多,对比网页版的模型看看:

{
 "models": [
        {
 "slug": "text-davinci-002-render-sha",
 "max_tokens": 4097,
 "title": "Turbo (Default for free users)",
 "description": "The standard ChatGPT model",
 "tags": [
 "not_concise"
            ]
        }
    ]
}

检索模型信息

openai.Model.retrieve("code-davinci-002")

结果:

<Model model id=code-davinci-002 at 0x2d08a533130> JSON: {
  "created": 1649880485,
  "id": "code-davinci-002",
  "object": "model",
  "owned_by": "openai",
  "parent": null,
  "permission": [
    {
      "allow_create_engine": false,
      "allow_fine_tuning": false,
      "allow_logprobs": true,
      "allow_sampling": true,
      "allow_search_indices": false,
      "allow_view": true,
      "created": 1675900441,
      "group": null,
      "id": "modelperm-R84J18EpoqsxtydS37J4fHX9",
      "is_blocking": false,
      "object": "model_permission",
      "organization": "*"
    }
  ],
  "root": "code-davinci-002"
}

信息处理

chatGPT对内容的处理主要包括三种:Text completionCode completionImage generation,分别针对文本、代码和图片

Completion

这是早期版本的核心功能,但升后后chat接口比这个更强,此接口不支持gpt-3.5和gpt-4模型,所以推荐使用后面的chat接口代替。

参数说明
参数类型说明
modelstring必填,指定功能模型
promptstring或array提示语
max_tokensinteger默认值16,The maximum number of tokens to generate in the completion.
temperaturenumber默认值1,采样精度,取值范围为0~2,较高的值(如0.8)将使输出更加随机,而较低的值(例如0.2)将使其更加相关
top_pnumber默认值1,采样精度的另一种表示方式,如0.1表示更相关的10%的内容,请不要和temperature同时使用(2选1)
ninteger默认值1,返回内容的条数
streamboolean默认值false,是否流式输出内容
echoboolean默认值false,是否回显prompt内容
stopstring或array默认值null,Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.

参数中max_tokens决定了返回内容的最大长度,主要模型支持的token上限是2048,而最新的模型支持4098。

# 文本处理,蠢的要死,没法用
completion = openai.Completion.create(
  model="text-davinci-003",
  prompt="你好,chatGPT",
  max_tokens=1024,
  temperature=0.5
)

# print(completion.choices[0].text)
# 代码处理,主要是换模型
# openai.Completion.create(
#   model="code-davinci-002",
#   prompt="访问chatGPT的接口?",
#   max_tokens=1920,
#   temperature=0
# )

chat

这是API中最最最最重要的接口,可以说是灵魂,所以,那么多接口其实都可以不关注,只关注这一个就能满足会话应用的需求。

2023年3月1日新增接口,使用的是最新的GPT-3.5模型和GPT-4模型,推荐使用,和网页版一至。

https://platform.openai.com/docs/api-reference/chat/create​platform.openai.com/docs/api-reference/chat/create

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

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

print(completion.choices[0].message)

注意此接口不支持早期模型,只能用gpt-3.5-turbo gpt-3.5-turbo-16kgpt-4gpt-4-32k 几个模型。

消息的角色只能为system、user、assistant和function,而且消息你可以只用user角色发,这样效果就和以前的一样。而使用system角色可以指定chatGPT的功能定位,在assistant中传chatGPT回答的消息就实现了上下文关联,需要注意的是不要超了token限制。

这个接口的参数如下:

参数类型必填默认值说明
modelstring要使用的模型的ID。可用模型:gpt-4, gpt-4-0613, gpt-4-32k, gpt-4-32k-0613, gpt-3.5-turbo, gpt-3.5-turbo-0613, gpt-3.5-turbo-16k, gpt-3.5-turbo-16k-0613
messagesarray包含迄今为止的对话消息的列表。示例Python代码
functionsarray模型可能为其生成JSON输入的函数列表。
function_callstring或objectnone/auto控制模型如何响应函数调用。"none"表示模型不调用函数,而是响应最终用户。"auto"表示模型可以在最终用户和调用函数之间选择。通过{"name": "my_function"}指定特定函数会强制模型调用该函数。当没有函数时,默认为"none"。当存在函数时,默认为"auto"。
temperaturenumber1使用的采样温度,介于0和2之间。较高的值(如0.8)会使输出更随机,而较低的值(如0.2)会使其更集中和确定性。一般建议只更改此参数或top_p参数中的一个。
top_pnumber1采用与温度不同的采样方式,称为核采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1表示仅考虑占前10%概率质量的令牌。一般建议只更改此参数或温度参数中的一个。
ninteger1每个输入消息要生成多少个聊天完成选项。
streambooleanfalse如果设置,将发送部分消息增量,例如在ChatGPT中。令牌将作为仅数据的服务器发送的事件发送,一旦可用,就会终止流,其中包含数据:[DONE]消息。示例Python代码
stopstring或arraynull最多4个序列,API将在其中停止生成进一步的令牌。
max_tokensintegerinf聊天完成中要生成的最大令牌数。输入令牌和生成的令牌的总长度受模型上下文长度的限制。统计令牌数量的示例Python代码
presence_penaltynumber0-2.0到2.0之间的数字。正值会根据新令牌是否出现在迄今为止的文本中对其进行惩罚,增加模型谈论新主题的可能性。有关频率和存在惩罚的更多信息
frequency_penaltynumber0-2.0到2.0之间的数字。正值会根据新令牌在迄今为止的文本中的现有频率对其进行惩罚,降低模型重复相同行的可能性。有关频率和存在惩罚的更多信息
logit_biasmapnull修改聊天完成中指定令牌出现的可能性。接受将令牌(由其在标记器中的令牌ID指定)映射到-100到100的相关偏差值的json对象。在数学上,偏差被添加到模型生成的logits之前进行采样。确切的效果因模型而异,但-1到1之间的值应该会减少或增加选择的可能性;像-100或100这样的值应该会导致相关令牌的禁止或独占选择。
userstring表示您的最终用户的唯一标识符,可帮助OpenAI监视和检测滥用。了解更多
messages参数类型必填说明
rolestring消息作者的角色。可以是system、user、assistant或function之一。
contentstring消息的内容。除了带有函数调用的assistant消息外,所有消息都需要content。
namestring此消息作者的名称。如果角色是function,则需要提供name,并且应该是content中响应的函数的名称。名称可以包含a-z、A-Z、0-9和下划线,最大长度为64个字符。
function_callobject要调用的函数的名称和参数,由模型生成。
functions参数类型必填说明
namestring要调用的函数的名称。必须为a-z、A-Z、0-9,或包含下划线和破折号,最大长度为64。
descriptionstring函数的描述。
parametersobject函数接受的参数,描述为JSON Schema对象。有关示例,请参考下文。

以上参数多数都是非必填项,主要是指定模型和消息,需要重点说明的是可选参数temperature和top_p,这二个是GPT模型中用于控制生成文本多样性的两个参数。推荐只选其中一个使用,要么用temperature,要么用top_p,另一个用默认值,不建议同时用。

temperature是一个介于0和2之间的数字,用于控制随机性。当temperature接近0时,生成的文本会变得非常确定和重复,而当temperature接近2时,生成的文本会变得更加随机和多样化。在实践中,temperature通常设置在0.7到1.0之间,以平衡文本的多样性和可读性。

top_p是一个介于0和1之间的数字,用于控制生成文本的多样性。它表示模型在考虑下一个词时,只考虑概率质量最高的前top_p个词。这种方法也被称为nucleus采样。当top_p接近1时,生成的文本会变得更加多样化,而当top_p接近0时,生成的文本会变得更加确定和重复。

在实践中,这两个参数通常用于平衡生成文本的多样性和可读性。如果需要生成更加多样化的文本,可以将temperature设置为较高的值或将top_p设置为较低的值。如果需要生成更加确定和可读性强的文本,可以将temperature设置为较低的值或将top_p设置为较高的值。

message 示例

聊天模型以消息列表作为输入,并返回模型生成的消息作为输出。虽然聊天格式旨在使多轮对话变得容易,但对于没有任何对话的单轮任务同样有用。

以下是一个API调用的示例:

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

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

print(completion.choices[0].message)
{
  "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas.",
  "role": "assistant"
}
# 响应
print(completion)
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas.",
        "role": "assistant"
      }
    }
  ],
  "created": 1687245755,
  "id": "chatcmpl-7TPz9ROgLbcxGQFsgkvseElFDxMay",
  "model": "gpt-3.5-turbo-0301",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 17,
    "prompt_tokens": 57,
    "total_tokens": 74
  }
}

主要输入是 messages 参数。messages 必须是一个消息对象数组,其中每个对象都有一个角色("system"、"user"或"assistant")和内容。对话可以只有一个消息或多个来回轮流的消息。

通常,对话以系统消息system开头,然后是用户user和助手assistant交替的消息。

系统消息system有助于设置助手assistant的行为。例如,您可以修改助手的个性或提供有关其在整个对话中应如何行事的具体说明。但是请注意,系统消息是可选的,如果没有系统消息,模型的行为可能类似于使用通用消息(例如"You are a helpful assistant.")。

用户消息user提供了助手要回应的请求或评论。助手消息assistant存储以前的助手响应,但也可以由您编写,以提供所需行为的示例。

包括对话历史记录在内是很重要的,当用户说明涉及到先前的消息时。在上面的示例中,用户的最后一个问题"Where was it played?"只有在先前关于2020年世界杯大赛的消息的情况下才有意义。由于模型没有记忆过去的请求,因此所有相关信息都必须作为每个请求的对话历史记录的一部分提供。如果对话无法适应模型的令牌限制,则需要以某种方式缩短它。

关于模型和令牌
最新模型描述最大令牌数训练数据
gpt-3.5-turbo最具能力的GPT-3.5模型,针对聊天进行了优化,成本仅为text-davinci-003的1/10。将在最新模型发布后2周更新。4,096个令牌截至2021年9月
gpt-3.5-turbo-16k具有标准gpt-3.5-turbo模型相同的功能,但上下文增加了4倍。16,384个令牌截至2021年9月
gpt-3.5-turbo-0613gpt-3.5-turbo的快照,包含函数调用数据,截至2023年6月13日。与gpt-3.5-turbo不同,此模型将不会接收更新,并在新版本发布后3个月后被弃用。4,096个令牌截至2021年9月
gpt-3.5-turbo-16k-0613gpt-3.5-turbo-16k的快照,截至2023年6月13日。与gpt-3.5-turbo-16k不同,此模型将不会接收更新,并在新版本发布后3个月后被弃用。16,384个令牌截至2021年9月

要模仿ChatGPT中看到的文本迭代返回的效果,请将 stream 参数设置为true

function 示例

2023年6月13日OpenAI更新了API,除了增加了16k的模型,另一个重大变化就是增加了function角色和相关参数

在API调用中,您可以向gpt-3.5-turbo-0613gpt-4-0613描述函数,并让模型智能地选择输出一个包含调用这些函数的参数的JSON对象。Chat Completions API不会调用函数;相反,模型会生成JSON,您可以在代码中使用该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调用
    例如,将“我的顶级客户是谁?”转换为get_customers(min_revenue:int,created_before:string,limit:int)并调用您的内部API
  • 从文本中提取结构化数据
    例如,定义一个名为extract_data(name:string,birthday:string)或sql_query(query:string)的函数
  • ...等等!

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

  1. 使用在“functions”参数中定义的一组函数和用户查询调用模型。
  2. 模型可以选择调用函数,如果是这样,内容将是符合您自定义模式的字符串化JSON对象(注意:模型可能会生成无效的JSON或幻想参数)。
  3. 在您的代码中将字符串解析为JSON,并在提供的参数存在的情况下调用您的函数。
  4. 通过将函数响应作为新消息附加,再次调用模型,并让模型将结果总结回用户。

您可以通过下面的示例来了解这些步骤的具体操作:

import openai
import json


# 示例虚拟函数返回天气信息
# 在生产环境中,这可以是您的后端API或外部API
def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather in a given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)


def run_conversation():
    # 步骤1:将交谈和可用函数发送到GPT
    messages = [{"role": "user", "content": "What's the weather like in Boston?"}]
    functions = [
        {
            "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"],
            },
        }
    ]
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo-0613",
        messages=messages,
        functions=functions,
        function_call="auto",  # auto is default, but we'll be explicit
    )
    response_message = response["choices"][0]["message"]

    # 步骤2:检查GPT是否想要调用一个函数
    if response_message.get("function_call"):
        # 步骤3:调用函数
        # 注意:JSON响应可能不总是有效的;一定要处理错误
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        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"),
        )

        # 步骤四:将函数调用和函数响应的信息发送给GPT。
        messages.append(response_message)  # extend conversation with assistant's reply
        messages.append(
            {
                "role": "function",
                "name": function_name,
                "content": function_response,
            }
        )  # extend conversation with function response
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo-0613",
            messages=messages,
        )  # get a new response from GPT where it can see the function response
        return second_response


print(run_conversation())
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "The current weather in Boston is 72 degrees Fahrenheit and sunny with windy conditions.",
        "role": "assistant"
      }
    }
  ],
  "created": 1687245796,
  "id": "chatcmpl-7TPzomGUSp7YJ6gwGRGbgJGvIHaLK",
  "model": "gpt-3.5-turbo-0613",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 16,
    "prompt_tokens": 72,
    "total_tokens": 88
  }
}

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

例如,如果您询问模型“找到波士顿本周末的天气,预订周六的两个晚餐,并更新我的日历”,并提供相应的查询函数,它可能会选择连续调用它们,只在最后创建一个面向用户的消息。

如果您想强制模型生成一个面向用户的消息,可以通过设置function_call:"none"来实现(如果没有提供函数,则不会调用函数)。

您可以在OpenAI cookbook中找到更多的函数调用示例:How to call functions with chat models

可以看到函数能力让chatGPT的API更加强大,我们不再需要微调训练模型,改为直接调用我们自己的函数,能更轻松实现个性化的能力,而且通过函数让API拥有了联网能力,变的无限可能。

Image

生成图像的接口,提供风景照片还行,如果是人物照片,那真是无法直视,惨不忍睹。重点提示:图像接口是网页版没有的功能,但要慎重使用,因为收费很贵,尺寸1024x1024像素的图一张收费0.02美元,大约人民币0.13元左右。

参数说明
参数说明
prompt图片描述,必填
n需要生成的图片数量,取值1-10,默认值1
size图片大小,取值只能为256x256、512x512、1024x1024,默认值1024x1024
response_format返回图片数据类型,取值url或b64_json,默认值url
# 图片生成
openai.Image.create(
  prompt="长河落日圆",
  n=2,
  size="1024x1024"
)
<OpenAIObject at 0x2d085be03b0> JSON: {
  "created": 1675931511,
  "data": [
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-731BUwkIVAz6b1eBzWDCOpnc/user-hpg2zKlWmHI7Bxzzbn6Cx8zN/img-ttjoN3wlnBnfzroprAfgSXdG.png?st=2023-02-09T07%3A31%3A50Z&se=2023-02-09T09%3A31%3A50Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-02-08T22%3A00%3A41Z&ske=2023-02-09T22%3A00%3A41Z&sks=b&skv=2021-08-06&sig=6SKKszN0MtDMoxKIYSifb8f8JDWVtBlakztIA3CuOTs%3D"
    },
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-731BUwkIVAz6b1eBzWDCOpnc/user-hpg2zKlWmHI7Bxzzbn6Cx8zN/img-SnGuU9lXaTUcDhmpyGZ7dT5r.png?st=2023-02-09T07%3A31%3A51Z&se=2023-02-09T09%3A31%3A51Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-02-08T22%3A00%3A41Z&ske=2023-02-09T22%3A00%3A41Z&sks=b&skv=2021-08-06&sig=Yhkybe2IZEKBWdHKtinYHwfgrdw8xTxRe83s/qEyO1M%3D"
    }
  ]
}

以下接口在进阶功能开发中很有用,但基础功能开发基本不需要用到,本文只提供HTTP请求地址和Python版示例。想看详细参数的,可以直接看官网文档:

https://platform.openai.com/docs/api-reference​platform.openai.com/docs/api-reference

注意:看官网文档时不要登录你的账号,不登录在国内还能访问,登录后就不在服务区了。

Create image edit

在给定原始图像和提示的情况下创建编辑或扩展图像。

POST https://api.openai.com/v1/images/edits
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"
)

Create image variation

创建给定图像的变体。

POST https://api.openai.com/v1/images/variations
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"
)

Create embeddings

Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.

POST https://api.openai.com/v1/embeddings
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..."
)

Files

Files are used to upload documents that can be used with features like Fine-tuning.

此接口可以上传自己的数据用来训练属于你的模型。

List files

GET https://api.openai.com/v1/files
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.list()

Upload file

POST https://api.openai.com/v1/files
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.create(
  file=open("mydata.jsonl", "rb"),
  purpose='fine-tune'
)

Delete file

DELETE https://api.openai.com/v1/files/{file_id}
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.delete("file-XjGxS3KTG0uNmNOK362iJua3")

Retrieve file

GET https://api.openai.com/v1/files/{file_id}
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.File.retrieve("file-XjGxS3KTG0uNmNOK362iJua3")

Retrieve file content

GET https://api.openai.com/v1/files/{file_id}/content
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
content = openai.File.download("file-XjGxS3KTG0uNmNOK362iJua3")

Fine-tunes

Manage fine-tuning jobs to tailor a model to your specific training data.

简单的说,用你自己的数据训练模型,需要先用文件接口上传数据。

Create fine-tune

POST https://api.openai.com/v1/fine-tunes
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.create(training_file="file-XGinujblHPwGLSztz8cPS8XY")

List fine-tunes

GET https://api.openai.com/v1/fine-tunes
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.list()

Retrieve fine-tune

GET https://api.openai.com/v1/fine-tunes/{fine_tune_id}
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.retrieve(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

Cancel fine-tune

POST https://api.openai.com/v1/fine-tunes/{fine_tune_id}/cancel
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.cancel(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

List fine-tune events

GET https://api.openai.com/v1/fine-tunes/{fine_tune_id}/events
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.FineTune.list_events(id="ft-AF1WoRqd3aJAHsqc9NY7iL8F")

Delete fine-tune model

DELETE https://api.openai.com/v1/models/{model}
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")

Create moderation

给定输入文本,如果模型将其分类为违反OpenAI的内容安全策略,则输出信息。

POST https://api.openai.com/v1/moderations
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Moderation.create(
  input="I want to kill them.",
)

Engines

注意:Engines接口即将弃用,所以,请用models模型接口代替。

List engines

GET https://api.openai.com/v1/engines
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Engine.list()

Retrieve engine

GET https://api.openai.com/v1/engines/{engine_id}
Python示例
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.Engine.retrieve("text-davinci-003")

其它API

以上介绍的API是官网文档写的很清楚的,但还有一些API官网没有公开文档,但很有用,比如查询余额、查询使用明细管理密钥等,这些API也是通过密钥调用的,这里也简单介绍几个:

余额查询

查询账号可用余额及有效期~

接口
GET https://api.openai.com/dashboard/billing/credit_grants
示例
curl --location 'https://api.openai.com/dashboard/billing/credit_grants' \
--header 'Authorization: Bearer sk-************'
结果
{
    "object": "credit_summary",
    "total_granted": 18.0,
    "total_used": 13.787460000000001,
    "total_available": 4.212539999999999,
    "grants": {
        "object": "list",
        "data": [
            {
                "object": "credit_grant",
                "id": "2965a2aa-6cd8-4c34-95f2-fbe0c4c8c24e",
                "grant_amount": 18.0,
                "used_amount": 13.787460000000001,
                "effective_at": 1676246400.0,
                "expires_at": 1685577600.0
            }
        ]
    }
}

使用情况

查询指定时间段内每类接口使用情况

接口
GET https://api.openai.com/dashboard/billing/usage?end_date=2023-03-01&start_date=2023-02-01
示例
curl --location 'https://api.openai.com/dashboard/billing/usage?end_date=2023-02-14&start_date=2023-02-13' \
--header 'Authorization: Bearer sk-******'
结果
{
    "object": "list",
    "daily_costs": [
        {
            "timestamp": 1676246400.0,
            "line_items": [
                {
                    "name": "Base",
                    "cost": 0.302
                },
                {
                    "name": "FT Training",
                    "cost": 0.0
                },
                {
                    "name": "FT Inference",
                    "cost": 0.0
                },
                {
                    "name": "Embeddings",
                    "cost": 0.0
                },
                {
                    "name": "DALL-E API",
                    "cost": 0.0
                }
            ]
        }
    ],
    "total_usage": 0.302
}

使用明细

查询指定日期接口使用明细

接口
GET https://api.openai.com/v1/usage?date=2023-02-18
示例
curl --location 'https://api.openai.com/v1/usage?date=2023-02-14' \
--header 'authorization: Bearer sess-*******'
结果
{
    "object": "list",
    "data": [
        {
            "aggregation_timestamp": 1676361300,
            "n_requests": 3,
            "operation": "completion",
            "snapshot_id": "davinci:2020-05-03",
            "n_context": 3,
            "n_context_tokens_total": 53,
            "n_generated": 3,
            "n_generated_tokens_total": 2117
        },
        {
            "aggregation_timestamp": 1676367300,
            "n_requests": 2,
            "operation": "completion",
            "snapshot_id": "text-davinci-002",
            "n_context": 2,
            "n_context_tokens_total": 46,
            "n_generated": 2,
            "n_generated_tokens_total": 2046
        },

        {
            "aggregation_timestamp": 1676367900,
            "n_requests": 1,
            "operation": "completion",
            "snapshot_id": "text-davinci-003",
            "n_context": 1,
            "n_context_tokens_total": 23,
            "n_generated": 1,
            "n_generated_tokens_total": 1023
        }
    ],
    "ft_data": [],
    "dalle_api_data": [],
    "current_usage_usd": 0.0
}

更多账号管理的API如果有兴趣可以看以下内容:

雪风:chatGPT余额查询及密钥管理相关API介绍0 赞同 · 0 评论文章

收费说明

使用API接口是要收费的,具体收费简单说明一下,API调用是分功能的,不同功能使用了不同的接口,不同的接口有不同的收费标准,主要功能接口API调用收费如下:

GPT-4

GPT-3.5

2023年6月更新

绘画

音频

总的来说,GPT-3.5是最推荐的接口,便宜又好用,1千个token大约0.013元,而GPT-4是土豪才用的起的。

  • 24
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴躁的秋秋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值