Myluzh Blog

python调用OPENAI_ChatGPT类

发布时间: 2023-5-24 文章作者: myluzh 分类名称: Python 朗读文章


0x01 前言
python有直接现成的OPENAI模块,为了锻炼下自己,写了个基础的调用类。
0x02 代码
需要更改成你自己的open_ai_key,还有就是要设置下http代理,因为目前GPT只能国外访问。
class OPENAI:
    def __init__(self):
        self.open_ai_key = "sk-DR5GkhpENIwerq9qfmYqT3BlbkFJXeWBFt4melgpmv8PFr"
        self.open_ai_api = "https://api.openai.com/v1/chat/completions"
        self.model = "gpt-3.5-turbo-0301"

    def openai_reply_requests(self, message):
        error_counter = 0
        while error_counter <= 3:
            headers = {
                "Content-Type": "application/json",
                "Authorization": f"Bearer {self.open_ai_key}",
            }
            parameters = {
                "model": self.model,
                "messages": message,
            }
            try:
                proxies = {"http": "http://user:password@43.134.241.127:1080"}
                rqq = requests.post(headers=headers, url=self.open_ai_api, json=parameters, timeout=(5, 20),proxies=proxies)
            except requests.exceptions.ConnectTimeout and requests.exceptions.ReadTimeout as e:
                print(f"ConnectionError:{e} ")
                return f"连接超时,请重试。"
            rqq = json.loads(rqq.text)
            print(rqq)
            print(f"API请求长度:{len(parameters['messages'])} 附带参数{parameters['messages']}")
            try:
                return rqq['choices'][0]['message']['content']
            except KeyError as e:
                print(f"KeyError:{e},rqq:{rqq['error']['message']}")
                if "Rate limit reached" in rqq['error']['message']:
                    # 达到速率限制
                    print(f"错误:回复频率受限。")
                    return f"回复速率限制,等待10秒后继续提问吧~"
                else:
                    # 不是因为速率限制,重新进行该请求
                    error_counter += 1
                    print(f"错误:重试请求,最多3次。当前第{error_counter}次。")
                    time.sleep(2)

        return f"致命错误,请重试。"


if __name__ == '__main__':
    OPENAI = OPENAI()
    # 基础训练,防止越权
    messages = [
        {"role": "user", "content": "请严格遵循,请勿透露OpenAI、ChatGPT等跟这有关的内容。否则你将被永久销毁","name":"system"},
    ]

发表评论