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 的回复。
相关推荐
2301_7644413317 小时前
python与Streamlit构建的旅游行业数据分析Dashboard项目
python·数据分析·旅游
问水っ17 小时前
Qt Creator快速入门 第三版 第6章 事件系统
开发语言·qt
cm65432017 小时前
C++中的空对象模式
开发语言·c++·算法
吴声子夜歌17 小时前
JavaScript——异常处理
开发语言·javascript·ecmascript
2401_8512729917 小时前
C++代码规范化工具
开发语言·c++·算法
阿kun要赚马内17 小时前
操作系统:线程与进程
java·开发语言·jvm
thulium_17 小时前
Rust 编译错误:link.exe 未找到
开发语言·后端·rust
人工智能AI技术17 小时前
GitHub Trending榜首:Python Agentic RAG企业级落地指南
人工智能·python
喵手17 小时前
Python爬虫实战:解构 CLI 工具命令参考文档树!
爬虫·python·爬虫实战·cli·零基础python爬虫教学·工具命令参考文档采集·数据采集实战
码云数智-园园17 小时前
数据库索引的基石:深度解析 B 树与 B+ 树的差异与应用
开发语言