API-ja e Ndërveprimeve ( Beta ) është një ndërfaqe e unifikuar për bashkëveprimin me modelet dhe agjentët Gemini. Ajo thjeshton menaxhimin e gjendjes, orkestrimin e mjeteve dhe detyrat që ekzekutohen për një kohë të gjatë. Për një pamje gjithëpërfshirëse të skemës së API-t, shihni Referencën e API-t . Gjatë Betës, veçoritë dhe skemat i nënshtrohen ndryshimeve të rëndësishme .
Shembulli i mëposhtëm tregon se si të thirret API-ja e Ndërveprimeve me një mesazh teksti.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a short joke about programming."
}'
Ndërveprimet themelore
API-ja e Ndërveprimeve është e disponueshme përmes SDK-ve tona ekzistuese . Mënyra më e thjeshtë për të bashkëvepruar me modelin është duke ofruar një mesazh teksti. Të input mund të jenë një varg, një listë që përmban objekte përmbajtjeje ose një listë kthesash me role dhe objekte përmbajtjeje.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a short joke about programming."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a short joke about programming.',
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a short joke about programming."
}'
Bisedë
Mund të ndërtoni biseda me shumë kthesa në dy mënyra:
- Në mënyrë statike duke iu referuar një ndërveprimi të mëparshëm
- Pa shtetësi duke ofruar të gjithë historikun e bisedave
Bisedë madhështore
Kaloni id në nga bashkëveprimi i mëparshëm te parametri previous_interaction_id për të vazhduar një bisedë.
Python
from google import genai
client = genai.Client()
# 1. First turn
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input="Hi, my name is Phil."
)
print(f"Model: {interaction1.outputs[-1].text}")
# 2. Second turn (passing previous_interaction_id)
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input="What is my name?",
previous_interaction_id=interaction1.id
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. First turn
const interaction1 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Hi, my name is Phil.'
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
// 2. Second turn (passing previous_interaction_id)
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What is my name?',
previous_interaction_id: interaction1.id
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
PUSHTIM
# 1. First turn
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Hi, my name is Phil."
}'
# 2. Second turn (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-3-flash-preview",
# "input": "What is my name?",
# "previous_interaction_id": "INTERACTION_ID"
# }'
Rikthe ndërveprimet e kaluara me gjendje të plotë
Duke përdorur id në e ndërveprimit për të rikuperuar kthesat e mëparshme të bisedës.
Python
previous_interaction = client.interactions.get("<YOUR_INTERACTION_ID>")
print(previous_interaction)
JavaScript
const previous_interaction = await client.interactions.get("<YOUR_INTERACTION_ID>");
console.log(previous_interaction);
PUSHTIM
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/<YOUR_INTERACTION_ID>" \
-H "x-goog-api-key: $GEMINI_API_KEY"
Bisedë pa shtetësi
Mund ta menaxhoni historikun e bisedave manualisht në anën e klientit.
Python
from google import genai
client = genai.Client()
conversation_history = [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
}
]
interaction1 = client.interactions.create(
model="gemini-3-flash-preview",
input=conversation_history
)
print(f"Model: {interaction1.outputs[-1].text}")
conversation_history.append({"role": "model", "content": interaction1.outputs})
conversation_history.append({
"role": "user",
"content": "What is the most famous landmark in the second one?"
})
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input=conversation_history
)
print(f"Model: {interaction2.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const conversationHistory = [
{
role: 'user',
content: "What are the three largest cities in Spain?"
}
];
const interaction1 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: conversationHistory
});
console.log(`Model: ${interaction1.outputs[interaction1.outputs.length - 1].text}`);
conversationHistory.push({ role: 'model', content: interaction1.outputs });
conversationHistory.push({
role: 'user',
content: "What is the most famous landmark in the second one?"
});
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: conversationHistory
});
console.log(`Model: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"role": "user",
"content": "What are the three largest cities in Spain?"
},
{
"role": "model",
"content": "The three largest cities in Spain are Madrid, Barcelona, and Valencia."
},
{
"role": "user",
"content": "What is the most famous landmark in the second one?"
}
]
}'
Aftësitë multimodale
Mund ta përdorni API-në e Ndërveprimeve për raste përdorimi multimodal, siç është kuptimi i imazheve ose gjenerimi i videove.
Kuptimi multimodal
Mund të jepni të dhëna multimodale si të dhëna të koduara në base64 brenda rreshtit, duke përdorur API-n e Skedarëve për skedarë më të mëdhenj ose duke kaluar një lidhje të aksesueshme publikisht në fushën uri. Shembujt e kodit që vijojnë demonstrojnë metodën e URL-së publike.
Kuptimi i imazhit
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "Describe the image."},
{
"type": "image",
"uri": "YOUR_URL",
"mime_type": "image/png"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import {GoogleGenAI} from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{type: 'text', text: 'Describe the image.'},
{
type: 'image',
uri: 'YOUR_URL',
mime_type: 'image/png'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
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-flash-preview",
"input": [
{
"type": "text",
"text": "Describe the image."
},
{
"type": "image",
"uri": "YOUR_URL",
"mime_type": "image/png"
}
]
}'
Kuptimi i audios
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What does this audio say?"},
{
"type": "audio",
"uri": "YOUR_URL",
"mime_type": "audio/wav"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What does this audio say?' },
{
type: 'audio',
uri: 'YOUR_URL',
mime_type: 'audio/wav'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What does this audio say?"},
{
"type": "audio",
"uri": "YOUR_URL",
"mime_type": "audio/wav"
}
]
}'
Kuptimi i videos
Python
from google import genai
client = genai.Client()
print("Analyzing video...")
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What is happening in this video? Provide a timestamped summary."},
{
"type": "video",
"uri": "YOUR_URL",
"mime_type": "video/mp4"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
console.log('Analyzing video...');
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What is happening in this video? Provide a timestamped summary.' },
{
type: 'video',
uri: 'YOUR_URL',
mime_type: 'video/mp4'
}
]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What is happening in this video?"},
{
"type": "video",
"uri": "YOUR_URL",
"mime_type": "video/mp4"
}
]
}'
Kuptimi i dokumentit (PDF)
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{"type": "text", "text": "What is this document about?"},
{
"type": "document",
"uri": "YOUR_URL",
"mime_type": "application/pdf"
}
]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'text', text: 'What is this document about?' },
{
type: 'document',
uri: 'YOUR_URL',
mime_type: 'application/pdf'
}
],
});
console.log(interaction.outputs[0].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "text", "text": "What is this document about?"},
{
"type": "document",
"uri": "YOUR_URL",
"mime_type": "application/pdf"
}
]
}'
Gjenerimi multimodal
Mund të përdorni Interactions API për të gjeneruar rezultate multimodale.
Gjenerimi i imazhit
Python
import base64
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-pro-image-preview",
input="Generate an image of a futuristic city.",
response_modalities=["IMAGE"]
)
for output in interaction.outputs:
if output.type == "image":
print(f"Generated image with mime_type: {output.mime_type}")
# Save the image
with open("generated_city.png", "wb") as f:
f.write(base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-pro-image-preview',
input: 'Generate an image of a futuristic city.',
response_modalities: ['IMAGE']
});
for (const output of interaction.outputs) {
if (output.type === 'image') {
console.log(`Generated image with mime_type: ${output.mime_type}`);
// Save the image
fs.writeFileSync('generated_city.png', Buffer.from(output.data, 'base64'));
}
}
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-pro-image-preview",
"input": "Generate an image of a futuristic city.",
"response_modalities": ["IMAGE"]
}'
Gjenerimi i të folurit
Gjeneroni të folur me tingull natyral nga teksti duke përdorur modelin tekst-në-të-fjaluar (TTS). Konfiguroni zërin, gjuhën dhe cilësimet e altoparlantit me speech_config
parametër.
Python
import base64
from google import genai
import wave
# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
with wave.open(filename, "wb") as wf:
wf.setnchannels(channels)
wf.setsampwidth(sample_width)
wf.setframerate(rate)
wf.writeframes(pcm)
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-flash-preview-tts",
input="Say the following: WOOHOO This is so much fun!.",
response_modalities=["AUDIO"],
generation_config={
"speech_config": {
"language": "en-us",
"voice": "kore"
}
}
)
for output in interaction.outputs:
if output.type == "audio":
print(f"Generated audio with mime_type: {output.mime_type}")
# Save the audio as wave file to the current directory.
wave_file("generated_audio.wav", base64.b64decode(output.data))
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import wav from 'wav';
async function saveWaveFile(
filename,
pcmData,
channels = 1,
rate = 24000,
sampleWidth = 2,
) {
return new Promise((resolve, reject) => {
const writer = new wav.FileWriter(filename, {
channels,
sampleRate: rate,
bitDepth: sampleWidth * 8,
});
writer.on('finish', resolve);
writer.on('error', reject);
writer.write(pcmData);
writer.end();
});
}
async function main() {
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const client = new GoogleGenAI({apiKey: GEMINI_API_KEY});
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash-preview-tts',
input: 'Say the following: WOOHOO This is so much fun!.',
response_modalities: ['AUDIO'],
generation_config: {
speech_config: {
language: "en-us",
voice: "kore"
}
}
});
for (const output of interaction.outputs) {
if (output.type === 'audio') {
console.log(`Generated audio with mime_type: ${output.mime_type}`);
const audioBuffer = Buffer.from(output.data, 'base64');
// Save the audio as wave file to the current directory
await saveWaveFile("generated_audio.wav", audioBuffer);
}
}
}
await main();
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash-preview-tts",
"input": "Say the following: WOOHOO This is so much fun!.",
"response_modalities": ["AUDIO"],
"generation_config": {
"speech_config": {
"language": "en-us",
"voice": "kore"
}
}
}' | jq -r '.outputs[] | select(.type == "audio") | .data' | base64 -d > generated_audio.pcm
# You may need to install ffmpeg.
ffmpeg -f s16le -ar 24000 -ac 1 -i generated_audio.pcm generated_audio.wav
Gjenerimi i të folurit me shumë folës
Gjeneroni fjalim me folës të shumtë duke specifikuar emrat e folësve në komandë dhe duke i përputhur ata në speech_config .
Kërkesa duhet të përfshijë emrat e folësve:
TTS the following conversation between Alice and Bob:
Alice: Hi Bob, how are you doing today?
Bob: I'm doing great, thanks for asking! How about you?
Alice: Fantastic! I just learned about the Gemini API.
Pastaj konfiguroni speech_config me folësit që përputhen:
"generation_config": {
"speech_config": [
{"voice": "Zephyr", "speaker": "Alice", "language": "en-US"},
{"voice": "Puck", "speaker": "Bob", "language": "en-US"}
]
}
Aftësitë agjentike
API-ja e Ndërveprimeve është projektuar për ndërtimin dhe bashkëveprimin me agjentë, dhe përfshin mbështetje për thirrjen e funksioneve, mjete të integruara, rezultate të strukturuara dhe Protokollin e Kontekstit të Modelit (MCP).
Agjentë
Mund të përdorni agjentë të specializuar si deep-research-pro-preview-12-2025 për detyra komplekse. Për të mësuar më shumë rreth Agjentit të Kërkimit të Thellë Gemini, shihni udhëzuesin e Kërkimit të Thellë .
Python
import time
from google import genai
client = genai.Client()
# 1. Start the Deep Research Agent
initial_interaction = client.interactions.create(
input="Research the history of the Google TPUs with a focus on 2025 and 2026.",
agent="deep-research-pro-preview-12-2025",
background=True
)
print(f"Research started. Interaction ID: {initial_interaction.id}")
# 2. Poll for results
while True:
interaction = client.interactions.get(initial_interaction.id)
print(f"Status: {interaction.status}")
if interaction.status == "completed":
print("\nFinal Report:\n", interaction.outputs[-1].text)
break
elif interaction.status in ["failed", "cancelled"]:
print(f"Failed with status: {interaction.status}")
break
time.sleep(10)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Start the Deep Research Agent
const initialInteraction = await client.interactions.create({
input: 'Research the history of the Google TPUs with a focus on 2025 and 2026.',
agent: 'deep-research-pro-preview-12-2025',
background: true
});
console.log(`Research started. Interaction ID: ${initialInteraction.id}`);
// 2. Poll for results
while (true) {
const interaction = await client.interactions.get(initialInteraction.id);
console.log(`Status: ${interaction.status}`);
if (interaction.status === 'completed') {
console.log('\nFinal Report:\n', interaction.outputs[interaction.outputs.length - 1].text);
break;
} else if (['failed', 'cancelled'].includes(interaction.status)) {
console.log(`Failed with status: ${interaction.status}`);
break;
}
await new Promise(resolve => setTimeout(resolve, 10000));
}
PUSHTIM
# 1. Start the Deep Research Agent
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"input": "Research the history of the Google TPUs with a focus on 2025 and 2026.",
"agent": "deep-research-pro-preview-12-2025",
"background": true
}'
# 2. Poll for results (Replace INTERACTION_ID with the ID from the previous interaction)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"
Mjetet dhe thirrja e funksioneve
Ky seksion shpjegon se si të përdoret thirrja e funksioneve për të përcaktuar mjete të personalizuara dhe si të përdoren mjetet e integruara të Google brenda API-t të Ndërveprimeve.
Thirrja e funksionit
Python
from google import genai
client = genai.Client()
# 1. Define the tool
def get_weather(location: str):
"""Gets the weather for a given location."""
return f"The weather in {location} is sunny."
weather_tool = {
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}
# 2. Send the request with tools
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="What is the weather in Paris?",
tools=[weather_tool]
)
# 3. Handle the tool call
for output in interaction.outputs:
if output.type == "function_call":
print(f"Tool Call: {output.name}({output.arguments})")
# Execute tool
result = get_weather(**output.arguments)
# Send result back
interaction = client.interactions.create(
model="gemini-3-flash-preview",
previous_interaction_id=interaction.id,
input=[{
"type": "function_result",
"name": output.name,
"call_id": output.id,
"result": result
}]
)
print(f"Response: {interaction.outputs[-1].text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
// 1. Define the tool
const weatherTool = {
type: 'function',
name: 'get_weather',
description: 'Gets the weather for a given location.',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }
},
required: ['location']
}
};
// 2. Send the request with tools
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'What is the weather in Paris?',
tools: [weatherTool]
});
// 3. Handle the tool call
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Tool Call: ${output.name}(${JSON.stringify(output.arguments)})`);
// Execute tool (Mocked)
const result = `The weather in ${output.arguments.location} is sunny.`;
// Send result back
interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
previous_interaction_id:interaction.id,
input: [{
type: 'function_result',
name: output.name,
call_id: output.id,
result: result
}]
});
console.log(`Response: ${interaction.outputs[interaction.outputs.length - 1].text}`);
}
}
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "What is the weather in Paris?",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Gets the weather for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA"}
},
"required": ["location"]
}
}]
}'
# Handle the tool call and send result back (Replace INTERACTION_ID and CALL_ID)
# curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
# -H "Content-Type: application/json" \
# -H "x-goog-api-key: $GEMINI_API_KEY" \
# -d '{
# "model": "gemini-3-flash-preview",
# "previous_interaction_id": "INTERACTION_ID",
# "input": [{
# "type": "function_result",
# "name": "get_weather",
# "call_id": "FUNCTION_CALL_ID",
# "result": "The weather in Paris is sunny."
# }]
# }'
Thirrja e funksionit me gjendjen e klientit
Nëse nuk doni të përdorni gjendjen në anën e serverit, mund ta menaxhoni të gjithën në anën e klientit.
Python
from google import genai
client = genai.Client()
functions = [
{
"type": "function",
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {"type": "array", "items": {"type": "string"}},
"date": {"type": "string", "description": "Date of the meeting (e.g., 2024-07-29)"},
"time": {"type": "string", "description": "Time of the meeting (e.g., 15:00)"},
"topic": {"type": "string", "description": "The subject of the meeting."},
},
"required": ["attendees", "date", "time", "topic"],
},
}
]
history = [{"role": "user","content": [{"type": "text", "text": "Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API."}]}]
# 1. Model decides to call the function
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=history,
tools=functions
)
# add model interaction back to history
history.append({"role": "model", "content": interaction.outputs})
for output in interaction.outputs:
if output.type == "function_call":
print(f"Function call: {output.name} with arguments {output.arguments}")
# 2. Execute the function and get a result
# In a real app, you would call your function here.
# call_result = schedule_meeting(**json.loads(output.arguments))
call_result = "Meeting scheduled successfully."
# 3. Send the result back to the model
history.append({"role": "user", "content": [{"type": "function_result", "name": output.name, "call_id": output.id, "result": call_result}]})
interaction2 = client.interactions.create(
model="gemini-3-flash-preview",
input=history,
)
print(f"Final response: {interaction2.outputs[-1].text}")
else:
print(f"Output: {output}")
JavaScript
// 1. Define the tool
const functions = [
{
type: 'function',
name: 'schedule_meeting',
description: 'Schedules a meeting with specified attendees at a given time and date.',
parameters: {
type: 'object',
properties: {
attendees: { type: 'array', items: { type: 'string' } },
date: { type: 'string', description: 'Date of the meeting (e.g., 2024-07-29)' },
time: { type: 'string', description: 'Time of the meeting (e.g., 15:00)' },
topic: { type: 'string', description: 'The subject of the meeting.' },
},
required: ['attendees', 'date', 'time', 'topic'],
},
},
];
const history = [
{ role: 'user', content: [{ type: 'text', text: 'Schedule a meeting for 2025-11-01 at 10 am with Peter and Amir about the Next Gen API.' }] }
];
// 2. Model decides to call the function
let interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: history,
tools: functions
});
// add model interaction back to history
history.push({ role: 'model', content: interaction.outputs });
for (const output of interaction.outputs) {
if (output.type === 'function_call') {
console.log(`Function call: ${output.name} with arguments ${JSON.stringify(output.arguments)}`);
// 3. Send the result back to the model
history.push({ role: 'user', content: [{ type: 'function_result', name: output.name, call_id: output.id, result: 'Meeting scheduled successfully.' }] });
const interaction2 = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: history,
});
console.log(`Final response: ${interaction2.outputs[interaction2.outputs.length - 1].text}`);
}
}
Mjete të integruara
Gemini vjen me mjete të integruara si Grounding me Google Search , Execution Code , URL context dhe Computer Use.
Bazë me Kërkimin në Google
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Who won the last Super Bowl?",
tools=[{"type": "google_search"}]
)
# Find the text output (not the GoogleSearchResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Who won the last Super Bowl?',
tools: [{ type: 'google_search' }]
});
// Find the text output (not the GoogleSearchResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Who won the last Super Bowl?",
"tools": [{"type": "google_search"}]
}'
Ekzekutimi i kodit
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Calculate the 50th Fibonacci number.",
tools=[{"type": "code_execution"}]
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Calculate the 50th Fibonacci number.',
tools: [{ type: 'code_execution' }]
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Calculate the 50th Fibonacci number.",
"tools": [{"type": "code_execution"}]
}'
Konteksti i URL-së
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Summarize the content of https://www.wikipedia.org/",
tools=[{"type": "url_context"}]
)
# Find the text output (not the URLContextResultContent)
text_output = next((o for o in interaction.outputs if o.type == "text"), None)
if text_output:
print(text_output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Summarize the content of https://www.wikipedia.org/',
tools: [{ type: 'url_context' }]
});
// Find the text output (not the URLContextResultContent)
const textOutput = interaction.outputs.find(o => o.type === 'text');
if (textOutput) console.log(textOutput.text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Summarize the content of https://www.wikipedia.org/",
"tools": [{"type": "url_context"}]
}'
Përdorimi i kompjuterit
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-2.5-computer-use-preview-10-2025",
input="Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
tools=[{
"type": "computer_use",
"environment": "browser",
"excludedPredefinedFunctions": ["drag_and_drop"]
}]
)
# The response will contain tool calls (actions) for the computer interface
# or text explaining the action
for output in interaction.outputs:
print(output)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-2.5-computer-use-preview-10-2025',
input: 'Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.',
tools: [{
type: 'computer_use',
environment: 'browser',
excludedPredefinedFunctions: ['drag_and_drop']
}]
});
// The response will contain tool calls (actions) for the computer interface
// or text explaining the action
interaction.outputs.forEach(output => console.log(output));
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-computer-use-preview-10-2025",
"input": "Search for highly rated smart fridges with touchscreen, 2 doors, around 25 cu ft, priced below 4000 dollars on Google Shopping. Create a bulleted list of the 3 cheapest options in the format of name, description, price in an easy-to-read layout.",
"tools": [{
"type": "computer_use",
"environment": "browser",
"excludedPredefinedFunctions": ["drag_and_drop"]
}]
}'
Protokolli i kontekstit të Modelit në Distancë (MCP)
Integrimi i MCP në distancë thjeshton zhvillimin e agjentëve duke i lejuar Gemini API-t të thërrasë drejtpërdrejt mjete të jashtme të vendosura në servera në distancë.
Python
import datetime
from google import genai
client = genai.Client()
mcp_server = {
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}
today = datetime.date.today().strftime("%d %B %Y")
interaction = client.interactions.create(
model="gemini-2.5-flash",
input="What is the weather like in New York today?",
tools=[mcp_server],
system_instruction=f"Today is {today}."
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const mcpServer = {
type: 'mcp_server',
name: 'weather_service',
url: 'https://gemini-api-demos.uc.r.appspot.com/mcp'
};
const today = new Date().toDateString();
const interaction = await client.interactions.create({
model: 'gemini-2.5-flash',
input: 'What is the weather like in New York today?',
tools: [mcpServer],
system_instruction: `Today is ${today}.`
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash",
"input": "What is the weather like in New York today?",
"tools": [{
"type": "mcp_server",
"name": "weather_service",
"url": "https://gemini-api-demos.uc.r.appspot.com/mcp"
}],
"system_instruction": "Today is '"$(date +"%du%Bt%Y")"' YYYY-MM-DD>."
}'
Shënime të rëndësishme:
- MCP në distancë funksionon vetëm me serverat HTTP të Streamable (serverët SSE nuk mbështeten)
- MCP në distancë nuk funksionon me modelet Gemini 3 (kjo do të vijë së shpejti)
- Emrat e serverëve MCP nuk duhet të përfshijnë karakterin "-" (përdorni emrat e serverëve snake_case në vend të tyre)
Prodhimi i strukturuar (skema JSON)
Zbatoni një dalje specifike JSON duke ofruar një skemë JSON në parametrin response_format . Kjo është e dobishme për detyra të tilla si moderimi, klasifikimi ose nxjerrja e të dhënave.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod';
const client = new GoogleGenAI({});
const moderationSchema = z.object({
decision: z.union([
z.object({
reason: z.string().describe('The reason why the content is considered spam.'),
spam_type: z.enum(['phishing', 'scam', 'unsolicited promotion', 'other']).describe('The type of spam.'),
}).describe('Details for content classified as spam.'),
z.object({
summary: z.string().describe('A brief summary of the content.'),
is_safe: z.boolean().describe('Whether the content is safe for all audiences.'),
}).describe('Details for content classified as not spam.'),
]),
});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format: z.toJSONSchema(moderationSchema),
});
console.log(interaction.outputs[0].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
"response_format": {
"type": "object",
"properties": {
"decision": {
"type": "object",
"properties": {
"reason": {"type": "string", "description": "The reason why the content is considered spam."},
"spam_type": {"type": "string", "description": "The type of spam."}
},
"required": ["reason", "spam_type"]
}
},
"required": ["decision"]
}
}'
Kombinimi i mjeteve dhe rezultateve të strukturuara
Kombinoni mjetet e integruara me rezultatin e strukturuar për të marrë një objekt JSON të besueshëm bazuar në informacionin e marrë nga një mjet.
Python
from google import genai
from pydantic import BaseModel, Field
from typing import Literal, Union
client = genai.Client()
class SpamDetails(BaseModel):
reason: str = Field(description="The reason why the content is considered spam.")
spam_type: Literal["phishing", "scam", "unsolicited promotion", "other"]
class NotSpamDetails(BaseModel):
summary: str = Field(description="A brief summary of the content.")
is_safe: bool = Field(description="Whether the content is safe for all audiences.")
class ModerationResult(BaseModel):
decision: Union[SpamDetails, NotSpamDetails]
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Moderate the following content: 'Congratulations! You've won a free cruise. Click here to claim your prize: www.definitely-not-a-scam.com'",
response_format=ModerationResult.model_json_schema(),
tools=[{"type": "url_context"}]
)
parsed_output = ModerationResult.model_validate_json(interaction.outputs[-1].text)
print(parsed_output)
JavaScript
import { GoogleGenAI } from '@google/genai';
import { z } from 'zod'; // Assuming zod is used for schema generation, or define manually
const client = new GoogleGenAI({});
const obj = z.object({
winning_team: z.string(),
score: z.string(),
});
const schema = z.toJSONSchema(obj);
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Who won the last euro?',
tools: [{ type: 'google_search' }],
response_format: schema,
});
console.log(interaction.outputs[0].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Who won the last euro?",
"tools": [{"type": "google_search"}],
"response_format": {
"type": "object",
"properties": {
"winning_team": {"type": "string"},
"score": {"type": "string"}
}
}
}'
Karakteristika të përparuara
Ekzistojnë gjithashtu veçori shtesë të përparuara që ju japin më shumë fleksibilitet në punën me Interactions API.
Transmetim
Merr përgjigje në mënyrë graduale ndërsa ato gjenerohen.
Python
from google import genai
client = genai.Client()
stream = client.interactions.create(
model="gemini-3-flash-preview",
input="Explain quantum entanglement in simple terms.",
stream=True
)
for chunk in stream:
if chunk.event_type == "content.delta":
if chunk.delta.type == "text":
print(chunk.delta.text, end="", flush=True)
elif chunk.delta.type == "thought":
print(chunk.delta.thought, end="", flush=True)
elif chunk.event_type == "interaction.complete":
print(f"\n\n--- Stream Finished ---")
print(f"Total Tokens: {chunk.interaction.usage.total_tokens}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const stream = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Explain quantum entanglement in simple terms.',
stream: true,
});
for await (const chunk of stream) {
if (chunk.event_type === 'content.delta') {
if (chunk.delta.type === 'text' && 'text' in chunk.delta) {
process.stdout.write(chunk.delta.text);
} else if (chunk.delta.type === 'thought' && 'thought' in chunk.delta) {
process.stdout.write(chunk.delta.thought);
}
} else if (chunk.event_type === 'interaction.complete') {
console.log('\n\n--- Stream Finished ---');
console.log(`Total Tokens: ${chunk.interaction.usage.total_tokens}`);
}
}
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Explain quantum entanglement in simple terms.",
"stream": true
}'
Konfigurimi
Personalizoni sjelljen e modelit me generation_config .
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Tell me a story about a brave knight.",
generation_config={
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low",
}
)
print(interaction.outputs[-1].text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Tell me a story about a brave knight.',
generation_config: {
temperature: 0.7,
max_output_tokens: 500,
thinking_level: 'low',
}
});
console.log(interaction.outputs[interaction.outputs.length - 1].text);
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Tell me a story about a brave knight.",
"generation_config": {
"temperature": 0.7,
"max_output_tokens": 500,
"thinking_level": "low"
}
}'
Të menduarit
Modelet Gemini 2.5 dhe më të reja përdorin një proces të brendshëm arsyetimi të quajtur "të menduarit" përpara se të gjenerojnë një përgjigje. Kjo ndihmon modelin të prodhojë përgjigje më të mira për detyra komplekse si matematika, kodimi dhe arsyetimi me shumë hapa.
Niveli i të menduarit
Parametri thinking_level ju lejon të kontrolloni thellësinë e arsyetimit të modelit:
| Niveli | Përshkrimi | Modelet e Mbështetura |
|---|---|---|
minimal | Përputhet me cilësimin "pa menduar" për shumicën e pyetjeve. Në disa raste, modelet mund të mendojnë shumë minimalisht. Minimizon vonesën dhe koston. | Vetëm modelet Flash (p.sh. Binjakët 3 Blic) |
low | Arsyetim i lehtë që i jep përparësi vonesës dhe kursimit të kostos për ndjekje të thjeshtë të udhëzimeve dhe bisedë. | Të gjitha modelet e të menduarit |
medium | Të menduarit e ekuilibruar për shumicën e detyrave. | Vetëm modelet Flash (p.sh. Binjakët 3 Blic) |
high | (Parazgjedhur) Maksimizon thellësinë e arsyetimit. Modelit mund t'i duhet shumë më tepër kohë për të arritur te një shenjë e parë, por rezultati do të arsyetohet më me kujdes. | Të gjitha modelet e të menduarit |
Përmbledhje të të menduarit
Mendimi i modelit përfaqësohet si blloqe mendimi ( type: "thought" ) në rezultatet e përgjigjeve. Ju mund të kontrolloni nëse do të merrni përmbledhje të procesit të të menduarit të lexueshme nga njeriu duke përdorur parametrin thinking_summaries :
| Vlerë | Përshkrimi |
|---|---|
auto | (Parazgjedhur) Kthen përmbledhje mendimesh kur janë të disponueshme. |
none | Çaktivizon përmbledhjet e mendimeve. |
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input="Solve this step by step: What is 15% of 240?",
generation_config={
"thinking_level": "high",
"thinking_summaries": "auto"
}
)
for output in interaction.outputs:
if output.type == "thought":
print(f"Thinking: {output.summary}")
elif output.type == "text":
print(f"Answer: {output.text}")
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: 'Solve this step by step: What is 15% of 240?',
generation_config: {
thinking_level: 'high',
thinking_summaries: 'auto'
}
});
for (const output of interaction.outputs) {
if (output.type === 'thought') {
console.log(`Thinking: ${output.summary}`);
} else if (output.type === 'text') {
console.log(`Answer: ${output.text}`);
}
}
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": "Solve this step by step: What is 15% of 240?",
"generation_config": {
"thinking_level": "high",
"thinking_summaries": "auto"
}
}'
Çdo bllok mendimi përmban një fushë signature (një hash kriptografik i gjendjes së arsyetimit të brendshëm) dhe një fushë summary opsionale (një përmbledhje e lexueshme nga njeriu e arsyetimit të modelit). signature është gjithmonë i pranishëm, por një bllok mendimi mund të përmbajë vetëm një nënshkrim pa përmbledhje në këto raste:
- Kërkesa të thjeshta : Modeli nuk kishte arsye të mjaftueshme për të gjeneruar një përmbledhje
-
thinking_summaries: "none": Përmbledhjet janë çaktivizuar në mënyrë të qartë
Kodi juaj duhet të trajtojë gjithmonë blloqe mendimesh ku summary është bosh ose mungon. Kur menaxhoni historikun e bisedave manualisht (modaliteti pa gjendje), duhet të përfshini blloqet e mendimeve me nënshkrimet e tyre në kërkesat pasuese për të vërtetuar vërtetësinë.
Duke punuar me skedarë
Puna me skedarë të largët
Qasuni skedarëve duke përdorur URL-të e largëta direkt në thirrjen API.
Python
from google import genai
client = genai.Client()
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg",
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{
type: 'image',
uri: 'https://github.com/<github-path>/cats-and-dogs.jpg',
},
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
PUSHTIM
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{
"type": "image",
"uri": "https://github.com/<github-path>/cats-and-dogs.jpg"
},
{"type": "text", "text": "Describe what you see."}
]
}'
Duke punuar me API-n e skedarëve Gemini
Ngarko skedarët në API-n Gemini Files përpara se t'i përdorësh.
Python
from google import genai
import time
import requests
client = genai.Client()
# 1. Download the file
url = "https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg"
response = requests.get(url)
with open("cats-and-dogs.jpg", "wb") as f:
f.write(response.content)
# 2. Upload to Gemini Files API
file = client.files.upload(file="cats-and-dogs.jpg")
# 3. Wait for processing
while client.files.get(name=file.name).state != "ACTIVE":
time.sleep(2)
# 4. Use in Interaction
interaction = client.interactions.create(
model="gemini-3-flash-preview",
input=[
{
"type": "image",
"uri": file.uri,
},
{"type": "text", "text": "Describe what you see."}
],
)
for output in interaction.outputs:
if output.type == "text":
print(output.text)
JavaScript
import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';
import fetch from 'node-fetch';
const client = new GoogleGenAI({});
// 1. Download the file
const url = 'https://github.com/philschmid/gemini-samples/raw/refs/heads/main/assets/cats-and-dogs.jpg';
const filename = 'cats-and-dogs.jpg';
const response = await fetch(url);
const buffer = await response.buffer();
fs.writeFileSync(filename, buffer);
// 2. Upload to Gemini Files API
const myfile = await client.files.upload({ file: filename, config: { mimeType: 'image/jpeg' } });
// 3. Wait for processing
while ((await client.files.get({ name: myfile.name })).state !== 'ACTIVE') {
await new Promise(resolve => setTimeout(resolve, 2000));
}
// 4. Use in Interaction
const interaction = await client.interactions.create({
model: 'gemini-3-flash-preview',
input: [
{ type: 'image', uri: myfile.uri, },
{ type: 'text', text: 'Describe what you see.' }
],
});
for (const output of interaction.outputs) {
if (output.type === 'text') {
console.log(output.text);
}
}
PUSHTIM
# 1. Upload the file (Requires File API setup)
# See https://ai.google.dev/gemini-api/docs/files for details.
# Assume FILE_URI is obtained from the upload step.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"input": [
{"type": "image", "uri": "FILE_URI"},
{"type": "text", "text": "Describe what you see."}
]
}'
Modeli i të dhënave
Mund të mësoni më shumë rreth modelit të të dhënave në Referencën API . Më poshtë është një përmbledhje e përgjithshme e komponentëve kryesorë.
Ndërveprimi
| Pronë | Lloji | Përshkrimi |
|---|---|---|
id | string | Identifikues unik për bashkëveprimin. |
model / agent | string | Modeli ose agjenti i përdorur. Mund të jepet vetëm një. |
input | Content[] | Të dhënat e dhëna. |
outputs | Content[] | Përgjigjet e modeles. |
tools | Tool[] | Mjetet e përdorura. |
previous_interaction_id | string | ID-ja e ndërveprimit të mëparshëm për kontekstin. |
stream | boolean | Nëse bashkëveprimi është duke u transmetuar. |
status | string | Statusi: completed , in_progress , requires_action , failed , etj. |
background | boolean | Nëse bashkëveprimi është në modalitetin e sfondit. |
store | boolean | Nëse duhet të ruhet bashkëveprimi. Parazgjedhja: true . Vendoseni në false për të çregjistruar. |
usage | Përdorimi | Përdorimi i tokenit të kërkesës së ndërveprimit. |
Modele dhe agjentë të mbështetur
| Emri i modelit | Lloji | ID e modelit |
|---|---|---|
| Gemini 2.5 Pro | Model | gemini-2.5-pro |
| Binjakët 2.5 Flash | Model | gemini-2.5-flash |
| Gemini 2.5 Flash-lite | Model | gemini-2.5-flash-lite |
| Pamje paraprake e Gemini 3 Pro | Model | gemini-3-pro-preview |
| Pamje paraprake e shpejtë e Gemini 3 | Model | gemini-3-flash-preview |
| Pamje paraprake e hulumtimit të thellë | Agjent | deep-research-pro-preview-12-2025 |
Si funksionon API-ja e Ndërveprimeve
API-ja e Ndërveprimeve është projektuar rreth një burimi qendror: Interaction . Një Interaction përfaqëson një kthesë të plotë në një bisedë ose detyrë. Ai vepron si një regjistrim sesioni, që përmban të gjithë historikun e një ndërveprimi, duke përfshirë të gjitha inputet e përdoruesit, mendimet e modelit, thirrjet e mjeteve, rezultatet e mjeteve dhe daljet përfundimtare të modelit.
Kur bëni një thirrje në interactions.create , ju po krijoni një burim të ri Interaction .
Menaxhimi i gjendjes nga ana e serverit
Mund të përdorni id në e një bashkëveprimi të përfunduar në një thirrje pasuese duke përdorur parametrin previous_interaction_id për të vazhduar bisedën. Serveri përdor këtë ID për të rimarrë historikun e bisedës, duke ju kursyer nga ridërgimi i të gjithë historikut të bisedës.
Vetëm historiku i bisedës (të dhënat hyrëse dhe dalëse) ruhet duke përdorur previous_interaction_id . Parametrat e tjerë janë të varur nga ndërveprimi dhe zbatohen vetëm për ndërveprimin specifik që po gjeneroni aktualisht:
-
tools -
system_instruction -
generation_config(duke përfshirëthinking_level,temperature, etj.)
Kjo do të thotë që duhet t'i rispecifikoni këto parametra në çdo bashkëveprim të ri nëse dëshironi që ato të zbatohen. Ky menaxhim i gjendjes nga ana e serverit është opsional; gjithashtu mund të veproni në modalitetin pa gjendje duke dërguar historikun e plotë të bisedës në çdo kërkesë.
Ruajtja dhe ruajtja e të dhënave
Si parazgjedhje, të gjitha objektet e Ndërveprimit ruhen ( store=true ) për të thjeshtuar përdorimin e veçorive të menaxhimit të gjendjes në anën e serverit (me previous_interaction_id ), ekzekutimin në sfond (duke përdorur background=true ) dhe për qëllime vëzhgimi.
- Niveli i Paguar : Ndërveprimet ruhen për 55 ditë .
- Niveli Falas : Ndërveprimet ruhen për 1 ditë .
Nëse nuk e dëshironi këtë, mund të vendosni store=false në kërkesën tuaj. Ky kontroll është i ndarë nga menaxhimi i gjendjes; mund të zgjidhni të mos përdorni hapësirën e ruajtjes për çdo ndërveprim. Megjithatë, vini re se store=false nuk është i përputhshëm me background=true dhe parandalon përdorimin e previous_interaction_id për raundet pasuese.
Mund t’i fshini ndërveprimet e ruajtura në çdo kohë duke përdorur metodën e fshirjes që gjendet në Referencën API . Mund t’i fshini ndërveprimet vetëm nëse e dini ID-në e ndërveprimit.
Pas skadimit të periudhës së ruajtjes, të dhënat tuaja do të fshihen automatikisht.
Objektet e ndërveprimit përpunohen sipas termave .
Praktikat më të mira
- Shkalla e klikimeve në memorien e përkohshme : Përdorimi i
previous_interaction_idpër të vazhduar bisedat i lejon sistemit të përdorë më lehtë ruajtjen implicite në memorien e përkohshme për historikun e bisedave, gjë që përmirëson performancën dhe ul kostot. - Përzierja e ndërveprimeve : Ju keni fleksibilitetin për të përzier dhe përputhur ndërveprimet e Agjentit dhe Modelit brenda një bisede. Për shembull, mund të përdorni një agjent të specializuar, si agjenti i Kërkimit të Thellë, për mbledhjen fillestare të të dhënave, dhe më pas të përdorni një model standard Gemini për detyra pasuese, të tilla si përmbledhja ose riformatimi, duke i lidhur këto hapa me
previous_interaction_id.
SDK-të
Mund të përdorni versionin më të fundit të SDK-ve të Google GenAI për të aksesuar API-në e Ndërveprimeve.
- Në Python, kjo është paketa
google-genainga versioni1.55.0e tutje. - Në JavaScript, kjo është paketa
@google/genainga versioni1.33.0e tutje.
Mund të mësoni më shumë rreth mënyrës së instalimit të SDK-ve në faqen e Bibliotekave .
Kufizime
- Statusi Beta : API-ja e Ndërveprimeve është në fazën beta/parapamjeje. Karakteristikat dhe skemat mund të ndryshojnë.
Karakteristika të pambështetura : Karakteristikat e mëposhtme nuk mbështeten ende, por do të vijnë së shpejti:
Renditja e rezultateve : Renditja e përmbajtjes për mjetet e integruara (
google_searchdheurl_context) ndonjëherë mund të jetë e pasaktë, me tekstin që shfaqet para ekzekutimit të mjetit dhe rezultatit. Ky është një problem i njohur dhe një zgjidhje është në proces.Kombinimet e mjeteve : Kombinimi i mjeteve MCP, Thirrja e Funksionit dhe të integruara nuk mbështetet ende, por do të vijë së shpejti.
MCP në distancë : Gemini 3 nuk e mbështet mcp në distancë, kjo do të vijë së shpejti.
Ndryshime të rëndësishme
API-ja e Ndërveprimeve është aktualisht në një fazë të hershme beta. Ne po zhvillojmë dhe përsosim në mënyrë aktive aftësitë e API-t, skemat e burimeve dhe ndërfaqet e SDK-së bazuar në përdorimin në botën reale dhe reagimet e zhvilluesve.
Si rezultat, mund të ndodhin ndryshime të rëndësishme . Përditësimet mund të përfshijnë ndryshime në:
- Skemat për të dhënat hyrëse dhe dalëse.
- Nënshkrimet e metodave SDK dhe strukturat e objekteve.
- Sjelljet e karakteristikave specifike.
Për ngarkesat e punës në prodhim, duhet të vazhdoni të përdorni API-n standard generateContent . Ai mbetet rruga e rekomanduar për vendosje të qëndrueshme dhe do të vazhdojë të zhvillohet dhe mirëmbahet në mënyrë aktive.
Reagime
Reagimet tuaja janë thelbësore për zhvillimin e API-t të Ndërveprimeve. Ju lutemi ndani mendimet tuaja, raportoni gabime ose kërkoni veçori në Forumin tonë të Komunitetit të Zhvilluesve të IA-së në Google .
Çfarë vjen më pas
- Mësoni më shumë rreth Agjentit të Kërkimeve të Thellë Gemini .