Questa guida rapida mostra come installare le nostre librerie ed effettuare la prima richiesta, trasmettere in streaming le risposte, creare conversazioni multi-turno e utilizzare gli strumenti.
Esistono due modi per inviare una richiesta all'API Gemini:
- (Consigliato) L'API Interactions è una nuova primitiva con supporto integrato per l'utilizzo di strumenti in più passaggi, l'orchestrazione e flussi di ragionamento complessi tramite passaggi di esecuzione digitati. In futuro, i nuovi modelli oltre alla famiglia principale di base, insieme a nuove capacità agentiche e strumenti, verranno lanciati esclusivamente sull'API Interactions.
generateContentfornisce un modo per generare una risposta stateless da un modello. Sebbene consigliamo di utilizzare l'API Interactions,generateContentè completamente supportata.
Questa versione della guida rapida utilizza l'API Interactions per inviare una richiesta all'API Gemini.
Prima di iniziare
Per utilizzare l'API Gemini, devi disporre di una chiave API per autenticare le richieste, applicare limiti di sicurezza e monitorare l'utilizzo del tuo account.
Per iniziare, creane uno su AI Studio senza costi:
Installa l'SDK Google GenAI
Python
Utilizzando Python 3.9+, installa il
pacchetto google-genai
utilizzando il seguente
comando pip:
pip install -q -U google-genai
JavaScript
Utilizzando Node.js v18+, installa SDK Google Gen AI per TypeScript e JavaScript utilizzando il seguente comando npm:
npm install @google/genai
Genera testo
Utilizza il metodo interactions.create per
generare una risposta di testo.
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"
}'
Risposte dinamiche
Per impostazione predefinita, il modello restituisce una risposta solo dopo il completamento dell'intero processo di generazione. Per un'esperienza più rapida e interattiva, puoi trasmettere in streaming i blocchi della risposta man mano che vengono generati.
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
}'
Conversazioni a più turni
L'API Gemini supporta la creazione di
conversazioni multi-turno.
Basta passare il valore id restituito dall'interazione precedente come parametro previous_interaction_id e il server gestisce automaticamente la cronologia delle conversazioni.
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\"
}"
Utilizzare gli strumenti
Estendi le funzionalità del modello basando le risposte sulla Ricerca Google per accedere a contenuti web in tempo reale. Il modello decide automaticamente quando eseguire ricerche, esegue query e sintetizza una risposta con citazioni.
Il seguente esempio mostra come attivare la Ricerca 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"}]
}'
L'API Gemini supporta anche altri strumenti integrati:
- Esecuzione del codice: Consente al modello di scrivere ed eseguire codice Python per risolvere problemi matematici complessi.
- Contesto URL: consente di basare le risposte su URL di pagine web specifici che fornisci.
- Ricerca di file: ti consente di caricare file e basare le risposte sui loro contenuti utilizzando la ricerca semantica.
- Google Maps: ti consente di basare le risposte sui dati sulla posizione e cercare luoghi, indicazioni e mappe.
- Utilizzo del computer: consente al modello di interagire con uno schermo, una tastiera e un mouse virtuali per eseguire attività.
Chiamare funzioni personalizzate
Utilizza le chiamate di funzione
per connettere i modelli alle tue API e ai tuoi strumenti personalizzati. Il modello determina quando chiamare la funzione e restituisce un passaggio function_call con gli argomenti da eseguire per l'applicazione.
Questo esempio dichiara una funzione di temperatura simulata e verifica se il modello vuole chiamarla.
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"]
}
}]
}'
Passaggi successivi
Ora che hai iniziato a utilizzare l'API Gemini, esplora le seguenti guide per creare applicazioni più avanzate: