Panduan memulai ini menunjukkan cara menginstal library kami dan membuat permintaan pertama, melakukan streaming respons, membangun percakapan multi-turn, dan menggunakan alat.
Ada dua cara yang dapat Anda gunakan untuk mengirim permintaan ke Gemini API:
- (Direkomendasikan) Interactions API adalah primitif baru dengan dukungan bawaan untuk penggunaan alat multi-langkah, orkestrasi, dan alur penalaran yang kompleks melalui langkah-langkah eksekusi yang diketik. Ke depannya, model baru di luar keluarga mainline inti, bersama dengan kemampuan dan alat agentik baru, akan diluncurkan secara eksklusif di Interactions API.
generateContentmenyediakan cara untuk menghasilkan respons tanpa status dari model. Meskipun sebaiknya gunakan Interactions API,generateContentdidukung sepenuhnya.
Panduan memulai versi ini menggunakan Interactions API untuk mengirim permintaan ke Gemini API.
Sebelum memulai
Untuk menggunakan Gemini API, Anda harus memiliki kunci API untuk mengautentikasi permintaan, menerapkan batas keamanan, dan melacak penggunaan ke akun Anda.
Buat secara gratis di AI Studio untuk memulai:
Menginstal Google GenAI SDK
Python
Dengan menggunakan Python 3.9+, instal
paket google-genai
menggunakan
perintah pip berikut:
pip install -q -U google-genai
JavaScript
Dengan menggunakan Node.js v18+, instal Google Gen AI SDK for TypeScript and JavaScript menggunakan perintah npm berikut:
npm install @google/genai
Buat teks
Gunakan metode interactions.create untuk
membuat respons teks.
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();
REST
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"
}'
Aktifkan respons bertahap
Secara default, model hanya menampilkan respons setelah seluruh proses pembuatan selesai. Untuk pengalaman yang lebih cepat dan interaktif, Anda dapat mengalirkan potongan respons saat potongan tersebut dibuat.
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();
REST
# 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
}'
Percakapan multi-giliran
Gemini API memiliki dukungan bawaan untuk membangun
percakapan multi-giliran.
Cukup teruskan id yang ditampilkan dari interaksi sebelumnya sebagai parameter
previous_interaction_id, dan server akan otomatis mengelola histori percakapan.
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();
REST
# 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\"
}"
Menggunakan alat
Perluas kemampuan model dengan melakukan grounding pada respons dengan Google Penelusuran untuk mengakses konten web real-time. Model secara otomatis memutuskan kapan harus melakukan penelusuran, menjalankan kueri, dan menyintesis respons dengan kutipan.
Contoh berikut menunjukkan cara mengaktifkan Google Penelusuran:
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();
REST
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"}]
}'
Gemini API juga mendukung alat bawaan lainnya:
- Eksekusi kode: Memungkinkan model menulis dan menjalankan kode Python untuk memecahkan masalah matematika yang kompleks.
- Konteks URL: Memungkinkan Anda mendasarkan respons pada URL halaman web tertentu yang Anda berikan.
- Penelusuran file: Memungkinkan Anda mengupload file dan mendasarkan respons pada kontennya menggunakan penelusuran semantik.
- Google Maps: Memungkinkan Anda mendasarkan respons pada data lokasi dan menelusuri tempat, rute, dan peta.
- Penggunaan komputer: Memungkinkan model berinteraksi dengan layar, keyboard, dan mouse komputer virtual untuk melakukan tugas.
Memanggil fungsi kustom
Gunakan panggilan fungsi
untuk menghubungkan model ke alat dan API kustom Anda. Model menentukan kapan harus memanggil fungsi Anda dan menampilkan langkah function_call dengan argumen agar aplikasi Anda dapat dieksekusi.
Contoh ini mendeklarasikan fungsi suhu tiruan dan memeriksa apakah model ingin memanggilnya.
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();
REST
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"]
}
}]
}'
Langkah berikutnya
Setelah Anda mulai menggunakan Gemini API, pelajari panduan berikut untuk membuat aplikasi yang lebih canggih: