python openai库教程
配置环境
pip install openai
列出模型
import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")openai.Model.list()
发送请求
Create completion
import osimport openaiopenai.api_key = ''openai.Completion.create( model="gpt-3.5-turbo", prompt="Say this is a test", max_tokens=7, temperature=0)
response
{ "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", "object": "text_completion", "created": 1589478378, "model": "text-davinci-003", "choices": [ { "text": "\n\nThis is indeed a test", "index": 0, "logprobs": null, "finish_reason": "length" } ], "usage": { "prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12 }}
请求参数
model
prompt
: 如果没有, the model will generate as if from the beginning of a new document.suffix
: 感觉没啥用max_tokens integer Optional Defaults to 16
gpt返回的最大tokens数量, 你的promt的tokens+max_tokens必须小于2048或4096(最新的model)
temperature number Optional Defaults to 1
range from [0,2], 温度越高, 随机性越强
官方建议, 温度和top_p值改变一个
top_p number Optional Defaults to 1
用温度吧, 别用他n int Opt Defau 1
对于每个prompt, 产生的completions的条数
chat
import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, {"role": "user", "content": "Where was it played?"} ])print(completion.choices[0].message)
response
{ "id": "chatcmpl-123", "object": "chat.completion", "created": 1677652288, "choices": [{ "index": 0, "message": { "role": "assistant", "content": "\n\nHello there, how may I assist you today?", }, "finish_reason": "stop" }], "usage": { "prompt_tokens": 9, "completion_tokens": 12, "total_tokens": 21 }}
在 Python 中,可以使用 提取助手的回复response[‘choices’][0][‘message’][‘content’]
一般来说,gpt-3.5-turbo-0301
对系统消息的关注度不高,因此重要的说明往往放在用户消息中比较好。
edit
给定提示和指令,模型将返回提示的编辑版本。
import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")openai.Edit.create( model="text-davinci-edit-001", input="What day of the wek is it?",#用作编辑起点的输入文本。 instruction="Fix the spelling mistakes"# it's like prompt)
图像生成
建议用midjourney :)
import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")openai.Image.create( prompt="A cute baby sea otter",#最长1000个字符 n=2,#生成的图像数量, 在1~10之间 size="1024x1024")
图像编辑
在给定原始图像和提示的情况下创建编辑或扩展图像。
import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")openai.Image.create_edit( image=open("otter.png", "rb"),#要编辑的图像 mask=open("mask.png", "rb"),#附加图像,可选 prompt="A cute baby sea otter wearing a beret",#最长1000个字符 n=2, size="1024x1024")
嵌入
这个感觉好高级, 留个坑
上传文件
所有文件最大1GB
用到了fine-tunes, 暂时不太懂
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果