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="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")
print(response)

报错如下:
python请求chatgpt_第1张图片
因为 开了代理(访问chatgpt需要代理):
解决办法: 指定 urllib3 的版本

pip install urllib3==1.25.11

你可能感兴趣的:(chatgpt,python,人工智能)