Gemini API クイックスタート

このクイックスタートでは、任意の SDK を使用して Gemini API の使用を開始する方法を説明します。

前提条件

Python

Google AI で表示 Google Colab で実行 GitHub のノートブックを表示

このクイックスタートをローカルで完了するには、開発環境が次の要件を満たしていることを確認してください。

  • Python 3.9 以降
  • ノートブックを実行するための jupyter のインストール。

Go

このクイックスタートは、Go を使用したアプリケーションのビルドに精通していることを前提としています。

このクイックスタートを完了するには、開発環境が次の要件を満たしていることを確認してください。

  • Go 1.20 以降

Node.js

このクイックスタートは、Node.js を使用したアプリケーションのビルドに精通していることを前提としています。

このクイックスタートを完了するには、開発環境が次の要件を満たしていることを確認してください。

  • Node.js v18 以降
  • npm

ウェブ

このクイックスタートは、JavaScript を使用したウェブアプリの開発に精通していることを前提としています。このガイドはフレームワークに依存しません。

このクイックスタートを完了するには、開発環境が次の要件を満たしていることを確認してください。

  • (省略可)Node.js
  • 最新のウェブブラウザ

Dart(Flutter)

このクイックスタートは、Dart を使用したアプリケーションの構築に精通していることを前提としています。

このクイックスタートを完了するには、開発環境が次の要件を満たしていることを確認してください。

  • Dart 3.2.0 以降

Swift

このクイックスタートは、Xcode を使用した Swift アプリの開発に精通していることを前提としています。

このクイックスタートを完了するには、開発環境と Swift アプリが次の要件を満たしていることを確認してください。

  • Xcode 15.0 以降
  • Swift アプリは、iOS 15 以降または macOS 12 以降を対象にする必要があります。

Android

このクイックスタートは、Android Studio を使用した Android アプリの開発に精通していることを前提としています。

このクイックスタートを完了するには、開発環境と Android アプリが次の要件を満たしていることを確認してください。

  • Android Studio(最新バージョン)
  • Android アプリは API レベル 21 以降を対象にする必要があります。

API キーを設定する

Gemini API を使用するには、API キーが必要です。まだ作成していない場合は、Google AI Studio でキーを作成します。

API キーを取得する

次に、鍵を構成します。

Python

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。このクイックスタートでは、環境変数として API キーにアクセスすることを前提としています。

API キーを環境変数に割り当てます。

export API_KEY=<YOUR_API_KEY>

Go

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。このクイックスタートでは、環境変数として API キーにアクセスすることを前提としています。

API キーを環境変数に割り当てます。

export API_KEY=<YOUR_API_KEY>

Node.js

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。このクイックスタートでは、環境変数として API キーにアクセスすることを前提としています。

API キーを環境変数に割り当てます。

export API_KEY=<YOUR_API_KEY>

ウェブ

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。代わりに、モデルを初期化する直前に API キーをアプリに渡す必要があります。

このクイックスタートでは、グローバル定数として API キーにアクセスすることを前提としています。

Dart(Flutter)

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。このクイックスタートでは、プロセス環境変数として API キーにアクセスすることを前提としています。Flutter アプリを開発している場合は、アプリの実行時にプロセス環境が異なるため、String.fromEnvironment を使用して --dart-define=API_KEY=$API_KEYflutter build または flutter run に渡して API キーでコンパイルできます。

Swift

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。もう 1 つの方法は、GenerativeAI-Info.plist ファイルに保存し、.plist ファイルから API キーを読み取ることです。この .plist ファイルをアプリのルートフォルダに配置し、バージョン管理から除外してください。

enum APIKey {
   // Fetch the API key from `GenerativeAI-Info.plist`
   static var `default`: String {
      guard let filePath = Bundle.main.path(forResource: "GenerativeAI-Info", ofType: "plist")
      else {
         fatalError("Couldn't find file 'GenerativeAI-Info.plist'.")
      }
      let plist = NSDictionary(contentsOfFile: filePath)
      guard let value = plist?.object(forKey: "API_KEY") as? String else {
         fatalError("Couldn't find key 'API_KEY' in 'GenerativeAI-Info.plist'.")
      }
      if value.starts(with: "_") {
         fatalError(
           "Follow the instructions at https://ai.google.dev/tutorials/setup to get an API key."
         )
      }
      return value
   }
}

Android

API キーはバージョン管理システムにチェックインしないことを強くおすすめします。代わりに、local.properties ファイル(プロジェクトのルート ディレクトリにありますが、バージョン管理から除外します)に保存し、Android 用 Secrets Gradle プラグインを使用して API キーをビルド構成変数として読み取る必要があります。

Kotlin:

// Access your API key as a Build Configuration variable
val apiKey = BuildConfig.apiKey

Java:

// Access your API key as a Build Configuration variable
String apiKey = BuildConfig.apiKey;

Secrets Gradle プラグインの実装を確認するには、この SDK のサンプルアプリを参照するか、Gemini API Starter テンプレート(使用を開始するための local.properties ファイルが含まれています)を含む Android Studio Iguana の最新プレビューを使用できます。

SDK をインストールする

Python

Gemini API 用の Python SDK は、google-generativeai パッケージに含まれています。pip を使用して依存関係をインストールします。

pip install -q -U google-generativeai

Go

独自のアプリケーションで Gemini API を使用するには、モジュール ディレクトリで Go SDK パッケージを get する必要があります。

go get github.com/google/generative-ai-go

Node.js

独自のアプリケーションで Gemini API を使用するには、Node.js 用の GoogleGenerativeAI パッケージをインストールする必要があります。

npm install @google/generative-ai

ウェブ

独自のウェブアプリで Gemini API を使用するには、@google/generative-ai をインポートします。

<script type="importmap">
   {
     "imports": {
       "@google/generative-ai": "https://esm.run/@google/generative-ai"
     }
   }
</script>

Dart(Flutter)

独自のアプリケーションで Gemini API を使用するには、Dart または Flutter アプリに google_generative_ai パッケージを add する必要があります。

Dart:

dart pub add google_generative_ai

Flutter:

flutter pub add google_generative_ai

Swift

独自の Swift アプリで Gemini API を使用するには、GoogleGenerativeAI パッケージをアプリに追加します。

  1. Xcode で、プロジェクト ナビゲータのプロジェクトを右クリックします。

  2. コンテキスト メニューから [Add Packages] を選択します。

  3. [Add Packages] ダイアログで、検索バーにパッケージの URL を貼り付けます。none https://github.com/google/generative-ai-swift

  4. [パッケージを追加] をクリックします。Xcode が GoogleGenerativeAI パッケージをプロジェクトに追加します。

Android

  1. モジュール(アプリレベル)の Gradle 構成ファイル(<project>/<app-module>/build.gradle.kts など)に、Google AI SDK for Android の依存関係を追加します。

    Kotlin:

    dependencies {
    
       // add the dependency for the Google AI client SDK for Android
       implementation("com.google.ai.client.generativeai:generativeai:0.3.0")
    }
    

    Java:

    Java の場合は、ライブラリを 2 つ追加する必要があります。

    dependencies {
    
        // add the dependency for the Google AI client SDK for Android
        implementation("com.google.ai.client.generativeai:generativeai:0.3.0")
    
        // Required for one-shot operations (to use `ListenableFuture` from Guava Android)
        implementation("com.google.guava:guava:31.0.1-android")
    
        // Required for streaming operations (to use `Publisher` from Reactive Streams)
        implementation("org.reactivestreams:reactive-streams:1.0.4")
    }
    
  2. Android プロジェクトと Gradle ファイルを同期する。

生成モデルを初期化する

Python

API 呼び出しを行うには、生成モデルをインポートして初期化しておく必要があります。

import google.generativeai as genai

genai.configure(api_key=os.environ["API_KEY"])
model = genai.GenerativeModel('gemini-pro')

Go

API 呼び出しを行うには、生成モデルをインポートして初期化しておく必要があります。

import "github.com/google/generative-ai-go/genai"
import "google.golang.org/api/option"

ctx := context.Background()
// Access your API key as an environment variable (see "Set up your API key" above)
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// For text-only input, use the gemini-pro model
model := client.GenerativeModel("gemini-pro")

Node.js

API 呼び出しを行うには、生成モデルをインポートして初期化しておく必要があります。

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// ...

// For text-only input, use the gemini-pro model
const model = genAI.getGenerativeModel({ model: "gemini-pro"});

// ...

ウェブ

API 呼び出しを行うには、生成モデルをインポートして初期化しておく必要があります。

<html>
<body>
   <!-- ... Your HTML and CSS -->
   <!-- Import @google/generative-ai, as shown above. -->
   <script type="module">
      import { GoogleGenerativeAI } from "@google/generative-ai";

      // Fetch your API_KEY
      const API_KEY = "...";

      // Access your API key (see "Set up your API key" above)
      const genAI = new GoogleGenerativeAI(API_KEY);

      // ...

      // For text-only input, use the gemini-pro model
      const model = genAI.getGenerativeModel({ model: "gemini-pro"});

      // ...
   </script>
</body>
</html>

Dart(Flutter)

API 呼び出しを行うには、生成モデルをインポートして初期化しておく必要があります。

import 'package:google_generative_ai/google_generative_ai.dart';

// Access your API key as an environment variable (see "Set up your API key" above)
final apiKey = Platform.environment['API_KEY'];
if (apiKey == null) {
  print('No \$API_KEY environment variable');
  exit(1);
}

// For text-only input, use the gemini-pro model
final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);

Swift

API 呼び出しを行う前に、生成モデルを初期化する必要があります。

  1. GoogleAI モジュールをインポートします。

    import GoogleGenerativeAI
    
  2. 生成モデルを初期化します。

    // For text-only input, use the gemini-pro model
    // Access your API key from your on-demand resource .plist file (see "Set up your API key" above)
    let model = GenerativeModel(name: "gemini-pro", apiKey: APIKey.default)
    

Android

API 呼び出しを行うには、その前に GenerativeModel オブジェクトを初期化する必要があります。

Kotlin:

val generativeModel = GenerativeModel(
      // For text-only input, use the gemini-pro model
      modelName = "gemini-pro",
      // Access your API key as a Build Configuration variable (see "Set up your API key" above)
      apiKey = BuildConfig.apiKey
)

Java:

Java の場合は、GenerativeModelFutures オブジェクトを初期化する必要もあります。

// For text-only input, use the gemini-pro model
GenerativeModel gm = new GenerativeModel(/* modelName */ "gemini-pro",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
      /* apiKey */ BuildConfig.apiKey);

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(gm);

テキストを生成

Python

response = model.generate_content("Write a story about a magic backpack.")
print(response.text)

Go

resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
  log.Fatal(err)
}

Node.js

async function run() {
  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

ウェブ

async function run() {
  const prompt = "Write a story about a magic backpack."

  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart(Flutter)

void main() async {
   // Access your API key as an environment variable (see "Set up your API key" above)
   final apiKey = Platform.environment['API_KEY'];
   if (apiKey == null) {
      print('No \$API_KEY environment variable');
      exit(1);
   }
   // For text-only input, use the gemini-pro model
   final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
   final content = [Content.text('Write a story about a magic backpack.')];
   final response = await model.generateContent(content);
   print(response.text);
}

Swift

let prompt = "Write a story about a magic backpack."
let response = try await model.generateContent(prompt)
if let text = response.text {
  print(text)
}

Android

Kotlin:

generateContent() は suspend 関数であり、コルーチン スコープから呼び出す必要があります。コルーチンに慣れていない場合は、Android での Kotlin コルーチンをご覧ください。

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

Java:

generateContent()ListenableFuture を返します。この API を使い慣れていない場合は、Android のドキュメントで ListenableFuture の使用に関する説明をご覧ください。

Content content = new Content.Builder()
      .addText("Write a story about a magic backpack.")
      .build();

Executor executor = // ...

ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
         String resultText = result.getText();
         System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
         t.printStackTrace();
      }
}, executor);

次のステップ

Gemini API の操作について詳しくは、ご使用の言語のチュートリアルをご覧ください。

curl コマンドを使用して Gemini API を試すこともできます。

生成 AI モデルを初めて使用する場合は、クイックスタートを試す前にコンセプト ガイドGemini API の概要をご覧ください。