要用PHP使用ChatGPT API,你可以按照以下步骤进行:
首先,你需要创建一个可以向API端点发送请求的HTTP客户端。为此,你可以使用PHP内置的curl库。下面是一个例子的代码片段:
// Create a new cURL resource
$ch = curl_init();
// Set the API endpoint URL
$url = "https://api.openai.com/v1/engine/davinci-codex/completions";
// Set the request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer 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"
);
// Set the request data
$data = array(
"prompt" => "Hello, how are you?",
"max_tokens" => 5
);
// Set the cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Send the request and get the response
$response = curl_exec($ch);
// Close the cURL resource
curl_close($ch);
// Print the response
echo $response;
在这个代码片段中,我们正在创建一个新的cURL资源,并设置API端点的URL、请求头和请求数据。然后我们设置cURL选项并使用curl_exec函数发送请求。最后,我们要打印响应。
你可以修改$data数组以包括你自己的提示和参数。例如,你可以设置温度参数来控制生成文本的创造力。
你可以解析响应的JSON来提取生成的文本。比如说
// Parse the response JSON
$response_data = json_decode($response, true);
// Get the generated text
$generated_text = $response_data["choices"][0]["text"];
// Print the generated text
echo $generated_text;
在这个代码片段中,我们使用json_decode函数解析响应的JSON,并从响应数据中提取生成的文本。然后,我们正在打印生成的文本。
我希望这能帮助你开始用PHP使用ChatGPT API!