<!-- language: lang-html -->
<?php
function generateAIContent($apiKey, $prompt) {
$url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key={$apiKey}";
$postData = json_encode([
"contents" => [
[
"parts" => [
["text" => $prompt]
]
]
],
"generationConfig" => [
"temperature" => 0.9,
"topK" => 1,
"topP" => 1,
"maxOutputTokens" => 2000,
"stopSequences" => []
],
"safetySettings" => [
[
"category" => "HARM_CATEGORY_HARASSMENT",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_HATE_SPEECH",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold" => "BLOCK_ONLY_HIGH"
],
[
"category" => "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold" => "BLOCK_ONLY_HIGH"
]
]
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
]);
$response = curl_exec($ch);
curl_close($ch);
$responseData = json_decode($response, true);
if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
return $responseData['candidates'][0]['content']['parts'][0]['text'];
} else {
return "No generated text found.";
}
}
$apiKey="--------------";
$prompt="--------------";
$generatedText = generateAIContent($apiKey, $prompt);
echo $generatedText;
?>
<!-- end snippet -->
在本地计算机上测试时,此代码成功连接到 Gemini API 并返回所需的结果(即返回提示中问题的答案),但是当移动到实时服务器时(它不会返回问题的答案)在提示中返回“未找到生成的文本。”)。 我不明白为什么,你们有什么想法吗? api key 有问题还是服务器有问题。 我在许多不同的服务器上尝试了此操作,但没有返回来自 Gemini API 的响应。 但它会在我的本地机器上完美地返回答案。
我在本地主机上运行代码,它能够连接到 Gemini API 并返回提示中问题的答案。 我将代码移至实时服务器(免费 PHP 托管服务),但那里的代码无法返回提示中问题的答案。