Open API

Gemini Web Search API

Turn on Google Search grounding through the LMU AI Gemini native v1beta API to get answers based on live web pages, plus the search queries, cited sources and sentence-level citations.

Add the google_search tool to a Gemini native generateContent request and the model searches the web when it needs to, then answers based on the results. The response also returns the search queries, the cited sources, and which source backs each sentence. Use it when you need up-to-date information or need to show where an answer came from.

Requests must land in the "Gemini-官方Vertex" group

The search is run by the upstream, and only the Gemini-官方Vertex group runs it. Upstreams behind other Gemini groups may not run searches: the request still returns 200, but the response has no groundingMetadata and the answer is not based on live search results.

  • Group key (recommended): under "API Keys" in the console, create a new key in the "Gemini-官方Vertex" group and use it only for web search.
  • Unified key: it does not land in this group by default. In the "API Keys" list, click the unified key's badge to open "Billing", then change the pay-as-you-go tier of the "Gemini family" to "Gemini-官方Vertex". After that, all Gemini calls made with this key go to that group and are billed at its rate multiplier.

Can't find this group on the China site?

The China site does not list the "Gemini-官方Vertex" group. Please create an API Key in this group on the international site.


1. Overview

ItemValue
Base URLhttps://api.lmuai.com
Non-streamingPOST /v1beta/models/{model}:generateContent
StreamingPOST /v1beta/models/{model}:streamGenerateContent?alt=sse
Authenticationx-goog-api-key: <your sk- API Key>
Turn on searchAdd "tools": [{"google_search": {}}] to the request body
Sourcescandidates[0].groundingMetadata in the response

2. Quick start

curl -X POST \
  'https://api.lmuai.com/v1beta/models/gemini-3.5-flash-lite:generateContent' \
  -H 'x-goog-api-key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{"text": "What is the website api.lmuai.com? Please cite sources."}]
    }],
    "tools": [{"google_search": {}}],
    "generationConfig": {"maxOutputTokens": 2048}
  }'

Example response (some fields omitted):

{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{"text": "api.lmuai.com is the LLM API platform of LMU AI..."}]
    },
    "finishReason": "STOP",
    "groundingMetadata": {
      "webSearchQueries": ["api lmuai com", "lmuai com"],
      "groundingChunks": [
        {"web": {"uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/...", "title": "lmuai.com", "domain": "lmuai.com"}},
        {"web": {"uri": "https://vertexaisearch.cloud.google.com/grounding-api-redirect/...", "title": "lmuai.ai", "domain": "lmuai.ai"}}
      ],
      "groundingSupports": [{
        "segment": {"endIndex": 52, "text": "api.lmuai.com is the LLM API platform of LMU AI"},
        "groundingChunkIndices": [0, 1]
      }],
      "searchEntryPoint": {"renderedContent": "<style>...</style><div>...</div>"}
    }
  }],
  "usageMetadata": {"promptTokenCount": 43, "candidatesTokenCount": 288}
}

3. Request parameters

Compared with a normal Gemini request, the only addition is tools:

FieldRequiredDescription
contentsYesThe conversation, written the same way as in a normal Gemini request
toolsYesAlways [{"google_search": {}}]. The model decides whether to search and how many times
generationConfig.maxOutputTokensRecommendedAt least 2048. Thinking models (such as gemini-4-hydrogen) need more, otherwise the response may be cut off with MAX_TOKENS and you get neither the answer nor the sources

One request may run several searches

The model may split a question into several search queries. The searches it actually ran are listed in webSearchQueries in the response.


4. Response fields: groundingMetadata

FieldDescription
webSearchQueriesThe search queries actually run for this request
groundingChunks[].web.uriSource link. It is a Google redirect link (vertexaisearch.cloud.google.com/...) that leads to the original page
groundingChunks[].web.titleSource title, usually the site's domain
groundingChunks[].web.domainThe source site's domain, such as lmuai.com
groundingSupports[].segmentA piece of the answer: text is the content, startIndex / endIndex give its position (startIndex is omitted when the piece starts at the beginning)
groundingSupports[].groundingChunkIndicesWhich sources this piece cites, as indexes into groundingChunks
searchEntryPoint.renderedContentHTML snippet of Google search suggestions

When you show answers to end users

If you show web-search answers to end users, Google requires you to also display the search suggestions in searchEntryPoint.renderedContent. See Google's documentation.


5. Python example: read sources and sentence-level citations

import requests

API_KEY = "YOUR_API_KEY"
url = "https://api.lmuai.com/v1beta/models/gemini-3.5-flash-lite:generateContent"

resp = requests.post(
    url,
    headers={"x-goog-api-key": API_KEY},
    json={
        "contents": [{"role": "user", "parts": [{"text": "Which LLM API platforms are available in China? Please cite sources."}]}],
        "tools": [{"google_search": {}}],
        "generationConfig": {"maxOutputTokens": 2048},
    },
    timeout=180,
)
resp.raise_for_status()
cand = resp.json()["candidates"][0]

answer = "".join(p.get("text", "") for p in cand["content"]["parts"])
meta = cand.get("groundingMetadata", {})
chunks = meta.get("groundingChunks", [])

print("Answer:", answer)
print("Queries:", meta.get("webSearchQueries", []))

for i, c in enumerate(chunks):
    print(f"[{i}] {c['web'].get('domain')}  {c['web'].get('uri')}")

for s in meta.get("groundingSupports", []):
    refs = [chunks[i]["web"].get("domain") for i in s.get("groundingChunkIndices", [])]
    print(s["segment"].get("text"), "->", refs)

if not meta:
    print("No web search this time: the model saw no need to search, or this group does not support web search.")

6. Streaming

Switch the endpoint to streamGenerateContent?alt=sse and keep the request body:

curl -N -X POST \
  'https://api.lmuai.com/v1beta/models/gemini-3.5-flash-lite:streamGenerateContent?alt=sse' \
  -H 'x-goog-api-key: YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "contents": [{"role": "user", "parts": [{"text": "What is in the AI industry news today?"}]}],
    "tools": [{"google_search": {}}],
    "generationConfig": {"maxOutputTokens": 2048}
  }'

Each data: event carries a piece of text. groundingMetadata only appears in the last event: concatenate the text from all events, then read the sources from the last event.


7. Supported models

The following models have been tested with web search:

ModelNotes
gemini-3.5-flash-liteFastest and cheapest, good for batch calls
gemini-3.8-flashUsually cites more sources, good when citations matter
gemini-3.6-flash / gemini-3.7-flashSimilar to 3.8 Flash
gemini-3-flash-previewWorks
gemini-4-hydrogenRuns many searches and takes longer; set a large maxOutputTokens

The models actually available in your group are listed on the "Available Models" page in the console.


8. Calling with the OpenAI or Anthropic protocol

Gemini models can also be called with the OpenAI or Anthropic protocol, and each protocol's search tool triggers a web search:

ProtocolSearch toolSearches the webStructured sources
Gemini native{"google_search": {}}✅✅ groundingMetadata
OpenAI Chat Completions{"type": "web_search"}✅❌ links only in the answer text
OpenAI Responses{"type": "web_search"}✅❌ links only in the answer text
Anthropic Messages{"type": "web_search_20250305", "name": "web_search"}✅❌ links only in the answer text

If you need the source list or sentence-level citations, use the Gemini native protocol.

An ordinary function tool named google_search ("type": "function") does not trigger a web search. It is still a function that your own program runs.


9. Cost

Web-search requests are billed by the model used. You can see the cost of each request on the "Usage" page in the console. One request may run several searches, and the output is usually longer than a normal request.


10. Troubleshooting

SymptomCauseFix
200 but no groundingMetadataThe model saw no need to search, or the group's upstream does not run searchesUse a Key in the "Gemini-官方Vertex" group; ask explicitly for web search or sources in the prompt
Unified key never returns groundingMetadataThe unified key's Gemini family is still on its default tier and does not land in "Gemini-官方Vertex"Change "Billing" as described at the top of this page, or create a separate group key
finishReason is MAX_TOKENS and the answer is emptyThinking used up the output budgetIncrease maxOutputTokens
404 Not FoundWrong path, or the model is not in your groupCheck the path is /v1beta/models/{model}:generateContent and confirm the model name on the "Available Models" page
401 UnauthorizedWrong Key, or the Key is not in the x-goog-api-key headerCheck the request header

For protocol details see API protocols; for common errors see Error codes.

Last updated:

京ICP备2020034311号-7

On this page