0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PHPからGemini APIを使う

Posted at

はじめに

エンジニア兼プログラミング講師をしているmei_13と申します。
運用しているホームページにてPHPでGemini APIを使うことがあったので、関数化して使いやすくしました。
(prompt.jsonが生成されるので注意!!)
ご利用は自己責任でお願いします。また、例外処理はご自身で付け加えてご利用ください。

コード

function ReplyGemini($prompt, $gemini_api_key){
    $prompt_json = []; 
    $prompt_json["contents"]["parts"]["text"] = $prompt;
  
    $prompt_json = json_encode($prompt_json, JSON_PRETTY_PRINT);
 
    file_put_contents("prompt.json", $prompt_json);
 
    $curl_script = <<<EOM
    curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" \
    -H 'x-goog-api-key: $gemini_api_key' \
    -H 'Content-Type: application/json' \
    -X POST \
    -d@prompt.json \
EOM;
 
    exec($curl_script, $output, $ret);
 
    $output = implode("\n", $output);
 
    $json = json_decode($output, true);
    $text = $json["candidates"][0]["content"]["parts"][0]["text"];
 
    return($text);
}

$GEMINI_API_KEY = "YOUR API KEY";
$prompt = "こんにちは";
$rep = ReplyGemini($prompt, $GEMINI_API_KEY);

おわりに

Gemini APIは無料枠も大きく、他の生成AIに比べてとっつきやすいと思います。
最初に生成AIのAPIを使ってみようと思う方はおすすめです。

生成AIを活用しているホームページも増えてきましたね。
機会があれば私が運用しているホームページもご紹介したいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?