大家好,我是老三,最近几个月关于ChatGPT的信息可以说是铺天盖地。
“王炸,ChatGPT……”
“xxx震撼发布……”
“真的要失业了,xxx来袭……”
“普通如何利用ChatGPT……”
……
不过老三前一阵比较忙,对ChatGPT的使用基本只限于一些简单的问答,比如:
可以说是落伍到家了,刚好公司组织了对ChatGPT的一些讨论和实践,趁这个机会赶紧补补课。
快速上手
作为一般的后端开发人员,要利用ChatGPT,其实主要还是是调用openai的接口,先跟着官方文档(https://platform.openai.com/docs/quickstart),快速开始。
简介
- completions接口:https://platform.openai.com/docs/api-reference/completions/create
这个接口是openai核心接口,输入里有个参数prompt,可以简单理解为问,响应里有个参数completion,可以简单理解为答。
创建应用
官方给了Node.js和Python的Demo,没有关系,反正无非是接口调用,用什么都可以。
因为我本地配置了Python的环境,所以就跟着官方的Python Demo走一走。
拉取项目
Python环境的创建这里就不多说了,直接把官方的Demo拉下来。
git clone https://github.com/openai/openai-quickstart-python.git
添加API Key
首先需要在这个地址:https://platform.openai.com/account/api-keys 添加一个api-key.
在.env文件里添加配置OPENAI_API_KEY
:
运行
- 安装依赖
python -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- 运行项目
flask run
- 访问http://localhost:5000
简单看下官方Demo,官方提供了Python包:
import openai
官方还提供了node.js的包,社区也贡献了一些其他语言的包(https://platform.openai.com/docs/libraries/community-libraries):
- Java:https://github.com/TheoKanning/openai-java
- Go:https://github.com/sashabaranov/go-openai
……
Python Demo里就是直接用封装的方法调用:
response = openai.Completion.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
不用官方和社区封装的包,直接http调用也可以。
当然openai也不是免费的,以gpt-3.5-turbo为例,费用是$0.002 / 1K tokens,也就是大概$0.002 / 750个词,具体费用可以看看:https://openai.com/pricing,注册送了18💰,大概能答不到1000个问题吧。
常见API
在快速开始里用了Completion API,接下来再看看常见的API。
模型
Model(模型)是openai的核心,有一系列不同功能不同版本的模型。
Playground
在前面,我们跑了官方的Demo,其实还有一个更简单快捷的方式,官方提供了一个好用的Playground
,有点像开发版的chatGPT,可以直接指定不同的模型不同的参数,调用不同的api:
还可以直接查看代码,支持python、node.js、curl。
接下来看看openai的内容处理,主要包括三种:Text completion
、Code completion
和Image generation
,分别针对文本、代码和图片。
内容处理API
调用API还是用Python,因为官方给了Demo,Python跑起来也比较轻便。
接着用官方的实例,open-ai需要升级到最新版本:
Completion
- Completions:https://platform.openai.com/docs/api-reference/completions
这个是比较早,用的比较多的接口,不支持gpt-3.5和gpt-4模型的模型。
参数 | 类型 | 说明 |
---|---|---|
model | string | 必填,指定功能模型 |
prompt | string 或 array | 提示语 |
max_tokens | integer | 默认值 16,The maximum number of tokens to generate in the completion. |
temperature | number | 默认值 1,采样精度,取值范围为 0~2,较高的值(如 0.8)将使输出更加随机,而较低的值(例如 0.2)将使其更加相关 |
top_p | number | 默认值 1,采样精度的另一种表示方式,如 0.1 表示更相关的 10% 的内容,请不要和 temperature 同时使用(2 选 1) |
n | integer | 默认值 1,返回内容的条数 |
stream | boolean | 默认值 false,是否流式输出内容 |
echo | boolean | 默认值 false,是否回显 prompt 内容 |
stop | string 或 array | 默认值 null,Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence. |
- Python请求
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response=openai.Completion.create(
model="text-davinci-003",
prompt="Hello World",
max_tokens=512,
temperature=0
)
- 响应
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"text": "\n\nMy name is John and I am new to this website. I am interested in learning more about programming and computer science."
}
],
"created": 1679751379,
"id": "cmpl-6xyM7jPbvSSO7umjVk8HkrRfJVoHZ",
"model": "text-davinci-003",
"object": "text_completion",
"usage": {
"completion_tokens": 26,
"prompt_tokens": 2,
"total_tokens": 28
}
}
可以看到已经回复了,我们要是想继续怎么办呢?也就是类似chatGPT里接着会话——那就需要把整个上下文传过去。
比如上面一个,我希望它能继续回答:
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
prompt_context=["Hello World","\n\nMy name is John and I am new to this website. I am interested in learning more about programming and computer science.","Any more?"]
response=openai.Completion.create(
model="text-davinci-003",
prompt=prompt_context,
max_tokens=1024,
temperature=0
)
- 响应:可以看到接着继续回答了
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"logprobs": null,
"text": "\n\nMy name is John and I am new to this website. I am interested in learning more about programming and computer science."
},
{
"finish_reason": "stop",
"index": 1,
"logprobs": null,
"text": " I have some basic knowledge of HTML and CSS, but I am looking to expand my knowledge and learn more about other programming languages. I am also interested in learning more about web development and design."
},
{
"finish_reason": "stop",
"index": 2,
"logprobs": null,
"text": "\n\n-Making sure to get enough sleep\n-Eating a balanced diet\n-Drinking plenty of water\n-Exercising regularly\n-Managing stress\n-Limiting alcohol and caffeine intake\n-Practicing relaxation techniques\n-Spending time outdoors\n-Connecting with friends and family\n-Engaging in creative activities\n-Volunteering in the community\n-Practicing mindfulness and meditation"
}
],
"created": 1679751585,
"id": "cmpl-6xyPRzgmrTskbfQ85l5MdmIdUU6iZ",
"model": "text-davinci-003",
"object": "text_completion",
"usage": {
"completion_tokens": 149,
"prompt_tokens": 31,
"total_tokens": 180
}
}
当然prompt传的越多,网络消耗,以及💰消耗都越多,那怎么减少上下文传递呢?
具体实现,感兴趣的也可以再问问ChatGPT。
Chat
- Chat:https://platform.openai.com/docs/api-reference/chat
2023 年 3 月 1 日新增接口,使用的是最新的 GPT-3.5 模型和 GPT-4 模型。与 Completion
API 不同,ChatCompletion
API 更适合用于实时的、多轮的对话。
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
chat = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a assistant of shein,you can help user to resolve problems."},
{"role": "user", "content": "How can I refund my order?"},
]
)
- 响应:
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "To initiate a refund for your Shein order, you can follow these steps:\n\n1. Log in to your Shein account.\n2. Go to your order history and find the order you want to refund.\n3. Click on the \"Return\" button and select the item(s) you want to return.\n4. Choose the reason for the return and add any pictures or comments if necessary.\n5. Submit the return request and wait for Shein to send you a confirmation email.\n6. Pack and send your items back to Shein according to the instructions provided in the email.\n7. Once Shein receives and processes your return, your refund will be issued to your original payment method within 7-14 business days.\n\nNote: Make sure to check Shein's return policy before initiating a refund to ensure that your item is eligible for return.",
"role": "assistant"
}
}
],
"created": 1679876980,
"id": "chatcmpl-6yV1wSwqM09Aqb6QvFENUvuvC4ehW",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 171,
"prompt_tokens": 36,
"total_tokens": 207
}
}
ChatCompletion
支持三种角色:
- user:用户,提出问题或者输入内容的人
- assint:聊天机器人,基于GTP3等模型的的机器人,可以回答用户的问题或者会话。
- system:应用程序,负责处理用户输入,然后传递给聊天机器人,或者接收聊天机器人的回答,展现给用户。应用程序也可以负责处理其他任务,例如将用户输入保存到数据库中。
实际应用中,可以通过system指定指定 chatGPT 的功能定位,在 assistant 中传 chatGPT 回答的消息就实现了上下文。
Images
OpenAI的图片接口,支持通过描述生图,和以图生图:
- Images(通过描述生成图):https://platform.openai.com/docs/api-reference/images
参数 | 说明 |
---|---|
prompt | 图片描述,必填 |
n | 需要生成的图片数量,取值 1-10,默认值 1 |
size | 图片大小,取值只能为 256x256、512x512、1024x1024,默认值 1024x1024 |
response_format | 返回图片数据类型,取值 url 或 b64_json,默认值 url |
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response=openai.Image.create(
prompt="A beautiful young and generous Chinese girl",
n=1,
size="1024x1024"
)
- 响应
{
"created": 1679877722,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-ZPdLSXE667sQLqeMtNJSlY4u/user-CdRYPYeBIHN8eGFIq87eroQN/img-sSV6B5nOzOpRre41J73guwu6.png?st=2023-03-26T23%3A42%3A02Z&se=2023-03-27T01%3A42%3A02Z&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-03-26T20%3A06%3A23Z&ske=2023-03-27T20%3A06%3A23Z&sks=b&skv=2021-08-06&sig=EphBdwHcs4p5x3F5su8r9NvG8mGRKx4cOkCjbBWekGA%3D"
}
]
}
我们看看生成的图怎么样?
我滴妈,哕……
- Create image variationBeta(以图生图):https://platform.openai.com/docs/api-reference/images/create-variation
从某竞品网站下了一张好看的模特图:
图片需要裁剪和压缩一下,图片长宽需要1:1,是png文件,而且小于4M。
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response=openai.Image.create_variation(
image=open("apis/model.png", "rb"),
n=1,
size="1024x1024"
)
print(response)
- 响应
{
"created": 1679878760,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-ZPdLSXE667sQLqeMtNJSlY4u/user-CdRYPYeBIHN8eGFIq87eroQN/img-uZUO48KfwJpEuCf6Na7fIFG1.png?st=2023-03-26T23%3A59%3A20Z&se=2023-03-27T01%3A59%3A20Z&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-03-26T14%3A21%3A52Z&ske=2023-03-27T14%3A21%3A52Z&sks=b&skv=2021-08-06&sig=YR39Y3sxD7kqnoJcVqEqKxc9bBi//nsn3X0SOtX/wI4%3D"
}
]
}
看看生成的图片,
啊这。。。
当然chatGPT也支持对现有图的修改。
- Create image edit(以图修图可修改):https://platform.openai.com/docs/api-reference/images/create-edit)
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response=openai.Image.create_edit(
image=open("apis/model.png", "rb"),
mask=open("apis/model.png", "rb"),
prompt="Generate a female model who is equally beautiful, hotter, but with different looks and clothes",
n=2,
size="1024x1024"
)
print(response)
- 响应:
{
"created": 1680363981,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-ZPdLSXE667sQLqeMtNJSlY4u/user-CdRYPYeBIHN8eGFIq87eroQN/img-vYOBGDlf5su7sMfQSITKna8w.png?st=2023-04-01T14%3A46%3A21Z&se=2023-04-01T16%3A46%3A21Z&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-04-01T08%3A48%3A23Z&ske=2023-04-02T08%3A48%3A23Z&sks=b&skv=2021-08-06&sig=ajPilUO%2BzBNQDtFDHrEyK2/njZQrZsaTyV7wjQRFRJM%3D"
}
]
}
虽然,但是,这个api我尝试了好几个prompt,给我吐回的都是原图。
整体上来讲,chatGPT的Images API还是没有文本问答那么好用,而且比较贵,尺寸 1024x1024 像素的图一张收费 0.02 美元,大约人民币 0.13 元左右。
Audio
chatGPT还支持语音识别
- Audio:https://platform.openai.com/docs/api-reference/audio
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
audio_file = open("apis/audio.mp3", "rb")
transcript = openai.Audio.transcribe("whisper-1", audio_file)
print(transcript)
我一开始用了一段中英混杂的语言,结果响应:
{
"text": "Java\u662f\u8fd9\u4e2a\u4e16\u754c\u4e0a\u6700\u597d\u7684\u8bed\u8a00 \u4f46\u662f\u6211\u7528Python"
}
乱码了,赶紧问下chatGPT:
嗯,这次翻车了,连续尝试了五六个回答,都没能解决乱码的问题,看样子OpenAI确对中文语言输入不太友好。
改成英文语音输入的结果:
{
"text": "Jawa is the best language in the world, but I use Python."
}
英文的语音识别还是比较准确的,当然,语音识别早就不是什么问题了。
总体上来看,OpenAI的文本处理能力还是非常强大的,图像处理还有待提升,不过以OpenAI的迭代速度,以及全世界用户的不断”投喂“,相信新模型”远超Midjourney“绝对不是一句空话。
一些思考
可以用OpenAI干什么?
怎么应用OpenAI,或者说怎么应用AI呢?
先从工作看起吧,我是做跨境电商业务的,我问了一下ChatGPT,看看它的回答:
可以看一下,这里面包含客服、推荐、内容、翻译、风控等等……
有一些正在被我的同事实现,有些甚至已经投产。
那么我还是一个程序员,具体点Java程序员,我可以怎么利用OpenAI呢?
这里面有一些能力,相信很多朋友更加熟悉,现在日常开发,可以不用搜索引擎,而是直接向ChatGPT提问。
问答助手、代码生成插件、SQL助手……目前,这些也都有同事进行了实现。
大概都是怎么实现的呢?
其实这些应用,这些应用的关键,就是在于正确地向ChatGPT提问,有这么一条“公式”:定义角色+明确任务+限制输出 = better prompt
例如,我现在希望OpenAI作为一个商品评论审核员:
- 你是一个跨境电商的商品评论审核员,你需要对用户的评论进行审核,你需要识别不同语言的评论,用户评论中不能出现暴力、色情、政治等负面因素,你需要对评论进行打分,60分以上是合格评论,60分以下是不合格评论,用户评论越积极分数越高,你还要给出给用户打分的原因,你的回答只能用json格式{“score”:30,“reason”:“Violence”},score表示评分,reason表示原因,除此之外,你不应该回答任何内容
然后再输入一个评论:
- 这个商品是在太垃圾了
它的响应:
{
"score": 40,
"reason": "Negative sentiment"
}
开发的时候,就是要先把上下文给传过去:
chat = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0301",
messages=[
{"role": "system", "content": "你是一个跨境电商的商品评论审核员,你需要对用户的评论进行审核,你需要识别不同语言的评论,用户评论中不能出现暴力、色情、政治等负面因素,你需要对评论进行打分,60分以上是合格评论,60分以下是不合格评论,用户评论越积极分数越高,你还要给出给用户打分的原因,你的回答只能用json格式{\"score\":30,\"reason\":\"Violence\"},score表示评分,reason表示原因,除此之外,你不应该回答任何内容"},
{"role": "system", "content": "OK"},
{"role": "user", "content": "什么烂东西,浪费钱"}
]
)
是不是还挺简单的。
除此之外,有条件的还可以对OpenAI的模型进行微调,提升模型的性能。
我们会被淘汰吗?
坦白讲,大家都拥抱OpenAI很久,我实在落伍了。
现在对于OpenAI的应用,其实主要还是集中在AIGC方面,我主要搞的是支付开发,是交易类的,想了很久也没想出什么应用。
随后问了ChatGPT一个问题:“接入Alipay支付”:
看完,我直接沉默,代码虽然有些不太合理的地方,但是估计再调一调就能直接用了。
这就引入了一个问题,AIGC时代来临,程序员会不会被淘汰?——很有可能。
我们今天为ChatGPT欢呼,也许明天就会被它给驱逐。
36氪给李彦宏做了一个专访[3],我们看看其中的一段:
我甚至在想一个问题——AI会不会淘汰AI工程师呢?
所以,试着成为一名AI工程师?
参考:
[1]. https://platform.openai.com/
[2].https://www.zhihu.com/question/575983484/answer/2895862383
[3].https://36kr.com/p/2184414265262467