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

# Gemini

The platform supports accessing Gemini models using the OpenAI chat/completions protocol and the Gemini native protocol.

The following examples all use non-Stream mode. For Stream mode, change the path to /gemini/v1/models/{model}:**streamGenerateContent**.

## Quick Start

<CodeGroup>
  ```bash OpenAI theme={null}
  curl https://api.myrouter.ai/openai/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -d '{
      "model": "gemini-2.5-flash",
      "messages": [{
          "role": "user", "content": "What is the capital of France?"
      }],
      "reasoning_effort": "low"
    }'
  ```

  ```bash Gemini theme={null}
  curl https://api.myrouter.ai/gemini/v1/models/gemini-2.5-flash:generateContent \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -d '{
      "contents": [{
          "role": "user",
          "parts": [{"text": "What is the capital of France?"}]
      }],
      "generationConfig": {
          "thinkingConfig": {
              "thinkingBudget": 1024
          }
      }
    }'
  ```
</CodeGroup>

## OpenAI Protocol Thinking Control

The platform converts the reasoning\_effort parameter from OpenAI chat/completions requests into Gemini thinking parameters.

| reasoning\_effort | thinking               |
| ----------------- | ---------------------- |
| "disable", "none" | "budget\_tokens": 0    |
| "low"             | "budget\_tokens": 1024 |
| "medium"          | "budget\_tokens": 2048 |
| "high"            | "budget\_tokens": 4096 |

⚠️ Non-standard OpenAI values disable/none can be used to turn off the thinking process.

### Default Settings per Model

| Model          | Default Setting (when reasoning\_effort is not set)            |
| -------------- | -------------------------------------------------------------- |
| 2.5 Pro        | Dynamic thinking: the model decides when and how much to think |
| 2.5 Flash      | Dynamic thinking: the model decides when and how much to think |
| 2.5 Flash Lite | Thinking is disabled                                           |

⚠️ Thinking cannot be disabled for Gemini 2.5 Pro; reasoning\_effort: none will be converted to the minimum thinkingBudget of 128.
⚠️ thinkingBudget is only supported in Gemini 2.5 Flash, 2.5 Pro, and 2.5 Flash-Lite. Depending on the prompt, the model may exceed or fall below the token budget.

## Server-Side Tool Usage

### Google Search

With Google Search, you can connect Gemini models to real-time web content, supporting all available languages. This allows Gemini to provide more accurate answers and cite verifiable sources beyond its knowledge cutoff date.

<CodeGroup>
  ```bash OpenAI theme={null}
  curl https://api.myrouter.ai/openai/chat/completions \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "model": "gemini-2.5-flash-lite",
    "messages": [
      {
        "role": "user",
        "content": "List today's trending news in China"
      }
    ],
    "tools": [
      {
        "function": {"name": "google_search"}
      }
    ]
  }
  EOF
  ```

  ```bash Gemini theme={null}
  curl https://api.myrouter.ai/gemini/v1/models/gemini-2.5-flash-lite:generateContent \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "List today's trending news in China"}]
      }
    ],
    "tools": [
      {
        "googleSearch": {}
      }
    ]
  }
  EOF
  ```
</CodeGroup>

The result example is as follows. For the OpenAI protocol, grounding information can be obtained from the non-standard field gemini\_grounding\_metadata.

<CodeGroup>
  ```json OpenAI theme={null}
  {
    "id": "dcc7eab10b5adeb9e8648d134e815409",
    "object": "chat.completion",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "Here are some of today's top news in China: ..."
        },
        "finish_reason": "stop"
      }
    ],
    "gemini_grounding_metadata": {  # 👈 GEMINI GROUNDING
      "webSearchQueries": [
        "today's trending news"
      ],
      ...
      "groundingChunks": [
        ...
      ]
    }
  }
  ```

  ```json Gemini theme={null}
  {
    "candidates": [
      {
        "content": {
          "role": "model",
          "parts": [
            {
              "text": "Based on the search results you provided, here are some of today's trending news in China:..."
            }
          ]
        },
        "finishReason": "STOP",
        "index": 0,
        "groundingMetadata": {
          "webSearchQueries": [
            "today's trending news",
            "latest news headlines"
          ],
          "searchEntryPoint": {...},
          "groundingChunks": [...],
          "groundingSupports": [...]
        }
      }
    ]
  }
  ```
</CodeGroup>

### Code Execution

Gemini provides a code execution tool that allows the model to generate and run Python code. The model can then iteratively learn from code execution results until it produces the final output.

<CodeGroup>
  ```bash OpenAI theme={null}
  curl https://api.myrouter.ai/openai/chat/completions \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "model": "gemini-2.5-flash",
    "messages": [
      {
        "role": "user",
        "content": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50."
      }
    ],
    "tools": [
        {
             "function":  {"name": "code_execution"}
        }
    ],
    "reasoning_effort": "low"
  }
  EOF
  ```

  ```bash Gemini theme={null}
  curl https://api.myrouter.ai/gemini/v1/models/gemini-2.5-flash:generateContent \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50."}]
      }
    ],
    "tools": [
      {
        "codeExecution": {}
      }
    ],
    "generationConfig": {
      "thinkingConfig": {
        "thinkingBudget": 1024
      }
    }
  }
  EOF
  ```
</CodeGroup>

The result example is as follows. For the OpenAI protocol, the code and code execution results are included in the content. For the Gemini protocol, the code is in the executableCode field, the execution result is in the codeExecutionResult field, and the summary is in the text field.

<CodeGroup>
  ````markdown OpenAI theme={null}
  Okay, I can help you with that. I will write a Python script to find the
  first 50 prime numbers and then calculate their sum.

  Here's the plan:

  1.  Create a function to check if a number is prime.
  2.  Create a function to generate the first `n` prime numbers.
  3.  Call the generation function for the first 50 primes.
  4.  Sum the resulting list of primes.

  Here is the code to perform this calculation:

  ```PYTHON
  def is_prime(num):
      """Checks if a number is prime."""
      if num <= 1:
          return False
      if num <= 3:
          return True
      if num % 2 == 0 or num % 3 == 0:
          return False
      i = 5
      while i * i <= num:
          if num % i == 0 or num % (i + 2) == 0:
              return False
          i += 6
      return True

  def get_first_n_primes(n):
      """Generates a list of the first n prime numbers."""
      primes = []
      num = 2
      while len(primes) < n:
          if is_prime(num):
              primes.append(num)
          num += 1
      return primes

  # Get the first 50 prime numbers
  first_50_primes = get_first_n_primes(50)


  # Calculate the sum of these prime numbers

  sum_of_primes = sum(first_50_primes)


  print(f"The first 50 prime numbers are: {first_50_primes}")

  print(f"The sum of the first 50 prime numbers is: {sum_of_primes}")
  \```

  The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
  37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
  109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191,
  193, 197, 199, 211, 223, 227, 229]

  The sum of the first 50 prime numbers is: 5117
  ````

  ```markdown Gemini theme={null}
  - executableCode:
      language: PYTHON
      code: |
        import sympy

        def is_prime(n):
            if n <= 1:
                return False
            if n <= 3:
                return True
            if n % 2 == 0 or n % 3 == 0:
                return False
            i = 5
            while i * i <= n:
                if n % i == 0 or num % (i + 2) == 0:
                    return False
                i += 6
            return True

        prime_numbers = []
        num = 2
        while len(prime_numbers) < 50:
            if is_prime(num):
                prime_numbers.append(num)
            num += 1

        sum_of_primes = sum(prime_numbers)

        print(f"The first 50 prime numbers are: {prime_numbers}")
        print(f"The sum of the first 50 prime numbers is: {sum_of_primes}")
  - codeExecutionResult:
      outcome: OUTCOME_OK
      output: >
        The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
        31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103,
        107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179,
        181, 191, 193, 197, 199, 211, 223, 227, 229]

        The sum of the first 50 prime numbers is: 5117
  - text: The sum of the first 50 prime numbers is 5117.
  ```
</CodeGroup>

### URL context

With the URL context tool, you can provide additional context to the model in the form of URLs.
By adding URLs to the request, the model will access the content of those web pages to inform and improve the quality of its responses.

<CodeGroup>
  ```bash OpenAI theme={null}
  curl https://api.myrouter.ai/openai/chat/completions \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "model": "gemini-2.5-flash-lite",
    "messages": [
      {
        "role": "user",
        "content": "Who is this recipe suitable for? https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"
      }
    ],
    "tools": [
      {
        "function": {"name": "url_context"}
      }
    ]
  }
  EOF
  ```

  ```bash Gemini theme={null}
  curl https://api.myrouter.ai/gemini/v1/models/gemini-2.5-flash-lite:generateContent \
  -H "Authorization: Bearer <YOUR-API-KEY>" \
  -H "Content-Type: application/json" -d @- <<EOF
  {
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "Who is this recipe suitable for? https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592"}]
      }
    ],
    "tools": [
      {
        "urlContext": {}
      }
    ]
  }
  EOF
  ```
</CodeGroup>

Example response below:

<CodeGroup>
  ```json OpenAI theme={null}
  {
    "id": "82f10046aebe6697ed9d33a9fa398de4",
    "object": "chat.completion",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "This recipe is about how to make Ina Garten's perfect roast chicken.\n\n**Key Information:**\n* **Recipe Source:** Ina Garten, adapted from \"Barefoot Contessa Cookbook\".\n* **Prep Time:** 20 minutes\n* **Baking Time:** 1 hour 30 minutes\n* **Total Time:** 2 hours 10 minutes\n* **Servings:** 8\n* **Difficulty:** Medium\n\n**Ingredients:**\n* One 5-6 pound roasting chicken\n* Kosher salt\n* Freshly ground black pepper\n* A large bunch of fresh thyme, plus 20 sprigs\n* One lemon, halved\n* One head of garlic, cut in half crosswise\n* 2 tablespoons (1/4 stick) butter, melted\n* 1 large yellow onion, thickly sliced\n* 4 carrots, cut into 2-inch chunks\n* 1 fennel bulb, tops removed, cut into wedges\n* Olive oil\n\n**Cooking Steps:**\n1. Preheat oven to 425°F (about 220°C).\n2. Clean the chicken cavity, rinse inside and out. Remove excess fat and remaining feathers, pat dry the exterior.\n3. Generously season the inside of the chicken with salt and pepper. Stuff a bunch of thyme, half a lemon, and all the garlic into the cavity.\n4. Brush the outside of the chicken with melted butter, season again with salt and pepper.\n5. Tie the chicken legs together with kitchen twine and tuck the wing tips under the body.\n6. Place onion, carrots, and fennel in a roasting pan. Toss with salt, pepper, 20 sprigs of thyme, and olive oil. Spread the vegetables across the bottom of the pan, then place the chicken on top.\n7. Roast the chicken for 1.5 hours, or until juices run clear when a knife is inserted between the leg and thigh.\n8. Transfer the roasted chicken and vegetables to a platter, cover with aluminum foil and let rest for about 20 minutes.\n9. Slice the chicken and serve with the vegetables.\n\n**Cooking Tips and User Feedback:**\n* The recipe mentions that if the bottom of the vegetables starts to brown, you can add a cup of chicken broth to keep them moist.\n* Some users suggest using a smaller roasting pan to prevent the vegetables from burning.\n* Some users replaced the fennel with potatoes.\n* Many users reported the chicken was very tender and juicy, full of flavor, and the cooking process was simple."
        },
        "finish_reason": "stop"
      }
    ],
    "gemini_grounding_metadata": {
      "groundingChunks": [
        {
          "web": {
            "uri": "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592",
            "title": "Perfect Roast Chicken Recipe | Ina Garten | Food Network"
          }
        }
      ],
      "groundingSupports": [....]
    }
  }
  ```

  ```json Gemini theme={null}
  {
    "candidates": [
      {
        "content": {
          "role": "model",
          "parts": [
            {
              "text": "\nThis recipe is suitable for those who enjoy classic roast chicken, especially home cooks who want to prepare a delicious yet relatively easy dish. The recipe difficulty is rated as \"medium,\" and the total time required is 2 hours and 10 minutes (including 20 minutes of prep time, 20 minutes of idle time, and 1 hour 30 minutes of cooking time).\n\nAdditionally, it is also suitable for those who want to make an impressive main course for gatherings or special occasions, as roast chicken is typically a highlight on holiday tables.\n\nThe recipe also mentions that you can adjust the ingredients to personal taste. For example, reviews mention that you can omit the fennel or add chicken broth to help with basting, which suggests it is also suitable for those who enjoy experimenting and making adjustments while cooking."
            }
          ]
        },
        "finishReason": "STOP",
        "index": 0,
        "safetyRatings": null,
        "groundingMetadata": {
          "groundingChunks": [
            {
              "web": {
                "uri": "https://www.foodnetwork.com/recipes/ina-garten/perfect-roast-chicken-recipe-1940592",
                "title": "Perfect Roast Chicken Recipe | Ina Garten | Food Network"
              }
            }
          ],
          "groundingSupports": [
            {
              "segment": {
                "startIndex": 148,
                "endIndex": 317,
                "text": "The recipe difficulty is rated as \"medium,\" and the total time required is 2 hours and 10 minutes (including 20 minutes of prep time, 20 minutes of idle time, and 1 hour 30 minutes of cooking time)."
              },
              "groundingChunkIndices": [
                0
              ]
            },
            {
              "segment": {
                "startIndex": 319,
                "endIndex": 475,
                "text": "Additionally, it is also suitable for those who want to make an impressive main course for gatherings or special occasions, as roast chicken is typically a highlight on holiday tables."
              },
              "groundingChunkIndices": [
                0
              ]
            },
            {
              "segment": {
                "startIndex": 477,
                "endIndex": 695,
                "text": "The recipe also mentions that you can adjust the ingredients to personal taste. For example, reviews mention that you can omit the fennel or add chicken broth to help with basting, which suggests it is also suitable for those who enjoy experimenting and making adjustments while cooking."
              },
              "groundingChunkIndices": [
                0
              ]
            }
          ]
        }
      }
    ],
    "promptFeedback": {
      "safetyRatings": null
    },
    "usageMetadata": {
      "promptTokenCount": 37,
      "candidatesTokenCount": 159,
      "totalTokenCount": 3270,
      "trafficType": "ON_DEMAND",
      "promptTokensDetails": [
        {
          "modality": "TEXT",
          "tokenCount": 37
        }
      ],
      "candidatesTokensDetails": [
        {
          "modality": "TEXT",
          "tokenCount": 159
        }
      ],
      "toolUsePromptTokensDetails": [
        {
          "modality": "TEXT",
          "tokenCount": 3074
        }
      ],
      "toolUsePromptTokenCount": 3074
    },
    "responseId": "0472efecb0da2db5f78d047e70e54db6",
    "modelVersion": "gemini-2.5-flash-lite"
  }
  ```
</CodeGroup>
