当前位置:   article > 正文

python请求chatgpt

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

报错如下:
在这里插入图片描述
因为 开了代理(访问chatgpt需要vpn代理):
解决办法: 指定 urllib3 的版本

pip install urllib3==1.25.11
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/57321
推荐阅读
相关标签
  

闽ICP备14008679号