如何搭建ChatGPT Python测试环境?

官网提供了ChatGPT的python测试代码,代码非常简单,但是在运行的时候遇到了一些小问题,在ubuntu环境下使用python安装openai包出错,最后使用anaconda3安装成功。下面是具体安装过程:

安装anaconda3

$ wget https://repo.anaconda.com/archive/Anaconda3-2022.10-Linux-x86_64.sh

$ bash Anaconda3-2022.10-Linux-x86_64.sh

Please, press ENTER to continue:回车

view agreement –more–:按'q'直接完成

Do you accept the license terms? [yes|no]:yes

[/home/ubuntu/anaconda3]: /home/ubuntu/mydisk/anaconda3

Do you wish the installer to initialize Anaconda3 by running conda init? [yes|no]: yes

配置anacond环境:

$ conda create -n ai python=3.11

$ conda activate ai

$ conda install -c conda-forge openai(如果运行失败再试一次,我是第二次成功的)

创建ChatGPT测试程序:

$ vi chatGPT.py

import os
import openai
print("欢迎使用ChatGPT智能问答,请在Q:后面输入你的问题,输入quit退出!")
openai.api_key = "sk-XXXXXXXXX"  
start_sequence = "\nA:"
restart_sequence = "\nQ: "
while True:
    prompt = input(restart_sequence)
    if prompt == 'quit':
        break
    else:
        try:
            response = openai.Completion.create(
              model="text-davinci-003",#这里我们使用的是davinci-003的模型,准确度更高。
              prompt = prompt,
              temperature=1,
              max_tokens=2000, #这里限制的是回答的长度,你可以可以限制字数,如:写一个300字作文等。
              frequency_penalty=0,
              presence_penalty=0
            )
            print(start_sequence,response["choices"][0]["text"].strip())
        except Exception as exc: #捕获异常后打印出来
            print(exc)

将标红的sk-XXXXXXXXX替换成你自己的ChatGPT API token

$ python chatGPT.py

欢迎使用ChatGPT智能问答,请在Q:后面输入你的问题,输入quit退出!

Q: 你好

A: 同样地,你好!

Q: quit

测试成功!!

物联沃分享整理
物联沃-IOTWORD物联网 » 如何搭建ChatGPT Python测试环境?

发表评论