ChatGPT 3.5 API的调用不全指南(持续更新ing...)

诸神缄默不语-个人CSDN博文目录

最近更新时间:2023.6.2
最早更新时间:2023.5.17

关于怎么才能上ChatGPT、怎么才能获取API额度等等信息,建议直接见我的medium账号。
因为这不是能在内网发的内容。
本文不涉及相关网络问题。

我本来想靠问ChatGPT来做的,然后发现ChatGPT给我讲的代码也过时了……
这种时候果然还是得靠自己啊!
OpenAI官网上给的好多示例代码也是过期代码,是不是很无语,就是很无语

为什么不写GPT-4:因为我还在排队列表里,我还没排到API。

openai包安装方式:pip install openai
需要注意的是,如果你用的是比较老的Python版本(如我的阿里云服务器自带3.6.8版本),那openai就会安装比较老的版本,然后可能下面有一些封装好的功能就没有……
这是正常现象,建议改用requests(下面同样给出代码示例)。

1. 余额和token数

如何查看一句话算多少个token:https://platform.openai.com/tokenizer

ChatGPT使用BPE tokenizer tiktoken(官方GitHub项目:openai/tiktoken: tiktoken is a fast BPE tokeniser for use with OpenAI’s models.

import tiktoken
encoding = tiktoken.get_encoding("cl100k_base")
print(len(encoding.encode("一亩地租金1000元,那么3平方米地的租金应该是多少呢?首先需要将1亩转换为平方米,1亩=666.67平方米(约等于),因此每平方米的租金为:1000/666.67≈1.5元/平方米。\n\n那么3平方米的租金就是3×1.5=4.5元。")))

在response中也能看到每次调用所使用的总token数,见下面第2节的任务代码示例。

扫描二维码关注公众号,回复: 15187985 查看本文章

如何查看账户还剩多少token的余额:https://platform.openai.com/account/usage

2. 任务代码

2.1 通用文本生成

https://platform.openai.com/docs/guides/completion

使用官方提供的openai包:

import openai

openai.api_key = API_KEY

response = openai.Completion.create(
  model="text-davinci-003",
  prompt="一亩地有多少平方米?",
  temperature=0,
  max_tokens=100,
  top_p=1.0,
  frequency_penalty=0.0,
  presence_penalty=0.0,
)

print(response['choices'][0]['text'])

输出:一亩地的面积大小取决于所在的地区,一般来说,一亩地的面积大约为666平方米。(之前还会有两个回车,我也不知道为什么会有这玩意啊)

一个responce的输出格式:

<OpenAIObject text_completion id=omit at omit> JSON: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": "\n\n\u4e00\u4ea9\u5730\u7684\u9762\u79ef\u5927\u5c0f\u53d6\u51b3\u4e8e\u6240\u5728\u7684\u5730\u533a\uff0c\u4e00\u822c\u6765\u8bf4\uff0c\u4e00\u4ea9\u5730\u7684\u9762\u79ef\u5927\u7ea6\u4e3a666\u5e73\u65b9\u7c73\u3002"
    }
  ],
  "created": omit,
  "id": "omit",
  "model": "text-davinci-003",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 71,
    "prompt_tokens": 20,
    "total_tokens": 91
  }
}

使用requests:

import requests
response1=requests.post(url='https://api.openai.com/v1/completions',
                        headers={
    
    'Authorization':f"Bearer {
      
      API_KEY}",
                                 'content-type':'application/json'},
                        data="""{
                                "model": "text-davinci-003",
                                "prompt": "一亩地租金1000元,那么3平方米地的租金应该是多少呢?",
                                "max_tokens": 7,
                                "temperature": 0
                            }""".encode('utf-8')
                        )

response1.json()的输出:

{'id': 'omit',
 'object': 'text_completion',
 'created': omit,
 'model': 'text-davinci-003',
 'choices': [{'text': '\n\n3平方米地的租金应该是3000元。',
   'index': 0,
   'logprobs': None,
   'finish_reason': 'stop'}],
 'usage': {'prompt_tokens': 50, 'completion_tokens': 26, 'total_tokens': 76}}

(显然回答是错的,但这不重要)

2.2 通用对话

https://platform.openai.com/docs/guides/chat

使用openai包:

import openai
openai.api_key = api_key

completion = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
    {
    
    "role": "user", "content": "一亩地租金1000元,那么3平方米地的租金应该是多少呢?"}
  ]
)

completion.choices[0].message['content']的输出是:'首先需要将1亩转换为平方米,1亩=666.67平方米(约等于),因此每平方米的租金为:1000/666.67≈1.5元/平方米。\n\n那么3平方米的租金就是3×1.5=4.5元。'
看看人家的回答就阳间了很多啊,所以我的建议是用chat代替completion!

使用requests包:

import requests
response1=requests.post(url='https://api.openai.com/v1/chat/completions',
                        headers={
    
    'Authorization':f"Bearer {
      
      API_KEY}",
                                 'content-type':'application/json'},
                        data="""{
                                "model": "gpt-3.5-turbo",
                                "messages": [{"role":"user","content":"如何通过API调用查看余额?"}],
                                "max_tokens": 512,
                                "temperature": 0
                            }""".encode('utf-8'),
                        proxies={
    
    "http":"127.0.0.1:7890","https":"127.0.0.1:7890"}
                        )
print(response1.json())

输出是:
{'id': 'omit', 'object': 'chat.completion', 'created': omit, 'model': 'gpt-3.5-turbo-0301', 'usage': {'prompt_tokens': 19, 'completion_tokens': 291, 'total_tokens': 310}, 'choices': [{'message': {'role': 'assistant', 'content': '要通过API调用查看余额,您需要使用相应的API接口和密钥。以下是一般的步骤:\n\n1. 获取API密钥:您需要在交易所或钱包中创建API密钥,以便您可以使用API接口进行交易和查询余额。\n\n2. 查找API文档:您需要查找API文档,以了解如何使用API接口查询余额。不同的交易所和钱包可能有不同的API接口和参数。\n\n3. 发送API请求:使用API密钥和API接口,您可以发送API请求来查询余额。您需要提供相应的参数,例如货币类型和钱包地址。\n\n4. 解析API响应:一旦您发送了API请求,您将收到一个API响应。您需要解析响应以获取余额信息。响应可能是JSON格式的数据,您需要使用相应的编程语言解析它。\n\n请注意,不同的交易所和钱包可能有不同的API限制和费用。您需要仔细阅读API文档以了解这些限制和费用。'}, 'finish_reason': 'stop', 'index': 0}]}
其实我想问的是ChatGPT的API,不知道它觉得是什么的……

2.3 图像生成

https://platform.openai.com/docs/guides/images

2.4 微调

https://platform.openai.com/docs/guides/fine-tuning

建议有几百个示例。

2.5 嵌入

https://platform.openai.com/docs/guides/embeddings/what-are-embeddings

2.6 语音转文字

https://platform.openai.com/docs/guides/speech-to-text

2.7 内容安全性审核

https://platform.openai.com/docs/guides/moderation/overview
https://platform.openai.com/docs/guides/safety-best-practices

2.8 速率限制

https://platform.openai.com/docs/guides/rate-limits/overview

  1. 解决方案:
    指数退避:参考我撰写的博文Python3:在访问不可靠服务时的重试策略(持续更新ing…)
  2. 批输入

2.9 错误代码

https://platform.openai.com/docs/guides/error-codes/api-errors

  1. 你的尝试次数太多,超过了速率限制
  2. 整个网络上用这个模型的人太多了,把你的请求给卡掉了:b'{\n "error": {\n "message": "That model is currently overloaded with other requests. You can retry your request, or contact us through our help center at help.openai.com if the error persists. (Please include the request ID 8a25aae67dadf1f6334a4dadc65f2048 in your message.)",\n "type": "server_error",\n "param": null,\n "code": null\n }\n}\n'
    这个问题我查了一下,从1月开始就有人喷了:Status code 503: That model is currently overloaded with other requests - API - OpenAI Developer Forum

2.10 其他

https://platform.openai.com/docs/guides/production-best-practices

3. 模型

https://platform.openai.com/docs/models

3.1 模型选择

文本生成表现最好的就是Davinci (text-davinci-003),最便宜的是Ada (ada):

在这里插入图片描述
但是推荐用GPT 3.5这个chat模型来实现文本补完,因为效果好(上面给出示例了)

4. 通用超参设置

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

  1. temperature越高,多样性越大
  2. 输入长度:对于大多数模型,单个 API 请求在提示和完成之间最多只能处理 4,096 个token。
  3. max_tokens

5. 示例

https://platform.openai.com/examples
https://platform.openai.com/docs/tutorials/web-qa-embeddings

6. 在撰写本文过程中使用到的其他网络资料

  1. python - ‘latin-1’ codec can’t encode characters - Stack Overflow
  2. Python/Json:Expecting property name enclosed in double quotes - Stack Overflow

猜你喜欢

转载自blog.csdn.net/PolarisRisingWar/article/details/130733337