ChatGPT API申请及使用记录

发布于 2023-06-29  530 次阅读


如果连接错误可能是urllib3库的版本问题,可以回退至1.25.11版本

pip install urllib3==1.25.11

安装时若显示依赖库版本不兼容根据提示安装相应版本即可,如果提示anaconda-client版本冲突则将anaconda-client降至1.1.1

若安装后还不能连接,可能是国内api连接不稳定,可以使用代理

调用效果:

chatgpt-api调用代码示例

import openai
openai.api_key = "你的api地址" 

#如果api被墙可设置代理接口
"""
proxy = {
'http': 'http://localhost:7890',
'https': 'http://localhost:7890'
}
openai.proxy = proxy;
"""

# 调用 ChatGPT
response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                # {"role": "system", "content": "一位经验丰富的C++开发工程师"},
                {"role": "user", "content": "能给我介绍一下C++ 20的新特性吗?"},
            ],
        )

# 输出响应结果
# print(response)
answer = response.choices[0].message.content.strip()
print(answer)

#------------------------连续对话------------------------#
class Chat:
    def __init__(self,conversation_list=[]) -> None:
        # 初始化对话列表,可以加入一个key为system的字典,有助于形成更加个性化的回答
        # self.conversation_list = [{'role':'system','content':'你是一个非常友善的助手'}]
        self.conversation_list = []
    
    # 打印对话
    def show_conversation(self,msg_list):
        for msg in msg_list:
            if msg['role'] == 'user':
                print(f"\U0001f47b: {msg['content']}\n")
            else:
                print(f"\U0001f47D: {msg['content']}\n")

    # 提示chatgpt
    def ask(self,prompt):
        self.conversation_list.append({"role":"user","content":prompt})
        response = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=self.conversation_list)
        answer = response.choices[0].message['content']
        # 下面这一步是把chatGPT的回答也添加到对话列表中,这样下一次问问题的时候就能形成上下文了
        self.conversation_list.append({"role":"assistant","content":answer})
        self.show_conversation(self.conversation_list)
届ける言葉を今は育ててる
最后更新于 2023-07-03