ChatGPT API 接入指南

1,109 阅读3分钟

前言

因缘际会,参加了一个公司内部的AI应用场景创新超能力比赛,即设计一个智能产品,旨在提高业务的处理效率,减少人力成本,解决业务痛点问题,实现科技赋能业务。

笔者在团队内部被委任调研文案、图片等生成的开源项目, 要求能通过开放的API,进行少量的数据训练,并产出结果。

多方比对之后,ChatGPT脱颖而出,满足文案、图片的生成,支持对模型的微调。在阅读完官方文档和参考互联网上的案例之后,经过一番折腾,终于完成了技术验证。 此处笔者以ChatGPT聊天接口为例,尽量写一个简洁的ChatGPT API接入指南,以备查阅。

一、接入准备和了解

  1. 注册OPENAPI(亦或找朋友借个OPEN_API_KEY),此项必须
  2. openapi官网
  3. Chat 价格

ChatGPT models are optimized for dialogue. The performance of gpt-3.5-turbo is on par with Instruct Davinci.
机译:ChatGPT模型对对话进行了优化。gpt-3.5-turbo的性能与Instruct Davinci相当。

image.png

二、 接入方式

说明: 所有案例中 content 字段为录入的问题,可自行替换。

2.1 python SDK

2.1.1 环境准备

  1. python安装版本>=3.9, 官网下载
  2. openai 依赖包安装
# 安装
pip install openai

# openapi 版本查询
pip show openai

#查看版本

2.1.2 代码实现

  1. 官方案例
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)

  1. 简单聊天案例
import openai

openai.api_key = 'OPEN_API_KEY'
messages = [ {"role": "system", "content":"You are a intelligent assistant."} ]


while True:
    message = input("User : ")
    if message:
        messages.append(
            {"role": "user", "content": message},
        )
        chat = openai.ChatCompletion.create(
            model="gpt-3.5-turbo", messages=messages
        )
    reply = chat.choices[0].message.content
    print(f"ChatGPT: {reply}")
    messages.append({"role": "assistant", "content": reply})

2.2 URL

注意事项:

  • Authorization 的value值为Bearer $OPENAI_API_KEY
  • $OPENAI_API_KEY字符串替换为自己的key,即保留Bearer和空格

2.2.1 curl

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!"}]
  }'

2.2.2 postman工具

  1. 方法
post https://api.openai.com/v1/chat/completions
  1. 报文头
Content-Type:application/json
Authorization:Bearer OPEN_API_KEY

image.png

  1. 报文体
{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "who are you!"}]
}

image.png

2.2.3 http

快用自己喜欢或熟悉的语言来实现吧。

三、 问题及解决方法

  • urllib3 v2.0 only supports OpenSSL 1.1.1+
# 升级版本
pip install urllib3==1.26.6 

stackoverflow参考连接

CODEOVERVIEW
401 - Invalid AuthenticationCause:  Invalid Authentication Solution:  Ensure the correct API key and requesting organization are being used.
401 - Incorrect API key providedCause:  The requesting API key is not correct. Solution:  Ensure the API key used is correct, clear your browser cache, or generate a new one.
401 - You must be a member of an organization to use the APICause:  Your account is not part of an organization. Solution:  Contact us to get added to a new organization or ask your organization manager to invite you to an organization.
429 - Rate limit reached for requestsCause:  You are sending requests too quickly. Solution:  Pace your requests. Read the Rate limit guide.
429 - You exceeded your current quota, please check your plan and billing detailsCause:  You have hit your maximum monthly spend (hard limit) which you can view in the account billing section. Solution:  Apply for a quota increase.
429 - The engine is currently overloaded, please try again laterCause:  Our servers are experiencing high traffic. Solution:  Please retry your requests after a brief wait.
500 - The server had an error while processing your requestCause:  Issue on our servers. Solution:  Retry your request after a brief wait and contact us if the issue persists. Check the status page.
TYPEOVERVIEW
APIErrorCause:  Issue on our side. Solution:  Retry your request after a brief wait and contact us if the issue persists.
TimeoutCause:  Request timed out. Solution:  Retry your request after a brief wait and contact us if the issue persists.
RateLimitErrorCause:  You have hit your assigned rate limit. Solution:  Pace your requests. Read more in our Rate limit guide.
APIConnectionErrorCause:  Issue connecting to our services. Solution:  Check your network settings, proxy configuration, SSL certificates, or firewall rules.
InvalidRequestErrorCause:  Your request was malformed or missing some required parameters, such as a token or an input. Solution:  The error message should advise you on the specific error made. Check the documentation for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data.
AuthenticationErrorCause:  Your API key or token was invalid, expired, or revoked. Solution:  Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard.
ServiceUnavailableErrorCause:  Issue on our servers. Solution:  Retry your request after a brief wait and contact us if the issue persists. Check the status page.