python请求chatgpt

bash 复制代码
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)

报错如下:

因为 开了代理(访问chatgpt需要vpn代理):

解决办法: 指定 urllib3 的版本

bash 复制代码
pip install urllib3==1.25.11
相关推荐
写代码的【黑咖啡】1 分钟前
Python 中的 Requests 库:轻松进行 HTTP 请求
开发语言·python·http
栗子叶1 分钟前
Spring 中 Servlet 容器和 Python FastAPI 对比
python·spring·servlet·fastapi
Duang007_2 分钟前
拆解 Transformer 的灵魂:全景解析 Attention 家族 (Self, Cross, Masked & GQA)
人工智能·深度学习·transformer
磊-5 分钟前
AI Agent 学习计划(一)
人工智能·学习
杨杨杨大侠7 分钟前
DeepAgents 框架深度解析:从理论到实践的智能代理架构
后端·python·llm
不会打球的摄影师不是好程序员11 分钟前
dify实战-个人知识库搭建
人工智能
袁袁袁袁满15 分钟前
Python读取doc文件打印内容
开发语言·python·python读取doc文件
xixixi7777722 分钟前
对 两种不同AI范式——Transformer 和 LSTM 进行解剖和对比
人工智能·深度学习·大模型·lstm·transformer·智能·前沿
lfPCB23 分钟前
聚焦机器人算力散热:PCB液冷集成的工程化现实阻碍
人工智能·机器人
sunxunyong27 分钟前
CC-Ralph实测
人工智能·自然语言处理