python 用于请求chartGpt DEMO request请求方式

以下是一个使用 Python 的 requests 库向 ChatGPT 发起请求的示例代码。确保你已经安装了 requests 库,可以通过 pip install requests 来安装。

复制代码
import requests

# 替换为你的 OpenAI API 密钥
api_key = '你的_API_密钥'
url = 'https://api.openai.com/v1/chat/completions'

headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}

data = {
    'model': 'gpt-3.5-turbo',  # 或者 'gpt-4' 根据你的需求
    'messages': [
        {'role': 'user', 'content': '你好,ChatGPT!请问今天的天气怎么样?'}
    ],
    'temperature': 0.7
}

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    response_data = response.json()
    print("ChatGPT的回复:", response_data['choices'][0]['message']['content'])
else:
    print(f"请求失败,状态码: {response.status_code}, 原因: {response.text}")

在这个示例中:

  1. 替换 '你的_API_密钥' 为你从 OpenAI 获取的实际 API 密钥。
  2. 发送一个包含用户消息的请求,并设置模型和温度参数。
  3. 打印 ChatGPT 的回复。
相关推荐
悟空爬虫33 分钟前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风3 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽12 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805117 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon18 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly18 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程18 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly20 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python