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 的回复。
相关推荐
MC皮蛋侠客18 小时前
SQLAlchemy 系列(三):声明式映射与 Schema——让类型、默认值和约束一致
数据库·python
会博通·代码搬运工18 小时前
会博通API对接实战:工程企业文档分布式采集系统的技术实现与Python SDK详解
开发语言·分布式·python·线性代数·矩阵·架构·电子档案合规
空堂与归18 小时前
大模型再火,也得先过 class 这一关
python
Muselit18 小时前
Python 泛型:把 list[User] 讲明白
python·fastapi
2501_9160074718 小时前
Python实现HTTPS爬虫的完整指南:使用requests、BeautifulSoup、Selenium和Scrapy
爬虫·python·ios·小程序·https·uni-app·iphone
林森lsjs18 小时前
完结撒花!Java SE 语法阶段总结!
java·开发语言
lupai18 小时前
短信接口快速接入与调用实战指南
java·开发语言·数据库
gptAI_plus18 小时前
别把整个仓库塞给 AI:用 Python 生成安全的代码上下文清单
python·chatgpt
吃饱了得干活19 小时前
Agent 记忆系统:从短期记忆到长期记忆
python·langchain·agent
刘名喜19 小时前
第12篇-Gradle-Kotlin-DSL构建指南
开发语言·kotlin·springboot