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

# Geminiネイティブ（テキスト）

> Google Geminiのネイティブ形式でAPIを呼び出す

## はじめに

Gemini Native APIは、Google Geminiのリクエスト・レスポンス形式を使用します。Googleの公式クライアント（`google-generativeai` SDKなど）や、Geminiのデータ構造を直接使用する必要がある場面に適しています。

OpenAI互換クライアント（OpenAI SDKなど）を使用する場合は、`/v1/chat/completions`エンドポイントを使用してください。

### OpenAI形式との違い

| 機能 | Geminiネイティブ | OpenAI互換 |
| - | - | - |
| メッセージ構造 | `contents[].parts[]` | `messages[].content` |
| ロール名 | `user` / `model` | `user` / `assistant` |
| ストリーミングパラメータ | URLパラメータ`?alt=sse` | ボディパラメータ`stream: true` |
| システムプロンプト | `systemInstruction` | `messages[0].role: "system"` |
| マルチモーダル | 混合`parts[]`配列 | 混合`content[]`配列 |

## APIエンドポイント

| 機能 | メソッド | パス |
| - | - | - |
| テキスト生成（非ストリーミング） | POST | `/v1beta/models/{model}:generateContent` |
| テキスト生成（ストリーミング） | POST | `/v1beta/models/{model}:streamGenerateContent?alt=sse` |
| 単一の埋め込み | POST | `/v1beta/models/{model}:embedContent` |
| バッチ埋め込み | POST | `/v1beta/models/{model}:batchEmbedContents` |

## 認証

2つの認証方法に対応しています。

| メソッド | ヘッダー | 例 |
| - | - | - |
| Bearer Token (Recommended) | `Authorization` | `Bearer sk-xxxxxxxxxx` |
| Google Style | `x-goog-api-key` | `sk-xxxxxxxxxx` |

## リクエストパラメーター

| パラメーター | 型 | 必須 | 説明 |
| - | - | - | - |
| `contents` | array | はい | 会話内容の配列 |
| `generationConfig` | object | いいえ | 生成設定 |
| `safetySettings` | array | いいえ | 安全性フィルターの設定 |
| `systemInstruction` | object | いいえ | システム指示 |
| `tools` | array | いいえ | ツールの定義（関数呼び出し、検索など） |
| `cachedContent` | string | いいえ | キャッシュ済みコンテンツの名前 |

### generationConfigパラメータ

| パラメーター | 型 | 説明 |
| - | - | - |
| `temperature` | number | ランダム性（0～2） |
| `topP` | number | Nucleusサンプリング（0～1） |
| `topK` | integer | Top-Kサンプリング |
| `maxOutputTokens` | integer | 最大出力トークン数 |
| `stopSequences` | array | 停止シーケンス |
| `candidateCount` | integer | 応答候補の数 |
| `thinkingConfig` | object | 推論モードの設定 |

## 基本的な例

<Tabs>
  <Tab title="cURL（非ストリーミング）">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "contents": [
          {"role": "user", "parts": [{"text": "Explain artificial intelligence in one sentence"}]}
        ],
        "generationConfig": {
          "temperature": 0.7,
          "maxOutputTokens": 1024
        }
      }'
    ```
  </Tab>

  <Tab title="cURL（ストリーミング）">
    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "contents": [
          {"role": "user", "parts": [{"text": "Write a poem about spring"}]}
        ],
        "generationConfig": {
          "temperature": 0.8,
          "maxOutputTokens": 2048
        }
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    import google.generativeai as genai

    genai.configure(
        api_key="sk-xxxxxxxxxx",
        transport="rest",
        client_options={"api_endpoint": "https://api.mixroute.ai"}
    )

    model = genai.GenerativeModel("gemini-2.5-pro")
    response = model.generate_content("Explain artificial intelligence in one sentence")
    print(response.text)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    import { GoogleGenerativeAI } from "@google/generative-ai";

    const genAI = new GoogleGenerativeAI("sk-xxxxxxxxxx");

    // Custom endpoint
    const model = genAI.getGenerativeModel(
      { model: "gemini-2.5-pro" },
      { baseUrl: "https://api.mixroute.ai/v1beta" }
    );

    const result = await model.generateContent("Explain artificial intelligence in one sentence");
    console.log(result.response.text());
    ```
  </Tab>
</Tabs>

## 高度な機能

<Tabs>
  <Tab title="思考モード">
    ### 思考モード

    Gemini 2.5 ProとGemini 3 Proは思考モードに対応し、モデルが回答前に深い推論を行えます。

    **Gemini 2.5 Pro** - `thinkingBudget`を使用：

    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "Solve this geometry problem step by step"}]}],
      "generationConfig": {
        "maxOutputTokens": 16384,
        "thinkingConfig": {
          "includeThoughts": true,
          "thinkingBudget": 8192
        }
      }
    }
    ```

    **Gemini 3 Pro** - `thinkingLevel`を使用:

    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "Explain the principles of quantum entanglement"}]}],
      "generationConfig": {
        "maxOutputTokens": 16384,
        "thinkingConfig": {
          "includeThoughts": true,
          "thinkingLevel": "MEDIUM"
        }
      }
    }
    ```

    | パラメーター | 対象モデル | オプション |
    | - | - | - |
    | `thinkingBudget` | Gemini 2.5 Pro | 1～24576（トークン数） |
    | `thinkingLevel` | Gemini 3 Pro | `LOW` / `MEDIUM` / `HIGH` |
  </Tab>

  <Tab title="マルチモーダル入力">
    ### マルチモーダル入力

    画像、音声、動画など、複数の入力形式に対応しています。

    **画像入力（Base64）:**

    ```json theme={null}
    {
      "contents": [
        {
          "role": "user",
          "parts": [
            {
              "inlineData": {
                "mimeType": "image/jpeg",
                "data": "BASE64_ENCODED_IMAGE"
              }
            },
            {"text": "Describe the content of this image"}
          ]
        }
      ]
    }
    ```

    **画像入力（URL）：**

    ```json theme={null}
    {
      "contents": [
        {
          "role": "user",
          "parts": [
            {
              "fileData": {
                "mimeType": "image/jpeg",
                "fileUri": "https://example.com/image.jpg"
              }
            },
            {"text": "What's in this image?"}
          ]
        }
      ]
    }
    ```

    **対応するMIMEタイプ:**

    * 画像: `image/jpeg`、`image/png`、`image/gif`、`image/webp`
    * 音声: `audio/mp3`、`audio/wav`、`audio/aac`
    * 動画: `video/mp4`、`video/webm`
    * ドキュメント: `application/pdf`
  </Tab>

  <Tab title="関数呼び出し">
    ### 関数呼び出し

    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "What's the weather like in Shanghai today?"}]}],
      "tools": [
        {
          "functionDeclarations": [
            {
              "name": "get_weather",
              "description": "Get weather information for a specified city",
              "parameters": {
                "type": "object",
                "properties": {
                  "location": {
                    "type": "string",
                    "description": "City name"
                  },
                  "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "Temperature unit"
                  }
                },
                "required": ["location"]
              }
            }
          ]
        }
      ],
      "toolConfig": {
        "functionCallingConfig": {
          "mode": "AUTO"
        }
      }
    }
    ```

    **関数呼び出しモード:**

    * `AUTO`：呼び出すかどうかをモデルが自動的に判断
    * `ANY`: ツールの呼び出しを強制します
    * `NONE`: ツールの呼び出しを無効にします
  </Tab>

  <Tab title="Google検索">
    ### Google検索（グラウンディング）

    リアルタイム情報を取得するために、Google Searchを有効にします。

    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "What's the weather like in Beijing today?"}]}],
      "tools": [
        {
          "googleSearch": {}
        }
      ]
    }
    ```

    **動的検索の設定:**

    ```json theme={null}
    {
      "contents": [{"role": "user", "parts": [{"text": "Latest AI news"}]}],
      "tools": [
        {
          "googleSearch": {
            "dynamicRetrievalConfig": {
              "mode": "MODE_DYNAMIC",
              "dynamicThreshold": 0.5
            }
          }
        }
      ]
    }
    ```
  </Tab>

  <Tab title="ストリーミング">
    ### ストリーミング出力

    **Pythonのストリーミング：**

    ```python theme={null}
    import google.generativeai as genai

    genai.configure(
        api_key="sk-xxxxxxxxxx",
        transport="rest",
        client_options={"api_endpoint": "https://api.mixroute.ai"}
    )

    model = genai.GenerativeModel("gemini-2.5-pro")
    response = model.generate_content(
        "Write an article about artificial intelligence",
        stream=True
    )

    for chunk in response:
        print(chunk.text, end="", flush=True)
    ```

    **cURLのストリーミング：**

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "contents": [{"role": "user", "parts": [{"text": "Tell me a story"}]}]
      }'
    ```
  </Tab>

  <Tab title="コンテキストキャッシュ">
    ### コンテキストキャッシュ

    長いテキストや複数ターンの会話では、キャッシュによってトークン消費量を節約できます。

    **キャッシュの作成：**

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1beta/cachedContents" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "model": "models/gemini-2.5-pro",
        "displayName": "my-cache",
        "contents": [
          {
            "role": "user",
            "parts": [{"text": "This is a long document content..."}]
          }
        ],
        "ttl": "3600s"
      }'
    ```

    **キャッシュの使用:**

    ```json theme={null}
    {
      "cachedContent": "cachedContents/abc123",
      "contents": [
        {"role": "user", "parts": [{"text": "Based on the above document, summarize the key points"}]}
      ]
    }
    ```
  </Tab>

  <Tab title="画像生成">
    ### 画像生成

    Gemini 2.0 FlashまたはImagenモデルで画像を生成します。

    ```json theme={null}
    {
      "contents": [
        {
          "role": "user",
          "parts": [{"text": "Generate an image of a sunset at the beach"}]
        }
      ],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }
    ```

    **Imagenモデル:**

    ```bash theme={null}
    curl -X POST "https://api.mixroute.ai/v1beta/models/imagen-3.0-generate-002:predict" \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer sk-xxxxxxxxxx" \
      -d '{
        "instances": [
          {"prompt": "A cute cat in the sunshine"}
        ],
        "parameters": {
          "sampleCount": 1
        }
      }'
    ```
  </Tab>
</Tabs>

## 埋め込みAPI

### 単一の埋め込み

```bash theme={null}
curl -X POST "https://api.mixroute.ai/v1beta/models/text-embedding-004:embedContent" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "content": {
      "parts": [{"text": "This is text to be vectorized"}]
    }
  }'
```

**レスポンス例：**

```json theme={null}
{
  "embedding": {
    "values": [0.0123, -0.0456, 0.0789, ...]
  }
}
```

### バッチ埋め込み

```bash theme={null}
curl -X POST "https://api.mixroute.ai/v1beta/models/text-embedding-004:batchEmbedContents" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -d '{
    "requests": [
      {
        "model": "models/text-embedding-004",
        "content": {"parts": [{"text": "First text"}]}
      },
      {
        "model": "models/text-embedding-004",
        "content": {"parts": [{"text": "Second text"}]}
      }
    ]
  }'
```

**レスポンス例：**

```json theme={null}
{
  "embeddings": [
    {"values": [0.0123, -0.0456, ...]},
    {"values": [0.0234, -0.0567, ...]}
  ]
}
```

## レスポンス形式

```json theme={null}
{
  "candidates": [
    {
      "content": {
        "parts": [{"text": "Response text"}],
        "role": "model"
      },
      "finishReason": "STOP",
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE"
        }
      ]
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 20,
    "totalTokenCount": 30
  }
}
```

## エラー処理

| HTTPステータス | エラーの種類 | 説明 |
| - | - | - |
| 400 | INVALID\_ARGUMENT | 無効なリクエストパラメータ |
| 401 | UNAUTHENTICATED | APIキーが無効または未指定 |
| 403 | PERMISSION\_DENIED | このモデルへのアクセス権がありません |
| 404 | NOT\_FOUND | モデルが見つかりません |
| 429 | RESOURCE\_EXHAUSTED | レート制限を超過 |
| 500 | INTERNAL | 内部サーバーエラー |

**エラーレスポンスの例:**

```json theme={null}
{
  "error": {
    "code": 400,
    "message": "Invalid value at 'contents[0].parts[0]'",
    "status": "INVALID_ARGUMENT"
  }
}
```

## OpenAI形式との比較

| 機能 | Geminiネイティブ | OpenAI互換 |
| - | - | - |
| ベースURL | `https://api.mixroute.ai/v1beta` | `https://api.mixroute.ai/v1` |
| メッセージ構造 | `contents[].parts[]` | `messages[].content` |
| ロール名 | `user` / `model` | `user` / `assistant` |
| システムプロンプト | `systemInstruction` | `messages[0].role: "system"` |
| ストリーミングリクエスト | URLパラメータ`?alt=sse` | ボディパラメータ`stream: true` |
| 温度の範囲 | 0-2 | 0-2 |
| 関数呼び出し | `tools[].functionDeclarations` | `tools[].function` |
| 検索グラウンディング | `tools[].googleSearch` | 未対応 |
| 思考モード | `thinkingConfig` | 未対応 |

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url 'https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent' \
    --header 'Authorization: Bearer sk-xxxxxxxxxx' \
    --header 'Content-Type: application/json' \
    --data '{
      "contents": [
        {"role": "user", "parts": [{"text": "Explain artificial intelligence in one sentence"}]}
      ],
      "generationConfig": {
        "temperature": 0.7,
        "maxOutputTokens": 1024
      }
    }'
  ```

  ```python Python theme={null}
  import google.generativeai as genai

  genai.configure(
      api_key="sk-xxxxxxxxxx",
      transport="rest",
      client_options={"api_endpoint": "https://api.mixroute.ai"}
  )

  model = genai.GenerativeModel("gemini-2.5-pro")
  response = model.generate_content("Explain artificial intelligence in one sentence")
  print(response.text)
  ```

  ```javascript JavaScript theme={null}
  import { GoogleGenerativeAI } from "@google/generative-ai";

  const genAI = new GoogleGenerativeAI("sk-xxxxxxxxxx");
  const model = genAI.getGenerativeModel(
    { model: "gemini-2.5-pro" },
    { baseUrl: "https://api.mixroute.ai/v1beta" }
  );

  const result = await model.generateContent("Explain artificial intelligence in one sentence");
  console.log(result.response.text());
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->post('https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx',
          'Content-Type' => 'application/json',
      ],
      'json' => [
          'contents' => [
              ['role' => 'user', 'parts' => [['text' => 'Explain artificial intelligence in one sentence']]]
          ],
          'generationConfig' => [
              'temperature' => 0.7,
              'maxOutputTokens' => 1024
          ]
      ]
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "contents": []map[string]interface{}{
              {"role": "user", "parts": []map[string]string{{"text": "Explain artificial intelligence in one sentence"}}},
          },
          "generationConfig": map[string]interface{}{
              "temperature": 0.7,
              "maxOutputTokens": 1024,
          },
      }
      body, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST", "https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent", bytes.NewBuffer(body))
      req.Header.Set("Authorization", "Bearer sk-xxxxxxxxxx")
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  String json = """
      {
        "contents": [
          {"role": "user", "parts": [{"text": "Explain artificial intelligence in one sentence"}]}
        ],
        "generationConfig": {
          "temperature": 0.7,
          "maxOutputTokens": 1024
        }
      }
      """;
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .header("Content-Type", "application/json")
      .POST(HttpRequest.BodyPublishers.ofString(json))
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1beta/models/gemini-2.5-pro:generateContent')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'
  request['Content-Type'] = 'application/json'
  request.body = {
    contents: [
      { role: 'user', parts: [{ text: 'Explain artificial intelligence in one sentence' }] }
    ],
    generationConfig: {
      temperature: 0.7,
      maxOutputTokens: 1024
    }
  }.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "candidates": [
      {
        "content": {
          "parts": [{"text": "Artificial intelligence is a discipline that studies how to make computers simulate and implement human intelligence."}],
          "role": "model"
        },
        "finishReason": "STOP",
        "index": 0,
        "safetyRatings": []
      }
    ],
    "usageMetadata": {
      "promptTokenCount": 10,
      "candidatesTokenCount": 20,
      "totalTokenCount": 30
    },
    "modelVersion": "gemini-2.5-pro"
  }
  ```
</ResponseExample>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.