Интеграция с поиском Google позволяет модели Gemini подключаться к веб-контенту в режиме реального времени и работать со всеми доступными языками. Это дает Gemini возможность давать более точные ответы и ссылаться на проверенные источники, выходящие за рамки ее собственных знаний.
Заземление помогает создавать приложения, которые могут:
- Повышение точности фактов: уменьшение количества иллюзорных моделей за счет того, что ответы основываются на информации из реального мира.
- Получайте доступ к информации в режиме реального времени: отвечайте на вопросы о последних событиях и темах.
Укажите источники: укрепите доверие пользователей, показав ссылки на источники утверждений, содержащихся в модели.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.7-flash",
input="Who won the euro 2024?",
tools=[{"type": "google_search"}]
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: "gemini-3.7-flash",
input: "Who won the euro 2024?",
tools: [{ type: "google_search" }]
});
console.log(interaction.output_text);
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.7-flash"))
.input(InteractionsInput.of("What is the current score of the Lakers game?"))
.tools(Arrays.asList(new GoogleSearch()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
System.out.println(interaction.outputText().orElse(""));
ОТДЫХ
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.7-flash",
"input": "Who won the euro 2024?",
"tools": [{"type": "google_search"}]
}'
Как работает заземление с помощью поиска Google.
При включении инструмента google_search модель автоматически обрабатывает весь рабочий процесс поиска, обработки и цитирования информации.

- Запрос пользователя: Ваше приложение отправляет запрос пользователя в API Gemini с включенным инструментом
google_search. - Анализ запроса: Модель анализирует запрос и определяет, может ли поиск в Google улучшить ответ.
- Поиск Google: При необходимости модель автоматически генерирует один или несколько поисковых запросов и выполняет их.
- Обработка результатов поиска: Модель обрабатывает результаты поиска, синтезирует информацию и формирует ответ.
- Ответ, основанный на результатах поиска: API возвращает окончательный, удобный для пользователя ответ, основанный на результатах поиска. Этот ответ включает текстовый ответ модели с встроенными
annotations, содержащими цитаты, а также шагиgoogle_search_callиgoogle_search_resultс поисковыми запросами и подсказками.
Понимание реакции заземления
Когда ответ успешно обоснован, текстовый вывод модели включает в себя встроенные annotations непосредственно в блок текстового содержимого. Эти аннотации содержат информацию о цитировании, связывающую части ответа с их источниками.
{
"steps": [
{
"type": "thought",
"summary": [
{
"type": "text",
"text": "The user is asking for the winner of Euro 2024. I need to search for the result of the Euro 2024 final."
}
],
"signature": "CoMDAXLI2nynRYojJIy6B1Jh9os2crpWLfB0..."
},
{
"type": "google_search_call",
"arguments": {
"queries": ["UEFA Euro 2024 winner"]
}
},
{
"type": "google_search_result",
"call_id": "search_001",
"result": [
{
"search_suggestions": "<!-- HTML and CSS for the search widget -->"
}
]
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.",
"annotations": [
{
"type": "url_citation",
"url": "https://www.aljazeera.com/sports/euro-2024-final",
"title": "aljazeera.com",
"start_index": 0,
"end_index": 56
},
{
"type": "url_citation",
"url": "https://www.uefa.com/euro2024/news/spain-wins-euro-2024",
"title": "uefa.com",
"start_index": 57,
"end_index": 124
}
]
}
]
}
]
}
Ключевые поля в ответе:
-
google_search_call: Содержит поисковыеqueriesвыполненные моделью. -
google_search_result: Содержитsearch_suggestions, фрагмент HTML-кода для отображения поисковых подсказок в пользовательском интерфейсе. Полные требования к использованию подробно описаны в Условиях предоставления услуг . -
textсannotations: синтезированный моделью ответ с встроенными цитатами. Каждая аннотацияurl_citationсвязывает текстовый сегмент (определяемый параметрамиstart_indexиend_index) с исходным URL-адресом. Это ключ к созданию встроенных цитат.
Функция сопоставления данных с результатами поиска Google также может использоваться в сочетании с инструментом контекстного анализа URL-адресов для сопоставления ответов как с общедоступными веб-данными, так и с конкретными предоставленными вами URL-адресами.
Указание источников с помощью внутритекстовых ссылок
API возвращает встроенные аннотации url_citation для текстового блока, предоставляя вам полный контроль над отображением источников в пользовательском интерфейсе. Каждая аннотация включает start_index и end_index чтобы определить, на какую часть текста она ссылается. Вот как их извлечь и отобразить.
Python
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text":
print(content_block.text)
if content_block.annotations:
print("\nCitations:")
for annotation in content_block.annotations:
if annotation.type == "url_citation":
cited_text = content_block.text[annotation.start_index:annotation.end_index]
print(f" [{annotation.title}]({annotation.url})")
print(f" Cited text: \"{cited_text}\"")
JavaScript
for (const step of interaction.steps) {
if (step.type === 'model_output') {
for (const contentBlock of step.content) {
if (contentBlock.type === 'text') {
console.log(contentBlock.text);
if (contentBlock.annotations) {
console.log("\nCitations:");
for (const annotation of contentBlock.annotations) {
if (annotation.type === 'url_citation') {
const citedText = contentBlock.text.slice(annotation.startIndex, annotation.endIndex);
console.log(` [${annotation.title}](${annotation.url})`);
console.log(` Cited text: "${citedText}"`);
}
}
}
}
}
}
}
Java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Annotation;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.URLCitation;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;
Client client = new Client();
CreateModelInteraction params =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.7-flash"))
.input(InteractionsInput.of("What happened in tech news today?"))
.tools(Arrays.asList(new GoogleSearch()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();
if (interaction.steps().isPresent()) {
for (Step step : interaction.steps().get()) {
if (step instanceof ModelOutputStep) {
ModelOutputStep outputStep = (ModelOutputStep) step;
if (outputStep.content().isPresent()) {
for (Content content : outputStep.content().get()) {
if (content instanceof TextContent) {
TextContent textContent = (TextContent) content;
System.out.println("Response: " + textContent.text().orElse(""));
if (textContent.annotations().isPresent()) {
for (Annotation annotation : textContent.annotations().get()) {
if (annotation instanceof URLCitation) {
URLCitation citation = (URLCitation) annotation;
System.out.printf(" [%s](%s)\n", citation.title().orElse(""), citation.url().orElse(""));
}
}
}
}
}
}
}
}
}
В результате будет отображен текст, за которым следуют ссылки на него:
Spain won Euro 2024, defeating England 2-1 in the final. This victory marks Spain's record fourth European Championship title.
Citations:
[aljazeera.com](https://www.aljazeera.com/sports/euro-2024-final)
Cited text: "Spain won Euro 2024, defeating England 2-1 in the final."
[uefa.com](https://www.uefa.com/euro2024/news/spain-wins-euro-2024)
Cited text: "This victory marks Spain's record fourth European Championship title."
Цены
When you use Grounding with Google Search with Gemini 3, your project is billed for each search query that the model decides to execute. If the model decides to execute multiple search queries to answer a single prompt (for example, searching for "UEFA Euro 2024 winner" and "Spain vs England Euro 2024 final score" within the same API call), this counts as two billable uses of the tool for that request. For billing purposes, we ignore the empty web search queries when counting unique queries. This billing model only applies to Gemini 3 models; when you use search grounding with Gemini 2.5 or older models, your project is billed per prompt.
Подробную информацию о ценах см. на странице цен Gemini API .
Поддерживаемые модели
Полный список возможностей модели можно найти на странице обзора модели .
| Модель | Освоение основ поиска Google |
|---|---|
| Gemini 3.7 Flash | ✔️ |
| Вспышка Gemini 3.6 | ✔️ |
| Фонарь Gemini 3.5 Flash-Lite | ✔️ |
| Вспышка Gemini 3.5 | ✔️ |
| Предварительный просмотр изображения Gemini 3.1 Flash | ✔️ |
| Gemini 3.1 Pro Preview | ✔️ |
| Предварительный просмотр изображения Gemini 3 Pro | ✔️ |
| Предварительный просмотр Gemini 3 Flash | ✔️ |
| Gemini 2.5 Pro | ✔️ |
| Вспышка Gemini 2.5 | ✔️ |
| Фонарь Gemini 2.5 Flash-Lite | ✔️ |
| Gemini 2.0 Flash | ✔️ |
Поддерживаемые комбинации инструментов
Вы можете использовать функцию «Подключение к Google Поиску» совместно с другими инструментами, такими как выполнение кода , контекст URL и функция «Подключение к Google Картам» (поддерживается на моделях Gemini 3.5 Flash и более поздних версиях), для решения более сложных задач. Модели Gemini 3 также поддерживают комбинирование этих встроенных инструментов с пользовательскими инструментами (вызов функций). Подробнее см. на странице комбинаций инструментов .
Что дальше?
- Узнайте о других доступных инструментах, таких как вызов функций .
- Узнайте, как дополнять подсказки конкретными URL-адресами с помощью инструмента контекста URL .