במדריך למתחילים הזה מוסבר איך להתקין את הספריות שלנו, לשלוח את הבקשה הראשונה, להזרים תשובות, ליצור שיחות מרובות תפניות ולהשתמש בכלים.
יש שתי דרכים לשלוח בקשה אל Gemini API:
- (מומלץ) Interactions API הוא פרימיטיב חדש עם תמיכה מובנית בשימוש בכלי רב-שלבי, בתזמור ובזרימות מורכבות של חשיבה רציונלית באמצעות שלבי ביצוע מוקלדים. בעתיד, מודלים חדשים מעבר למשפחת הליבה של mainline, יחד עם יכולות של AI אקטיבי וכלים חדשים, יושקו באופן בלעדי ב-Interactions API.
-
generateContentמאפשר ליצור תשובה חסרת מצב ממודל. מומלץ להשתמש ב-Interactions API, אבלgenerateContentנתמך באופן מלא.
בגרסה הזו של המדריך לתחילת העבודה נעשה שימוש ב-Interactions API כדי לשלוח בקשה ל-Gemini API.
לפני שמתחילים
כדי להשתמש ב-Gemini API, צריך מפתח API לאימות הבקשות, לאכיפת מגבלות אבטחה ולמעקב אחר השימוש בחשבון.
כדי להתחיל, אפשר ליצור אחד ב-AI Studio בחינם:
התקנה של Google GenAI SDK
Python
באמצעות Python 3.9 ואילך, מתקינים את החבילה google-genai באמצעות פקודת pip הבאה:
pip install -q -U google-genai
JavaScript
באמצעות Node.js v18+, מתקינים את Google Gen AI SDK ל-TypeScript ול-JavaScript באמצעות פקודת npm הבאה:
npm install @google/genai
יצירת טקסט
משתמשים ב-interactions.create method כדי ליצור תשובת טקסט.
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"
}'
הצגת התשובות באופן שוטף
כברירת מחדל, המודל מחזיר תשובה רק אחרי שתהליך היצירה כולו מסתיים. כדי לקבל חוויה מהירה ואינטראקטיבית יותר, אתם יכולים להזרים את התשובה בחלקים בזמן שהיא נוצרת.
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
}'
שיחות עם זיכרון
Gemini API כולל תמיכה מובנית ביצירת שיחות מרובות תפניות.
פשוט מעבירים את הערך 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();
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\"
}"
שימוש בכלים
להרחיב את היכולות של המודל על ידי הצגת תשובות שמבוססות על חיפוש 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();
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 תומך גם בכלים מובנים אחרים:
- הרצת קוד: מאפשרת למודל לכתוב ולהריץ קוד Python כדי לפתור בעיות מתמטיות מורכבות.
- הקשר של כתובת URL: מאפשר להשתמש בכתובות URL ספציפיות של דפי אינטרנט שאתם מספקים כדי להנחות את התשובות.
- חיפוש קבצים: מאפשר להעלות קבצים ולבסס את התשובות על התוכן שלהם באמצעות חיפוש סמנטי.
- מפות Google: מאפשרת להשתמש בנתוני מיקום כדי להציג תשובות מבוססות-מיקום ולחפש מקומות, מסלולים ומפות.
- שימוש במחשב: מאפשר למודל ליצור אינטראקציה עם מסך מחשב וירטואלי, מקלדת ועכבר כדי לבצע משימות.
הפעלת פונקציות מותאמות אישית
משתמשים בבקשות להפעלת פונקציות כדי לקשר בין מודלים לבין כלים וממשקי 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();
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"]
}
}]
}'
המאמרים הבאים
אחרי שהתחלתם להשתמש ב-Gemini API, כדאי לעיין במדריכים הבאים כדי ליצור אפליקציות מתקדמות יותר: