Generative API の概要

Gemini API を使用すると、Google の最新の生成モデルにアクセスできます。API で使用できる一般的な機能を把握したら、使用言語のチュートリアルで開発を始めましょう。

モデル

Gemini は、Google が開発した一連のマルチモーダル生成 AI モデルです。Gemini モデルは、選択したモデル バリエーションに応じて、プロンプトにテキストと画像を受け入れ、テキスト レスポンスを出力できます。

詳細なモデル情報については、Gemini モデルのページをご覧ください。また、list_models メソッドを使用して使用可能なすべてのモデルを一覧表示し、get_model メソッドを使用して特定のモデルのメタデータを取得することもできます。

プロンプトのデータと設計

特定の Gemini モデルでは、テキストデータとメディア ファイルの両方を入力として受け付けます。この機能により、コンテンツの生成、データの分析、問題解決の可能性がさらに広がります。使用しているモデルの一般的な入力トークンの上限など、考慮すべき制限事項と要件がいくつかあります。特定のモデルのトークンの上限については、Gemini モデルをご覧ください。

Gemini API を使用したプロンプトのサイズは 20 MB 以下にする必要があります。Gemini API には、プロンプトで使用するメディア ファイルを一時的に保存する File API が用意されています。これにより、20 MB の上限を超えるプロンプト データを提供できます。Files API とプロンプトでサポートされているファイル形式の使用方法については、メディア ファイルを使用したプロンプト表示をご覧ください。

プロンプト設計とテキスト入力

効果的なプロンプトの作成、つまりプロンプト エンジニアリングは、芸術と科学を組み合わせたものです。プロンプトの作成方法については、プロンプトの概要をご覧ください。また、プロンプトの各種方法については、プロンプトの概要ガイドをご覧ください。

コンテンツの生成

Gemini API では、使用するモデル バリエーションに応じて、テキストデータと画像データの両方をプロンプトに使用できます。たとえば、gemini-pro モデルではテキスト プロンプトを使用してテキストを生成し、gemini-pro-vision モデルではテキストデータと画像データの両方を使用してプロンプトを作成できます。このセクションでは、それぞれの簡単なコード例を示します。 すべてのパラメータを網羅した詳細な例については、generateContent API リファレンスをご覧ください。

テキストと画像の入力

画像を含むテキスト プロンプトを gemini-pro-vision モデルに送信して、ビジョン関連のタスクを実行できます。たとえば、画像にキャプションを付ける、画像の内容を特定するなどします。

次のコードサンプルは、サポートされている各言語のテキストと画像のプロンプトの簡単な実装を示しています。

Python

model = genai.GenerativeModel('gemini-pro-vision')

cookie_picture = [{
    'mime_type': 'image/png',
    'data': pathlib.Path('cookie.png').read_bytes()
}]
prompt = "Do these look store-bought or homemade?"

response = model.generate_content(
    model="gemini-pro-vision",
    content=[prompt, cookie_picture]
)
print(response.text)

完全なコード スニペットについては、Python チュートリアルをご覧ください。

Go

vmodel := client.GenerativeModel("gemini-pro-vision")

data, err := os.ReadFile(filepath.Join("path-to-image", imageFile))
if err != nil {
  log.Fatal(err)
}
resp, err := vmodel.GenerateContent(ctx, genai.Text("Do these look store-bought or homemade?"), genai.ImageData("jpeg", data))
if err != nil {
  log.Fatal(err)
}

詳細な例については、Go のチュートリアルをご覧ください。

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-pro-vision" });

const prompt = "Do these look store-bought or homemade?";
const image = {
  inlineData: {
    data: Buffer.from(fs.readFileSync("cookie.png")).toString("base64"),
    mimeType: "image/png",
  },
};

const result = await model.generateContent([prompt, image]);
console.log(result.response.text());

完全な例については、Node.js チュートリアルをご覧ください。

ウェブ

const model = genAI.getGenerativeModel({ model: "gemini-pro-vision" });

const prompt = "Do these look store-bought or homemade?";
const image = {
  inlineData: {
    data: base64EncodedImage /* see JavaScript quickstart for details */,
    mimeType: "image/png",
  },
};

const result = await model.generateContent([prompt, image]);
console.log(result.response.text());

詳細な例については、ウェブ チュートリアルをご覧ください。

Dart(Flutter)

final model = GenerativeModel(model: 'gemini-pro-vision', apiKey: apiKey);
final prompt = 'Do these look store-bought or homemade?';
final imageBytes = await File('cookie.png').readAsBytes();
final content = [
  Content.multi([
    TextPart(prompt),
    DataPart('image/png', imageBytes),
  ])
];

final response = await model.generateContent(content);
print(response.text);

詳細な例については、Dart(Flutter)のチュートリアルをご覧ください。

Swift

let model = GenerativeModel(name: "gemini-pro-vision", apiKey: "API_KEY")
let cookieImage = UIImage(...)
let prompt = "Do these look store-bought or homemade?"

let response = try await model.generateContent(prompt, cookieImage)

詳細な例については、Swift チュートリアルをご覧ください。

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-pro-vision",
    apiKey = BuildConfig.apiKey
)

val cookieImage: Bitmap = // ...
val inputContent = content() {
  image(cookieImage)
  text("Do these look store-bought or homemade?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)

詳細な例については、Android チュートリアルをご覧ください。

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-pro-vision:generateContent?key=${API_KEY} \
    -H 'Content-Type: application/json' \
    -X POST \
    -d @<(echo'{
          "contents":[
            { "parts":[
                {"text": "Do these look store-bought or homemade?"},
                { "inlineData": {
                    "mimeType": "image/png",
                    "data": "'$(base64 -w0 cookie.png)'"
                  }
                }
              ]
            }
          ]
         }')

詳細については、REST API チュートリアルをご覧ください。

テキストのみの入力

Gemini API は、テキストのみの入力を処理することもできます。この機能を使用すると、テキスト補完や要約などの自然言語処理(NLP)タスクを実行できます。

次のコードサンプルは、サポートされている各言語のテキストのみのプロンプトの簡単な実装を示しています。

Python

model = genai.GenerativeModel('gemini-pro-vision')

prompt = "Write a story about a magic backpack."

response = model.generate_content(prompt)

完全な例については、Python のチュートリアルをご覧ください。

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

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

詳細な例については、Go のチュートリアルをご覧ください。

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = "Write a story about a magic backpack.";

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

完全な例については、Node.js チュートリアルをご覧ください。

ウェブ

const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = "Write a story about a magic backpack.";

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

詳細な例については、ウェブ チュートリアルをご覧ください。

Dart(Flutter)

final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
final prompt = 'Write a story about a magic backpack.';
final content = [Content.text(prompt)];
final response = await model.generateContent(content);
print(response.text);

詳細な例については、Dart(Flutter)のチュートリアルをご覧ください。

Swift

let model = GenerativeModel(name: "gemini-pro", apiKey: "API_KEY")
let prompt = "Write a story about a magic backpack."

let response = try await model.generateContent(prompt)

詳細な例については、Swift チュートリアルをご覧ください。

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-pro",
    apiKey = BuildConfig.apiKey
)

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

詳細な例については、Android チュートリアルをご覧ください。

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{ "contents":[
      { "parts":[{"text": "Write a story about a magic backpack"}]}
    ]
}'

詳細については、REST API チュートリアルをご覧ください。

マルチターンの会話(チャット)

Gemini API を使用すると、インタラクティブなチャット体験をユーザーに提供できます。API のチャット機能を使用すると、複数の質問と回答を収集できます。これにより、ユーザーは回答に段階的に進むことや、マルチパートの問題でサポートを受けることができます。この機能は、chatbot、インタラクティブ チューター、カスタマー サポート アシスタントなど、継続的な通信が必要なアプリケーションに最適です。

次のコードサンプルは、サポートされている各言語のチャット操作を簡単に実装する方法を示しています。

Python

  model = genai.GenerativeModel('gemini-pro')
  chat = model.start_chat(history=[])

  response = chat.send_message(
      "Pretend you\'re a snowman and stay in character for each response.")
  print(response.text)

  response = chat.send_message(
      "What\'s your favorite season of the year?")
  print(response.text)

詳細な例については、Python チュートリアルのチャットのデモをご覧ください。

Go

model := client.GenerativeModel("gemini-pro")
cs := model.StartChat()
cs.History = []*genai.Content{
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Pretend you're a snowman and stay in character for each response."),
    },
    Role: "user",
  },
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Hello! It's cold! Isn't that great?"),
    },
    Role: "model",
  },
}

resp, err := cs.SendMessage(ctx, genai.Text("What's your favorite season of the year?"))
if err != nil {
  log.Fatal(err)
}

詳細な例については、Go チュートリアルのチャットデモをご覧ください。

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-pro"});

const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: "Pretend you're a snowman and stay in character for each response.",
    },
    {
      role: "model",
      parts: "Hello! It's cold! Isn't that great?",
    },
  ],
  generationConfig: {
    maxOutputTokens: 100,
  },
});

const msg = "What's your favorite season of the year?";
const result = await chat.sendMessage(msg);
console.log(result.response.text());

詳細な例については、Node.js チュートリアルのチャットデモをご覧ください。

ウェブ

const model = genAI.getGenerativeModel({ model: "gemini-pro"});

const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: "Pretend you're a snowman and stay in character for each response.",
    },
    {
      role: "model",
      parts: "Hello! It's so cold! Isn't that great?",
    },
  ],
  generationConfig: {
    maxOutputTokens: 100,
  },
});

const msg = "What's your favorite season of the year?";
const result = await chat.sendMessage(msg);
console.log(result.response.text());

詳細な例については、ウェブ チュートリアルのチャットデモをご覧ください。

Dart(Flutter)

final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
final chat = model.startChat(history: [
  Content.text(
      "Pretend you're a snowman and stay in character for each response."),
  Content.model([TextPart("Hello! It's cold! Isn't that great?")]),
]);
final content = Content.text("What's your favorite season of the year?");
final response = await chat.sendMessage(content);
print(response.text);

詳細な例については、Dart(Flutter)チュートリアルのチャットデモをご覧ください。

Swift

let model = GenerativeModel(name: "gemini-pro", apiKey: "API_KEY")
let chat = model.startChat()

var message = "Pretend you're a snowman and stay in character for each response."
var response = try await chat.sendMessage(message)

message = "What\'s your favorite season of the year?"
response = try await chat.sendMessage(message)

詳細な例については、Swift チュートリアルのチャットデモをご覧ください。

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-pro",
    apiKey = BuildConfig.apiKey
)

val chat = generativeModel.startChat()
val response = chat.sendMessage("Pretend you're a snowman and stay in
        character for each response.")
print(response.text)

詳細な例については、Android チュートリアルをご覧ください。

cURL

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Pretend you're a snowman and stay in character for each
        {"role": "model",
            response."}]},
         "parts":[{
           "text": "Hello! It's so cold! Isn't that great?"}]},
        {"role": "user",
         "parts":[{
           "text": "What\'s your favorite season of the year?"}]},
       ]
    }' 2> /dev/null | grep "text"
# response example:
"text": "Winter, of course!"

詳細については、REST API チュートリアルをご覧ください。

ストリーミングされた回答

Gemini API は、生成 AI モデルからのレスポンスを受信する別の方法(データ ストリーム)を提供します。ストリーミングされたレスポンスでは、モデルによって生成されたデータの増分部分がアプリケーションに返されます。この機能を使用すると、ユーザーのリクエストにすばやく応答して進行状況を表示し、よりインタラクティブなエクスペリエンスを実現できます。

レスポンスのストリーミングは、Gemini モデルでの自由形式のプロンプトとチャットのオプションです。次のコード例は、サポートされている各言語のプロンプトに対してストリーミングされたレスポンスをリクエストする方法を示しています。

Python

prompt = "Write a story about a magic backpack."

response = genai.stream_generate_content(
    model="models/gemini-pro",
    prompt=prompt
)

完全なコード スニペットについては、Python チュートリアルをご覧ください。

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-pro")

iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }

  // print resp
}

詳細な例については、Go のチュートリアルをご覧ください。

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream([prompt]);
// print text as it comes in
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  console.log(chunkText);
}

完全な例については、Node.js チュートリアルをご覧ください。

ウェブ

const model = genAI.getGenerativeModel({ model: "gemini-pro" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream([prompt]);
// print text as it comes in
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  console.log(chunkText);
}

詳細な例については、ウェブ チュートリアルをご覧ください。

Dart(Flutter)

final model = GenerativeModel(model: 'gemini-pro', apiKey: apiKey);
final prompt = 'Write a story about a magic backpack.';
final content = [Content.text(prompt)];
final response = model.generateContentStream(content);
await for (final chunk in response) {
  print(chunk.text);
}

詳細な例については、Dart(Flutter)のチュートリアルをご覧ください。

Swift

let model = GenerativeModel(name: "gemini-pro", apiKey: "API_KEY")
let prompt = "Write a story about a magic backpack."

let stream = model.generateContentStream(prompt)
for try await chunk in stream {
  print(chunk.text ?? "No content")
}

詳細な例については、Swift チュートリアルをご覧ください。

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-pro",
    apiKey = BuildConfig.apiKey
)

val inputContent = content {
  text("Write a story about a magic backpack.")
}

var fullResponse = ""
generativeModel.generateContentStream(inputContent).collect { chunk ->
  print(chunk.text)
  fullResponse += chunk.text
}

詳細な例については、Android チュートリアルをご覧ください。

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-pro:streamGenerateContent?key=${API_KEY} \
    -H 'Content-Type: application/json' \
    --no-buffer \
    -d '{ "contents":[
            {"role": "user",
              "parts":[{"text": "Write a story about a magic backpack."}]
            }
          ]
        }' > response.json

詳細については、REST API チュートリアルをご覧ください。

JSON 形式のレスポンス

アプリケーションによっては、プロンプトに対するレスポンスを構造化データ形式で返す必要がある場合があります。特に、レスポンスを使用してプログラミング インターフェースにデータを入力する場合は、このようになります。Gemini API には、JSON 形式のレスポンスをリクエストするための構成パラメータが用意されています。

この出力機能を使用するには、response_mime_type 構成オプションを application/json に設定し、リクエストの本文に JSON 形式の仕様を含めます。次のコード例は、プロンプトに対する JSON レスポンスをリクエストする方法を示しています。

cURL

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{ "contents":[{
            "parts":[{"text": "List 5 popular cookie recipes using this JSON schema: \{ \"type\": \"object\", \"properties\": \{ \"recipe_name\": \{ \"type\": \"string\" \},\}\}"}] }],
          "generationConfig": {
            "response_mime_type": "application/json",
          } }'

エンベディング

Gemini API のエンベディング サービスは、単語、フレーズ、文に対する最先端のエンベディングを生成します。生成されたエンベディングは、セマンティック検索、テキスト分類、クラスタリングなどの NLP タスクに使用できます。エンベディングの概要と、エンベディング サービスの主なユースケースについては、エンベディング ガイドをご覧ください。

次のステップ