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 的回复。
相关推荐
笨笨聊运维42 分钟前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite1 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
Want5951 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
小毛驴8501 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
coderxiaohan1 小时前
【C++】多态
开发语言·c++
gfdhy1 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
闲人编程2 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760002 小时前
Python 数据结构
数据结构·windows·python
Eiceblue2 小时前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html