使用Python发送请求与ChatGPT进行交互

import requests

def chat_with_gpt(prompt, model="gpt-3.5-turbo", api_key=""):
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    data = {
        "model": model,
        "prompt": prompt,
        "temperature": 0.7,
        "max_tokens": 100
    }

    response = requests.post("https://api.openai.com/v1/engines/gpt-3.5-turbo/completions",
                             headers=headers, json=data, verify=False)

    if response.status_code == 200:
        return response.json()['choices'][0]['text'].strip()
    else:
        return f"Error: {response.status_code}"


# 使用示例
prompt = "你好,我是ChatGPT,请问有什么可以帮助你的?"
response = chat_with_gpt(prompt, api_key="sk-xxxxxxx")
print(response)

报错如下:

因为 开了代理(访问chatgpt需要vpn代理):
解决办法: 指定 urllib3 的版本

pip install urllib3==1.25.11
物联沃分享整理
物联沃-IOTWORD物联网 » 使用Python发送请求与ChatGPT进行交互

发表评论