Gemini AIをLaravelで使用する

Gemini AIをLaravelで使用する

Gemini AIは、Google AIによって開発された大規模言語モデルです。テキスト生成、翻訳、質問応答など、様々なタスクを実行することができます。このブログ記事では、Laravelフレームワークを使ってGemini AIを使用する方法を紹介します。

構築環境

  • Laravel 9.0|^10.0|^11.0
  • PHP ^8.1.0

インストール

まず、Composerを使ってGemini AIのLaravelパッケージをインストールします。

$ composer require google-gemini-php/laravel

次にインストールコマンドを実行します。

$php artisan gemini:install

APIキーの設定

Gemini AIを使用するには、APIキーが必要です。これを環境変数.envファイルに設定します。

GEMINI_API_KEY=your_api_key_here

使い方

Gemini AIと対話する基本的な方法は以下の通りです。

use Gemini\Laravel\Facades\Gemini;

$result = Gemini::geminiPro()->generateContent('Hello');

$result->text(); // Hello! How can I assist you today?

Gemini Proバージョンモデルを使用して画像とテキストで対話する例:

$result = Gemini::geminiProVision()
 ->generateContent([
  'What is this picture?',
  new Blob(
   mimeType: MimeType::IMAGE_JPEG,
   data: base64_encode(
    file_get_contents('https://storage.googleapis.com/generativeai-downloads/images/scones.jpg')
   )
  )
 ]);
 
$result->text(); //  The picture shows a table with a white tablecloth. On the table are two cups of coffee, a bowl of blueberries, a silver spoon, and some flowers. There are also some blueberry scones on the table.

その他、トークンの計算やストリーミングなどにも対応しています。

おわりに

この記事で、Laravelを使用してGemini AIを効果的に利用するための基本的なガイドを提供しました。さらに詳細な実装方法や最新の情報については、公式のGemini AIドキュメントとLaravelドキュメントを参照してください。

参考文献