> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aihubmix.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini ネイティブ SDK 統合

> @google/genai SDK を使用して AIHubMix に接続し、Interactions、Embeddings、Context Caching など Gemini API のすべてのネイティブ機能を呼び出す

## 概要

Google は `@google/genai`（JavaScript / TypeScript）と `google-genai`（Python）の 2 つの公式 SDK を提供しており、Gemini API のすべてのエンドポイントをカバーしています。`baseUrl` を AIHubMix ゲートウェイに向け、プラットフォームの API Key に置き換えるだけで、ネイティブ SDK を通じて Interactions、Embeddings、Context Caching など OpenAI 互換レイヤーではカバーされない機能を呼び出すことができます。ビジネスコードの変更は一切不要です。

## クイックスタート

### インストール

<CodeGroup>
  ```bash JavaScript / TypeScript theme={null}
  npm install @google/genai
  # >= 2.0.0 が必要です。latest のインストールを推奨
  ```

  ```bash Python theme={null}
  pip install -U google-genai
  # >= 2.0.0 が必要です
  ```
</CodeGroup>

<Warning>
  Interactions API は `@google/genai` **>= 2.0.0** または `google-genai` **>= 2.0.0** が必要です。古いバージョンの SDK からのリクエストは Google バックエンドに拒否されます（`legacy Interactions schema no longer supported`）。
</Warning>

### クライアントの初期化

<CodeGroup>
  ```js JavaScript theme={null}
  import { GoogleGenAI } from "@google/genai";

  const ai = new GoogleGenAI({
    apiKey: "sk-***", // AIHubMix で生成した API Key に置き換えてください
    httpOptions: {
      baseUrl: "https://aihubmix.com/gemini",
    },
  });
  ```

  ```python Python theme={null}
  from google import genai

  client = genai.Client(
      api_key="sk-***",  # AIHubMix で生成した API Key に置き換えてください
      http_options={"base_url": "https://aihubmix.com/gemini"},
  )
  ```
</CodeGroup>

<Tip>
  `baseUrl` は `https://aihubmix.com/gemini` に固定されており、OpenAI 互換エンドポイント `https://aihubmix.com/v1` とは異なります。
</Tip>

***

## Interactions API

Interactions は Gemini の新世代推論インターフェースで、構造化された `Interaction` オブジェクトを返し、テキスト生成、ネイティブ画像生成（Nano Banana）、マルチステップ推論をサポートします。現在は**同期モード**（`interactions.create()`）をサポートしています。非同期モード（Background Interactions：`get` / `cancel` / `delete`）は近日公開予定です。

### テキスト生成

`interactions.create()` を呼び出して推論を開始します。返される `Interaction` オブジェクトは `output_text` 便利プロパティを提供し、モデルの最後のテキスト出力を直接取得できます。

<CodeGroup>
  ```js JavaScript theme={null}
  const interaction = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "用一句话解释量子计算",
  });

  console.log(interaction.output_text);
  console.log(interaction.usage);
  // { total_tokens, total_input_tokens, total_output_tokens, ... }
  ```

  ```python Python theme={null}
  interaction = client.interactions.create(
      model="gemini-3.5-flash",
      input="用一句话解释量子计算",
  )

  print(interaction.output_text)
  ```
</CodeGroup>

### ネイティブ画像生成

`response_format` を設定して出力モダリティを画像に構成します。返される `Interaction` オブジェクトは `output_image` 便利プロパティを提供し、その `data` フィールドには Base64 エンコードされた画像データが含まれます。

<Tip>
  * 推奨モデル `gemini-3.1-flash-image`（Nano Banana 2、汎用画像生成モデル）。
  * `response_modalities` の値は**小文字**の `['text', 'image']` でなければなりません。大文字は `generateContent` API の書き方であり、Interactions API では `400` が返されます。
  * `delivery: 'inline'` を渡さないでください（`400 Image delivery mode is not supported`）。Interactions API はデフォルトで inline 方式で画像データを返します。
</Tip>

**`response_format` パラメータ：**

| フィールド          | 説明       | 使用可能な値                                    |
| -------------- | -------- | ----------------------------------------- |
| `type`         | 出力タイプ    | `"image"`                                 |
| `aspect_ratio` | アスペクト比   | `"1:1"` `"3:4"` `"4:3"` `"9:16"` `"16:9"` |
| `image_size`   | 出力解像度    | `"1K"` `"2K"` `"4K"`                      |
| `mime_type`    | 画像フォーマット | `"image/png"` `"image/jpeg"`              |

<CodeGroup>
  ```js JavaScript theme={null}
  import fs from "node:fs";

  const interaction = await ai.interactions.create({
    model: "gemini-3.1-flash-image",
    input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
    response_modalities: ["text", "image"],
    response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
  });

  // 方法 1：output_image 便利プロパティ（最後に生成された画像を取得）
  if (interaction.output_image?.data) {
    fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
  }

  // 方法 2：steps を反復処理、マルチステップ混合出力に適用
  for (const step of interaction.steps ?? []) {
    for (const block of step.content ?? []) {
      if (block.type === "image" && block.data) {
        fs.writeFileSync("output.png", Buffer.from(block.data, "base64"));
      }
    }
  }
  ```

  ```python Python theme={null}
  import base64

  interaction = client.interactions.create(
      model="gemini-3.1-flash-image",
      input="A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
      response_format={
          "type": "image",
          "aspect_ratio": "1:1",
          "image_size": "1K",
      },
  )

  # output_image 便利プロパティ
  if interaction.output_image:
      with open("output.png", "wb") as f:
          f.write(base64.b64decode(interaction.output_image.data))
  ```
</CodeGroup>

### ストリーミング出力

`stream: true` を渡して Server-Sent Events（SSE）ストリーミング転送を有効にします。イベントは以下の順序で到着します：

```
interaction.created → status_update → step.start → step.delta → step.stop → interaction.completed
```

増分テキストは `event.delta.text` から取得され、イベントタイプフィールドは `event_type` です。

```js JavaScript theme={null}
const stream = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "写一首关于月亮的俳句",
  stream: true,
});

for await (const event of stream) {
  if (event.event_type === "step.delta" && event.delta?.type === "text") {
    process.stdout.write(event.delta.text);
  }
  if (event.event_type === "interaction.completed") {
    console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
  }
}
```

***

## Embeddings

`embedContent` エンドポイントを通じて、テキストまたはマルチモーダルコンテンツのベクトル表現（embedding）を取得します。

<Tip>
  OpenAI 互換の `/v1/embeddings` エンドポイントが必要な場合は、[ベクトル埋め込み](/jp/api/EBD) を参照してください。
</Tip>

### embedContent

<CodeGroup>
  ```js JavaScript theme={null}
  const response = await ai.models.embedContent({
    model: "gemini-embedding-2-preview",
    contents: "What is the meaning of life?",
    config: {
      outputDimensionality: 768, // オプション：出力次元を指定（128-3072）、デフォルト 3072
    },
  });

  console.log("dimensions:", response.embeddings[0].values.length); // 768
  ```

  ```python Python theme={null}
  from google.genai import types

  result = client.models.embed_content(
      model="gemini-embedding-2-preview",
      contents="What is the meaning of life?",
      config=types.EmbedContentConfig(
          output_dimensionality=768,  # オプション：出力次元を指定（128-3072）、デフォルト 3072
      ),
  )

  print(f"dimensions: {len(result.embeddings[0].values)}")  # 768
  ```
</CodeGroup>

### バッチ Embeddings 取得

`embedContent` の `contents` パラメータに `Content` 配列を渡すことで、1 回の呼び出しで複数のテキストの embedding を取得できます：

```js JavaScript theme={null}
const response = await ai.models.embedContent({
  model: "gemini-embedding-2-preview",
  contents: [
    { parts: [{ text: "第一段文本" }] },
    { parts: [{ text: "第二段文本" }] },
  ],
});

console.log("count:", response.embeddings.length); // 2
for (const emb of response.embeddings) {
  console.log("dimensions:", emb.values.length);
}
```

### 利用可能なモデルとパラメータ

| モデル                          | 入力トークン上限 | デフォルト出力次元     | 入力モダリティ           | 説明                                            |
| ---------------------------- | -------- | ------------- | ----------------- | --------------------------------------------- |
| `gemini-embedding-2-preview` | 8,192    | 3,072（推奨 768） | テキスト、画像、動画、音声、PDF | 最新のマルチモーダル埋め込みモデル、`outputDimensionality` サポート |
| `gemini-embedding-001`       | 2,048    | 3,072         | テキストのみ            | 前世代のテキスト埋め込みモデル、`taskType` サポート               |

`gemini-embedding-001` は `config.taskType` を通じて埋め込みの用途を指定し、特定のダウンストリームタスクのベクトル品質を最適化できます：

| `taskType`            | 用途                  |
| --------------------- | ------------------- |
| `SEMANTIC_SIMILARITY` | セマンティック類似度計算        |
| `RETRIEVAL_DOCUMENT`  | ドキュメントインデックス（検索対象側） |
| `RETRIEVAL_QUERY`     | 検索クエリ（検索側）          |
| `CLASSIFICATION`      | テキスト分類              |
| `CLUSTERING`          | テキストクラスタリング         |

<Note>
  `gemini-embedding-2-preview` は `taskType` パラメータをサポートしていません。代わりにプロンプト内のプレフィックスでタスクタイプを指定します（例：`search_query: ...` または `search_document: ...`）。
</Note>

***

## Context Caching（明示的キャッシュ）

明示的キャッシュ（Explicit Caching）により、開発者は `CachedContent` オブジェクトを手動で作成、照会、参照、削除でき、複数のリクエスト間で同じ長いコンテキストを再利用するシナリオに適しています。[暗黙的キャッシュ](/jp/api/Gemini-Guides#コンテキストキャッシュ)とは異なり、明示的キャッシュはアプリケーション側がライフサイクルを主体的に管理します。

<Note>
  明示的キャッシュは `generateContent` API にのみ適用されます。Interactions API は暗黙的キャッシュのみをサポートしています。
</Note>

<Tip>
  ストレージ価格が設定されていないモデルは、ゲートウェイがキャッシュ作成リクエストをブロックします（`context caching is not available for model`）。これはストレージ料金の漏れを防ぐためです。主要モデル（gemini-2.5-flash、gemini-2.5-pro など）はすべて設定済みです。
</Tip>

### CachedContent の作成

`caches.create()` を通じてキャッシュを作成します。`ttl`（Time-To-Live）でキャッシュの有効期間を制御し、期限切れ後は自動的にクリアされます。

<CodeGroup>
  ```js JavaScript theme={null}
  const longDocument = "需要反復引用的長文本内容...".repeat(500);

  const cache = await ai.caches.create({
    model: "gemini-3.5-flash",
    config: {
      contents: longDocument,
      ttl: "300s",
    },
  });

  console.log("CachedContent name:", cache.name);
  // 形式：cachedContents/xxx
  ```

  ```python Python theme={null}
  long_document = "需要反復引用的長文本内容..." * 500

  cache = client.caches.create(
      model="gemini-3.5-flash",
      config={
          "contents": long_document,
          "ttl": "300s",
      },
  )

  print(f"CachedContent name: {cache.name}")
  ```
</CodeGroup>

### generateContent でキャッシュを参照

`cache.name` を `cachedContent`（JS）または `cached_content`（Python）パラメータに渡すことで、推論時にキャッシュをヒットさせることができます。ヒットしたトークン数は `usageMetadata.cachedContentTokenCount` に反映されます。

<CodeGroup>
  ```js JavaScript theme={null}
  const response = await ai.models.generateContent({
    model: "gemini-3.5-flash",
    contents: "请总结上述文档的核心观点",
    config: { cachedContent: cache.name },
  });

  console.log(response.text);
  console.log("cached tokens:", response.usageMetadata?.cachedContentTokenCount);
  ```

  ```python Python theme={null}
  response = client.models.generate_content(
      model="gemini-3.5-flash",
      contents="请总结上述文档的核心观点",
      config={"cached_content": cache.name},
  )

  print(response.text)
  print(f"cached tokens: {response.usage_metadata.cached_content_token_count}")
  ```
</CodeGroup>

### 照会と削除

<CodeGroup>
  ```js JavaScript theme={null}
  // CachedContent メタデータの照会
  const info = await ai.caches.get({ name: cache.name });
  console.log("model:", info.model, "expireTime:", info.expireTime);

  // キャッシュの削除
  await ai.caches.delete({ name: cache.name });
  ```

  ```python Python theme={null}
  # CachedContent メタデータの照会
  info = client.caches.get(name=cache.name)
  print(f"model: {info.model}  expire_time: {info.expire_time}")

  # キャッシュの削除
  client.caches.delete(name=cache.name)
  ```
</CodeGroup>

***

## サポート済み機能マトリックス

| 機能                                       | ステータス | 説明                                              |
| ---------------------------------------- | ----- | ----------------------------------------------- |
| `generateContent`                        | ✅     | 非ストリーミング + ストリーミング                              |
| `systemInstruction` / `generationConfig` | ✅     | temperature、maxOutputTokens など                  |
| Structured Output（`responseSchema`）      | ✅     | JSON mode                                       |
| Function Calling                         | ✅     | `functionDeclarations` ツール宣言                    |
| `thinkingConfig`                         | ✅     | 思考チェーン出力                                        |
| マルチモーダル入力                                | ✅     | 画像 / 音声 / 動画 / PDF via `inlineData` + Files API |
| Google Search Grounding                  | ✅     | 検索拡張                                            |
| `countTokens`                            | ✅     | トークンカウント                                        |
| Imagen（`generateImages`）                 | ✅     | Imagen 3 画像生成                                   |
| Veo（`generateVideos`）                    | ✅     | 動画生成                                            |
| TTS                                      | ✅     | 音声合成出力                                          |
| Files API                                | ✅     | 大容量ファイルのアップロードと参照                               |
| Interactions API                         | ✅     | 新世代推論インターフェース（テキスト + Nano Banana 画像生成）          |
| Embeddings（`embedContent`）               | ✅     | ネイティブベクトル埋め込み                                   |
| Context Caching CRUD                     | ✅     | 明示的キャッシュ管理                                      |
| Live API（WebSocket）                      | ❌     | 未対応                                             |

***

## よくある質問

<AccordionGroup>
  <Accordion title="interactions.create() を呼び出すと legacy schema エラーが発生する">
    SDK バージョンが低すぎます。`@google/genai` は >= 2.0.0、`google-genai` は >= 2.0.0 が必要です。`npm install @google/genai@latest` または `pip install -U google-genai` を実行して最新バージョンにアップグレードしてください。
  </Accordion>

  <Accordion title="モデルが 404 Not Found を返す">
    一部の初期モデル名（`gemini-2.5-flash-image-preview` など）は Interactions API ではすでに廃止されています。`gemini-3.1-flash-image`（Nano Banana 2）など、現在利用可能なモデル識別子を使用してください。`generateContent` API は影響を受けません。
  </Accordion>

  <Accordion title="response_modalities で 400 Bad Request が発生する">
    Interactions API の `response_modalities` の値は小文字（`"text"`、`"image"`）でなければなりません。大文字の `"TEXT"` / `"IMAGE"` は `generateContent` API の書き方であり、Interactions API では受け付けられません。
  </Accordion>

  <Accordion title="vertexai: true は使用できますか？">
    使用できません。SDK の `vertexai: true` モードは GCP OAuth + project / location パラメータを必要とし、`apiKey` とは相互排他的です（SDK が `Project/location and API key are mutually exclusive` をスローします）。AIHubMix 経由で接続する場合は Gemini Developer API 形式を使用するだけで十分です。バックエンドが自動的にルーティングします。
  </Accordion>

  <Accordion title="キャッシュ作成で context caching is not available for model エラーが発生する">
    ゲートウェイは、ストレージ価格が設定されていないモデルの `caches.create()` リクエストをブロックし、ストレージ料金の漏れを防ぎます。主要モデル（gemini-2.5-flash、gemini-2.5-pro など）はすべて設定済みです。このエラーが発生した場合は、そのモデルが明示的キャッシュをサポートしているか確認してください。
  </Accordion>
</AccordionGroup>

***

最終更新日：2026-07-07
