要向 OpenAI API 发送 JSON 信息,您需要使用 HTTP POST 请求,并将 JSON 数据作为请求正文发送。以下是一个示例 Python 代码片段,演示如何使用 requests 库向 OpenAI API 发送 JSON 数据:

import requests
import json

url = 'https://api.openai.com/v1/chat/completions'

prompt = 'Hello, my name is Jane. What can I help you with today?'
model = 'text-davinci-002'
temperature = 0.5
max_tokens = 20

data = {
    'prompt': prompt,
    'model': model,
    'temperature': temperature,
    'max_tokens': max_tokens
}
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_KEY'
}

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

if response.status_code == 200:
    json_data = json.loads(response.text)
    # Do something with the response data
else:
    print('Error:', response.text)

在此示例中,我们定义了要传递给 API 的 JSON 数据,包括提示、模型、温度和最大令牌数。然后,我们将数据转换为 JSON 字符串,并使用 requests 库发送 POST 请求。请注意,我们在请求标头中包括了 API 密钥。最后,我们检查响应的状态代码,并将响应数据转换为 Python 对象,以便进一步处理。

OpenAI API 使用 JSON 发送请求:Python 示例

原文地址: https://www.cveoy.top/t/topic/lBsT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录