PHP 调用 OpenAI Embeddings API 实现对话 - 完整代码示例
以下是一个使用 PHP 调用 OpenAI 的 Embeddings API 进行对话的示例代码:
<?php
// 设置 OpenAI API 的访问密钥
$apiKey = 'YOUR_API_KEY';
// 定义函数来调用 OpenAI API
function callOpenAI($url, $data, $apiKey) {
$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, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
]);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
// 定义函数来与 OpenAI 进行对话
function chatWithOpenAI($message, $apiKey) {
// 构建 API 请求数据
$data = json_encode([
'messages' => [['role' => 'system', 'content' => 'You are a helpful assistant.']],
'additional_context' => [['role' => 'system', 'content' => $message]],
'model' => 'gpt-3.5-turbo',
'max_tokens' => 100,
'stop' => ['\n']
]);
// 调用 OpenAI API
$response = callOpenAI('https://api.openai.com/v1/engines/davinci-codex/completions', $data, $apiKey);
// 解析 API 响应
$responseData = json_decode($response, true);
$choices = $responseData['choices'];
if (count($choices) > 0) {
$reply = $choices[0]['text'];
return $reply;
} else {
return 'No response from the API.';
}
}
// 使用示例
$message = 'What is the capital of France?';
$reply = chatWithOpenAI($message, $apiKey);
echo 'Chatbot: ' . $reply;
?>
请将 YOUR_API_KEY 替换为您的 OpenAI API 密钥。您可以在 OpenAI 网站上创建一个帐户并获取 API 密钥。
这个示例代码定义了两个函数,callOpenAI 用于调用 OpenAI API,chatWithOpenAI 用于与 OpenAI 进行对话。chatWithOpenAI 函数接受一个用户消息和 API 密钥作为输入,并返回与用户消息相关的 OpenAI 回复。
在示例中,我们使用了 GPT-3.5 Turbo 模型进行对话。您可以根据需要更改模型名称。
要使用该示例,请将用户消息存储在 $message 变量中,并将其传递给 chatWithOpenAI 函数。然后,将 OpenAI 的回复存储在 $reply 变量中,并使用 echo 语句将其输出。
请注意,OpenAI API 的使用是按次计费的。确保您的 API 密钥具有足够的配额以支持您的应用程序。
原文地址: https://www.cveoy.top/t/topic/bdko 著作权归作者所有。请勿转载和采集!