PHP 使用 cURL 调用 ChatGPT 文件 API 上传和获取文件列表
要调用 ChatGPT 的文件 API,您需要使用 PHP 中的 cURL 函数。以下是一个示例代码来调用 ChatGPT 的文件 API:
<?php
$apiKey = 'YOUR_API_KEY';
$url = 'https://api.openai.com/v1/files';
// 文件上传
$file = '/path/to/your/file.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'file' => new CURLFile($file),
]);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
]);
$response = curl_exec($ch);
curl_close($ch);
// 获取文件列表
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
]);
$response = curl_exec($ch);
curl_close($ch);
// 处理响应数据
$data = json_decode($response, true);
if (isset($data['data'])) {
foreach ($data['data'] as $file) {
echo $file['id'] . ': ' . $file['filename'] . "\n";
}
} else {
echo 'Error: ' . $data['error']['message'];
}
请确保将YOUR_API_KEY替换为您的 OpenAI API 密钥,并将/path/to/your/file.txt替换为要上传的文件路径。此代码示例首先将文件上传到 ChatGPT 的文件 API,然后获取文件列表并打印出每个文件的 ID 和文件名。请根据您的需求修改代码。
原文地址: https://www.cveoy.top/t/topic/qvUe 著作权归作者所有。请勿转载和采集!