首先得要有科学上网,我还没有测试过可行性,先贴下来不要浪费我的Token,回头再进行测试..

Step01 安装requests库

pip insatll requests

Step02 代码如下

import requests

class ChatGPT:
    def __init__(self, api_key):
        self.api_key = api_key
        self.api_url = "https://api.openai.com/v1/engines/davinci/completions"
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def ask(self, question):
        data = {
            "prompt": question,
            "max_tokens": 150  # you can adjust this as needed
        }
        response = requests.post(self.api_url, headers=self.headers, json=data)
        response_json = response.json()

        if "choices" in response_json and len(response_json["choices"]) > 0:
            return response_json["choices"][0]["text"].strip()
        else:
            return "Sorry, I couldn't process that request."

    def main():
        api_key = "YOUR_OPENAI_API_KEY"  # Replace with your OpenAI API key
        chatgpt = ChatGPT(api_key)

    while True:
        question = input("You: ")
        if question.lower() in ["exit", "quit"]:
            break
        answer = chatgpt.ask(question)
        print(f"ChatGPT: {answer}")

if __name__ == "__main__":
    main()

Step03 操作说明

  • 在上述代码中,将 "YOUR_OPENAI_API_KEY" 替换为您的OpenAI API密钥。
  • 运行代码,输入问题,然后ChatGPT会回复您。
  • 当您想退出对话时,输入exitquit
最后修改:2023 年 10 月 29 日
如果觉得我的文章对你有用,请随意赞赏..