以下是Python免费试用最新Openai API的步骤详解:
1. 注册Openai账号并获取API key
1.1 打开 https://beta.openai.com/signup/ 进入Openai注册页面;
1.2 在注册页面填写信息并完成注册;
1.3 注册成功后,进入Dashboard(仪表盘)页面,生成API key。
2. 安装Openai API
在终端中执行以下命令安装Openai API库:
pip install openai
3. 配置Openai API key
在Python脚本中使用以下代码配置API key:
import openai_secret_manager
assert "openai" in openai_secret_manager.get_services()
secrets = openai_secret_manager.get_secret("openai")
print(secrets)
# {'api_key': 'sk-***'}
4. 调用Openai API
接下来,我们就可以使用Openai API进行文本生成任务了。这里以GPT-3模型为例:
import openai
openai.api_key = secrets["api_key"]
model_engine = "text-davinci-002"
prompt = "It's a beautiful day in the neighborhood"
completions = openai.Completion.create(
engine=model_engine,
prompt=prompt,
max_tokens=60,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
print(message)
以上代码会向Openai API提交一个文本生成任务,生成的文本以消息的形式返回。其中参数含义如下:
- prompt:文本生成的起始点;
- max_tokens:最大生成的token数;
- n:生成的消息数;
- stop:生成消息的终止符号,None表示没有设置;
- temperature:生成文本的温度值。
示例1:生成文本
import openai
import openai_secret_manager
openai.api_key = openai_secret_manager.get_secret("openai")["api_key"]
model_engine = "davinci"
prompt = "My dog loves to go"
completions = openai.Completion.create(
engine=model_engine,
prompt=prompt,
max_tokens=60,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
print(message)
输出:
My dog loves to go for a walk with me. We always have fun together and he's so happy when we get back home.
示例2:改造诗歌
import openai
import openai_secret_manager
openai.api_key = openai_secret_manager.get_secret("openai")["api_key"]
model_engine = "davinci"
original = "Two roads diverged in a yellow wood, And sorry I could not travel both And be one traveler, long I stood And looked down one as far as I could"
paraphrase = "Rewrite this poem in simpler language"
completions = openai.Completion.create(
engine=model_engine,
prompt=original+"\n"+paraphrase,
max_tokens=60,
n=1,
stop=None,
temperature=0.5,
)
message = completions.choices[0].text
print(message[len(original):])
输出:
I couldn't choose between two roads. They looked about the same. And I stood there for a long time looking at one.
以上就是Python免费试用最新Openai API的步骤详解。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python免费试用最新Openai API的步骤 - Python技术站