调用openai接口的正确打开方式

调用openai接口的正确打开方式:

1.安装anaconda

为更好使用openai的功能,技术专家建议用py3.10。我问chatgpt它说只要py3.6及以上就行。我个人建议尽可能用anaconda较新的,但用anaconda2022.10的版本即可,可适配python3.10或python3.11。2023.03上新的anaconda仍有难以解决的bug,不推荐(安装后打不开,报错显示为File “C:\Users\bonni\anaconda3\lib\codecs.py”, line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xd3 in position 3421: invalid continuation byte)
如果用的是适配py3.6版本的anaconda,可能后续openai库安装失败等报错。

2.虚拟环境安库

在anaconda中新建虚拟环境py310,并交互式安装:
1.openai;
2.相关依赖库ipywidgets。

3.Jupyterlab交互体验

3.1 确认环境。

打开jupyterlab,先确保jupyterlab所在环境与你的虚拟环境py310一致。
import sys
print(sys.executable)
print(sys.version)

3.2 测试openai接口是否可用。

这里需要填写openai的api key,需要科学上网。

import openai
import os

openai.api_key = '你自己的api secret key'
COMPLETION_MODEL = "text-davinci-003"

prompt = """
Consideration proudct : 工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具

1. Compose human readable product title used on Amazon in english within 20 words.
2. Write 5 selling points for the products in Amazon.
3. Evaluate a price range for this product in U.S.

Output the result in json format with three properties called title, selling_points and price_range
"""

def get_response(prompt):
    completions = openai.Completion.create (
        engine=COMPLETION_MODEL,
        prompt=prompt,
        max_tokens=512,
        n=1,
        stop=None,
        temperature=0.0,        
    )
    message = completions.choices[0].text
    return message

print(get_response(prompt)) 

结果显示如下:

{
“title”: “Glow-in-the-Dark Inflatable PVC Frog Night Market Hot Selling Water Toy for Kids”,
“selling_points”: [
“Made of durable PVC material”,
“Glow-in-the-dark design for night play”,
“Inflatable design for easy storage and transport”,
“Fun water toy for kids of all ages”,
“Comes with a repair patch for convenience”
],
“price_range”: “$10 – $20”
}

物联沃分享整理
物联沃-IOTWORD物联网 » 调用openai接口的正确打开方式

发表评论