В этом кратком руководстве показано, как установить наши библиотеки и сделать первый запрос, получать потоковые ответы, создавать многоэтапные диалоги и использовать инструменты.
Для отправки запроса к API Gemini можно использовать два способа:
- (Рекомендуется) API взаимодействий — это новый примитив со встроенной поддержкой многошагового использования инструментов, оркестровки и сложных потоков рассуждений посредством типизированных шагов выполнения. В дальнейшем новые модели, выходящие за рамки основного семейства, а также новые возможности и инструменты для работы с агентами будут запускаться исключительно через API взаимодействий.
-
generateContentпредоставляет способ генерации ответа без сохранения состояния от модели. Хотя мы рекомендуем использовать Interactions API,generateContentполностью поддерживается.
В этой версии руководства по быстрому запуску используется API взаимодействий для отправки запроса к API Gemini.
Прежде чем начать
Для использования API Gemini вам потребуется ключ API, который позволит аутентифицировать ваши запросы, устанавливать ограничения безопасности и отслеживать использование в рамках вашей учетной записи.
Для начала создайте учетную запись бесплатно в AI Studio:
Установите Google GenAI SDK.
Python
При использовании Python 3.9+ установите пакет google-genai с помощью следующей команды pip :
pip install -q -U google-genai
JavaScript
Для работы с Node.js версии 18+ установите Google Gen AI SDK для TypeScript и JavaScript, используя следующую команду npm :
npm install @google/genai
Сгенерировать текст
Используйте метод interactions.create для генерации текстового ответа .
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3.5-flash",
input="Explain how AI works in a few words"
)
print(interaction.output_text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const interaction = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain how AI works in a few words",
});
console.log(interaction.output_text);
}
main();
ОТДЫХ
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
-d '{
"model": "gemini-3.5-flash",
"input": "Explain how AI works in a few words"
}'
Ответы потока
По умолчанию модель возвращает ответ только после завершения всего процесса генерации. Для более быстрой и интерактивной работы можно передавать фрагменты ответа по мере их генерации.
Python
stream = client.interactions.create(
model="gemini-3.5-flash",
input="Explain how AI works in detail",
stream=True
)
for event in stream:
if event.event_type == "step.delta":
if event.delta.type == "text":
print(event.delta.text, end="", flush=True)
JavaScript
async function main() {
const stream = await ai.interactions.create({
model: "gemini-3.5-flash",
input: "Explain how AI works in detail",
stream: true,
});
for await (const event of stream) {
if (event.event_type === "step.delta") {
if (event.delta.type === "text") {
process.stdout.write(event.delta.text);
}
}
}
}
main();
ОТДЫХ
# Use alt=sse for streaming
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-H "Api-Revision: 2026-05-20" \
--no-buffer \
-d '{
"model": "gemini-3.5-flash",
"input": "Explain how AI works in detail",
"stream": true
}'
Многоэтапные переговоры
API Gemini имеет встроенную поддержку для построения многоходовых диалогов . Просто передайте id , полученный в результате предыдущего взаимодействия, в качестве параметра previous_interaction_id , и сервер автоматически будет управлять историей диалога.
Python
interaction1 = client.interactions.create(
model="gemini-3.5-flash",
input="I have 2 dogs in my house."
)
print("Response 1:", interaction1.output_text)
interaction2 = client.interactions.create(
model="gemini-3.5-flash",
input="How many paws are in my house?",
previous_interaction_id=interaction1.id
)
print("Response 2:", interaction2.output_text)
JavaScript
async function main() {
const interaction1 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "I have 2 dogs in my house.",
});
console.log("Response 1:", interaction1.output_text);
const interaction2 = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "How many paws are in my house?",
previous_interaction_id: interaction1.id,
});
console.log("Response 2:", interaction2.output_text);
}
main();
ОТДЫХ
# Turn 1: Start the conversation
RESPONSE1=$(curl -s -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Api-Revision: 2026-05-20" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "gemini-3-flash-preview",
"input": "I have 2 dogs in my house."
}')
# Extract the interaction ID
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')
# Turn 2: Continue the conversation
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Api-Revision: 2026-05-20" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d "{
\"model\": \"gemini-3-flash-preview\",
\"input\": \"How many paws are in my house?\",
\"previous_interaction_id\": \"$INTERACTION_ID\"
}"
Используйте инструменты
Расширьте возможности модели, связав ответы с поиском Google для доступа к веб-контенту в режиме реального времени. Модель автоматически определяет, когда следует выполнять поиск, выполняет запросы и синтезирует ответ с цитатами.
Следующий пример демонстрирует, как включить поиск Google:
Python
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Who won the euro 2024?",
tools=[{"type": "google_search"}]
)
print(interaction.output_text)
for step in interaction.steps:
if step.type == "model_output":
for content_block in step.content:
if content_block.type == "text" and content_block.annotations:
print("\nCitations:")
for annotation in content_block.annotations:
if annotation.type == "url_citation":
print(f" - [{annotation.title}]({annotation.url})")
JavaScript
async function main() {
const interaction = await ai.interactions.create({
model: "gemini-3-flash-preview",
input: "Who won the euro 2024?",
tools: [{ type: "google_search" }]
});
console.log(interaction.output_text);
for (const step of interaction.steps) {
if (step.type === 'model_output') {
for (const contentBlock of step.content) {
if (contentBlock.type === 'text' && contentBlock.annotations) {
console.log("\nCitations:");
for (const annotation of contentBlock.annotations) {
if (annotation.type === 'url_citation') {
console.log(` - [${annotation.title}](${annotation.url})`);
}
}
}
}
}
}
}
main();
ОТДЫХ
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Api-Revision: 2026-05-20" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Who won the euro 2024?",
"tools": [{"type": "google_search"}]
}'
API Gemini также поддерживает другие встроенные инструменты:
- Выполнение кода : позволяет модели писать и запускать код на Python для решения сложных математических задач.
- Контекст URL : позволяет привязывать ответы к конкретным URL-адресам веб-страниц, которые вы указываете.
- Поиск файлов : позволяет загружать файлы и анализировать их содержимое с помощью семантического поиска.
- Google Maps : Позволяет основывать ответы на данных о местоположении и осуществлять поиск мест, прокладывать маршруты и просматривать карты.
- Использование компьютера : позволяет модели взаимодействовать с виртуальным экраном компьютера, клавиатурой и мышью для выполнения задач.
Вызов пользовательских функций
Используйте вызов функций для связи моделей с вашими пользовательскими инструментами и API. Модель определяет, когда следует вызывать вашу функцию, и возвращает шаг function_call с аргументами для выполнения вашим приложением.
В этом примере объявляется фиктивная функция температуры и проверяется, хочет ли модель её вызвать.
Python
import json
weather_function = {
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What's the temperature in London?",
tools=[weather_function],
)
fc_step = None
for step in interaction.steps:
if step.type == "function_call":
fc_step = step
break
if fc_step:
print(f"Model requested function: {fc_step.name} with args {fc_step.arguments}")
mock_result = {"temperature": "15C", "condition": "Cloudy"}
final_interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{
"type": "function_result",
"name": fc_step.name,
"call_id": fc_step.id,
"result": [{"type": "text", "text": json.dumps(mock_result)}],
}
],
tools=[weather_function],
previous_interaction_id=interaction.id,
)
print("Final Response:", final_interaction.output_text)
JavaScript
async function main() {
const weatherFunction = {
type: 'function',
name: 'get_current_temperature',
description: 'Gets the current temperature for a given location.',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'The city name, e.g. San Francisco',
},
},
required: ['location'],
},
};
const interaction = await ai.interactions.create({
model: 'gemini-3-flash-preview',
input: "What's the temperature in London?",
tools: [weatherFunction],
});
const fcStep = interaction.steps.find(s => s.type === 'function_call');
if (fcStep) {
console.log(`Model requested function: ${fcStep.name}`);
const mockResult = { temperature: "15C", condition: "Cloudy" };
const finalInteraction = await ai.interactions.create({
model: 'gemini-3-flash-preview',
input: [{
type: 'function_result',
name: fcStep.name,
call_id: fcStep.id,
result: [{ type: 'text', text: JSON.stringify(mockResult) }]
}],
tools: [weatherFunction],
previous_interaction_id: interaction.id,
});
console.log("Final Response:", finalInteraction.output_text);
}
}
main();
ОТДЫХ
curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Api-Revision: 2026-05-20" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What'\''s the temperature in London?",
"tools": [{
"type": "function",
"name": "get_current_temperature",
"description": "Gets the current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city name"}
},
"required": ["location"]
}
}]
}'
Что дальше?
Теперь, когда вы начали работать с API Gemini, ознакомьтесь со следующими руководствами для создания более сложных приложений: