0%

简单使用 chatGPT API

本来没有兴趣的,是 openai 的价格先动的手,记录一下使用 chatGPT API 的过程

起因

前段时间 chatGPT 刚出的时候用过网页端的,体验比较一般,第一是需要有稳定的网络环境,第二是反馈有时候会出不来需要重新加载页面。直到早上在 Twitter 刷到 openAI 的推文 Introducing ChatGPT and Whisper APIs

openAI's Twitter

又去官网看了眼价格,不关我事,是价格先动的手,有到2023年4月1日截止的免费的$18使用额度

chatGPT's Price

API使用效果

可以在代码里调用
chatGPT's api result

过程

前提

首先有两个前提:

  • 科学上网
  • 注册openAI的账号

由于是之前注册的,先留个空,可以先上网找下保姆级教程,回头再来补

注册API

  1. 先访问 openAI 然后登录
  2. 登录后找到 USER 选项下的 API Keys
  3. 点击 + Create new secret key 生成密钥并复制记录下来,应该无法再次查看的,如果没记到删了再加就行
  4. 生成后的界面如下

Create new secret key

在 python 中安装 openai

  1. 确保有python环境
  2. pip install openai

python 简单调用 chatGPT

新建一个.py文件,写入以下内容并保存

1
2
3
4
5
6
7
8
import openai
openai.api_key = 'sk-xxxxx'//${YOUR_API_KEY}
openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "How would you comment on the api of chatgpt?"},
]
)

代码说明

1
import openai

导入上一步安装的openai包,这个包里有很多其他好玩的东西,例如gym等

1
openai.api_key = 'sk-xxxxx'//${YOUR_API_KEY}

设置api_key,将'sk-xxxxx'替换成你在 openAI 上注册 API 时保存的那一串sk-起头的字符

1
2
3
4
5
6
openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "How would you comment on the api of chatgpt?"},
]
)

生成一个会话,使用gpt-3.5的模型,并发送user类别的信息How would you comment on the api of chatgpt?
在这个API中一共有system,user,assistant三个类别的信息,官方是这样说明的:

The system message helps set the behavior of the assistant. In the example above, the assistant was instructed with “You are a helpful assistant.”

The user messages help instruct the assistant. They can be generated by the end users of an application, or set by a developer as an instruction.

The assistant messages help store prior responses. They can also be written by a developer to help give examples of desired behavior.

可以简单理解为system是告诉它它是一个什么身份或有什么特性;user是一般使用的,用来询问或命令它生成信息;assistant是用于引导它生成你想得到的信息

执行代码后输出如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "\n\nAs an AI language model, I don't have access to the API of ChatGPT or any specific technical knowledge about it. However, based on user feedback and reviews, ChatGPT's API is generally considered to be reliable, user-friendly, and efficient in delivering chatbot services. With its advanced natural language processing capabilities, the ChatGPT API is recognized for its ability to provide intelligent and personalized responses to user queries, making it a valuable tool for businesses seeking to improve their customer service and engagement. Overall, the API of ChatGPT is a powerful and effective tool for chatbot development and integration.",
"role": "assistant"
}
}
],
"created": xxxxx,
"id": "chatcmpl-xxxxx",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 125,
"prompt_tokens": 20,
"total_tokens": 145
}
}

至此已经可以将这个API简单的嵌进自己的应用里了,至于还有什么开脑洞的用法还得用一段时间看看

欢迎关注我的其它发布渠道