首先需要安装openai模块
pip install openai
其次需要去官网申请一个key
登陆点击右上角头像,选择View API keys,然后点击下图按钮创建key即可。
1、聊天接口调用代码
import os
import openaiopenai.api_key = "sk-oahsWxJYvJYb6iX 你的key!!! Qggoq3vimkl7IKMOGCkm"
askInfo = input('--- ask: ')
# 聊天
response = openai.Completion.create(model="text-davinci-003",prompt=askInfo,temperature=0.7,max_tokens=2560,top_p=1,frequency_penalty=0,presence_penalty=0
)
print(response)
2、文字生成图片
下面代码除了需要openai模块外,还需要安装其他模块,主要用于返回的图片直接显示。
import os
import openaiimport requests as req
from PIL import Image
from io import BytesIOopenai.api_key = "sk-oahsWxJYvJYb6iX 你的key!!! Qggoq3vimkl7IKMOGCkm"askInfo = input('--- ask: ')# 绘制图片
response = openai.Image.create(prompt=askInfo,n=1,size="512x512"
)
print(response)
image_url = response['data'][0]['url']
print(image_url)# 打开链接中的图片
response = req.get(image_url)
image = Image.open(BytesIO(response.content))
image.show()