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 的回复。
相关推荐
方也_arkling8 小时前
【Java-Day08】static / final / 枚举
java·开发语言
风吹夏回8 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei118 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1128 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding8 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋98 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
小江的记录本8 小时前
【JVM虚拟机】垃圾回收GC:垃圾收集器:CMS:核心原理、回收流程、优缺点、废弃原因(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·面试·maven
xiaoshuaishuai89 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024069 小时前
SVN 检出操作
开发语言
田里的水稻9 小时前
OE_ubuntu26.04与宿主机之间复制粘贴内容
人工智能·python·机器人