Eseguire la migrazione all'SDK Google GenAI

A partire dalla release di Gemini 2.0 alla fine del 2024, abbiamo introdotto un nuovo insieme di librerie chiamato Google GenAI SDK. Offre un'esperienza di sviluppo migliorata grazie a un'architettura client aggiornata e semplifica la transizione tra i flussi di lavoro per sviluppatori ed enterprise.

Google GenAI SDK è ora in disponibilità generale (GA) su tutte le piattaforme supportate. Se utilizzi una delle nostre librerie legacy, ti consigliamo vivamente di eseguire la migrazione.

Questa guida fornisce esempi di codice migrato prima e dopo per aiutarti a iniziare.

Installazione

Prima

Python

pip install -U -q "google-generativeai"

JavaScript

npm install @google/generative-ai

Vai

go get github.com/google/generative-ai-go

Dopo

Python

pip install -U -q "google-genai"

JavaScript

npm install @google/genai

Vai

go get google.golang.org/genai

Accesso API

Il vecchio SDK gestiva implicitamente il client API dietro le quinte utilizzando una serie di metodi ad hoc. Ciò rendeva difficile la gestione del client e delle credenziali. Ora interagisci tramite un oggetto Client centrale. Questo oggetto Client funge da unico punto di accesso per vari servizi API (ad es. models, chats, files, tunings), promuovendo la coerenza e semplificando la gestione delle credenziali e della configurazione tra le diverse chiamate API.

Prima (accesso API meno centralizzato)

Python

Il vecchio SDK non utilizzava esplicitamente un oggetto client di primo livello per la maggior parte delle chiamate API. Avresti istanziato e interagito direttamente con gli oggetti GenerativeModel.

import google.generativeai as genai

# Directly create and use model objects
model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content(...)
chat = model.start_chat(...)

JavaScript

Sebbene GoogleGenerativeAI fosse un punto centrale per i modelli e la chat, altre funzionalità come la gestione di file e cache spesso richiedevano l'importazione e l'istanza di classi client completamente separate.

import { GoogleGenerativeAI } from "@google/generative-ai";
import { GoogleAIFileManager, GoogleAICacheManager } from "@google/generative-ai/server"; // For files/caching

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const fileManager = new GoogleAIFileManager("GEMINI_API_KEY");
const cacheManager = new GoogleAICacheManager("GEMINI_API_KEY");

// Get a model instance, then call methods on it
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });
const result = await model.generateContent(...);
const chat = model.startChat(...);

// Call methods on separate client objects for other services
const uploadedFile = await fileManager.uploadFile(...);
const cache = await cacheManager.create(...);

Vai

La funzione genai.NewClient ha creato un client, ma le operazioni del modello generativo venivano in genere chiamate su un'istanza GenerativeModel separata ottenuta da questo client. È possibile che ad altri servizi si sia acceduto tramite pacchetti o pattern distinti.

import (
      "github.com/google/generative-ai-go/genai"
      "github.com/google/generative-ai-go/genai/fileman" // For files
      "google.golang.org/api/option"
)

client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
fileClient, err := fileman.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))

// Get a model instance, then call methods on it
model := client.GenerativeModel("gemini-3.5-flash")
resp, err := model.GenerateContent(...)
cs := model.StartChat()

// Call methods on separate client objects for other services
uploadedFile, err := fileClient.UploadFile(...)

Dopo (oggetto client centralizzato)

Python

from google import genai

# Create a single client object
client = genai.Client()

# Access API methods through services on the client object
response = client.models.generate_content(...)
chat = client.chats.create(...)
my_file = client.files.upload(...)
tuning_job = client.tunings.tune(...)

JavaScript

import { GoogleGenAI } from "@google/genai";

// Create a single client object
const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});

// Access API methods through services on the client object
const response = await ai.models.generateContent(...);
const chat = ai.chats.create(...);
const uploadedFile = await ai.files.upload(...);
const cache = await ai.caches.create(...);

Vai

import "google.golang.org/genai"

// Create a single client object
client, err := genai.NewClient(ctx, nil)

// Access API methods through services on the client object
result, err := client.Models.GenerateContent(...)
chat, err := client.Chats.Create(...)
uploadedFile, err := client.Files.Upload(...)
tuningJob, err := client.Tunings.Tune(...)

Autenticazione

Sia le librerie legacy sia quelle nuove eseguono l'autenticazione utilizzando le chiavi API. Puoi creare la tua chiave API in Google AI Studio.

Prima

Python

Il vecchio SDK gestiva implicitamente l'oggetto client API.

import google.generativeai as genai

genai.configure(api_key=...)

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");

Vai

Importa le librerie Google:

import (
      "github.com/google/generative-ai-go/genai"
      "google.golang.org/api/option"
)

Crea il client:

client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))

Dopo

Python

Con Google GenAI SDK, crei prima un client API, che viene utilizzato per chiamare l'API. Il nuovo SDK recupererà la tua chiave API dalle variabili di ambiente GEMINI_API_KEY, se non ne passi una al client.

export GEMINI_API_KEY="YOUR_API_KEY"
from google import genai

client = genai.Client() # Set the API key using the GEMINI_API_KEY env var.
                        # Alternatively, you could set the API key explicitly:
                        # client = genai.Client(api_key="YOUR_API_KEY")

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});

Vai

Importa la libreria GenAI:

import "google.golang.org/genai"

Crea il client:

client, err := genai.NewClient(ctx, &genai.ClientConfig{
        Backend:  genai.BackendGeminiAPI,
})

Generazione di contenuti

Testo

Prima

Python

In precedenza, non esistevano oggetti client, ma si accedeva alle API direttamente tramite gli oggetti GenerativeModel.

import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content(
    'Tell me a story in 300 words'
)
print(response.text)

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });
const prompt = "Tell me a story in 300 words";

const result = await model.generateContent(prompt);
console.log(result.response.text());

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-3.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Tell me a story in 300 words."))
if err != nil {
    log.Fatal(err)
}

printResponse(resp) // utility for printing response parts

Dopo

Python

Il nuovo Google GenAI SDK fornisce l'accesso a tutti i metodi API tramite l'oggetto Client. Ad eccezione di alcuni casi speciali con stato (chat e session live-api), si tratta di funzioni senza stato. Per utilità e uniformità, gli oggetti restituiti sono classi pydantic.

from google import genai
client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.5-flash',
    contents='Tell me a story in 300 words.'
)
print(response.text)

print(response.model_dump_json(
    exclude_none=True, indent=4))

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: "Tell me a story in 300 words.",
});
console.log(response.text);

Vai

ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

result, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", genai.Text("Tell me a story in 300 words."), nil)
if err != nil {
    log.Fatal(err)
}
debugPrint(result) // utility for printing result

Immagine

Prima

Python

import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content([
    'Tell me a story based on this image',
    Image.open(image_path)
])
print(response.text)

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Tell me a story based on this image";

const imagePart = fileToGenerativePart(
  `path/to/organ.jpg`,
  "image/jpeg",
);

const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-3.5-flash")

imgData, err := os.ReadFile("path/to/organ.jpg")
if err != nil {
    log.Fatal(err)
}

resp, err := model.GenerateContent(ctx,
    genai.Text("Tell me about this instrument"),
    genai.ImageData("jpeg", imgData))
if err != nil {
    log.Fatal(err)
}

printResponse(resp) // utility for printing response

Dopo

Python

Molte delle stesse funzionalità di praticità sono presenti nel nuovo SDK. Ad esempio, gli oggetti PIL.Image vengono convertiti automaticamente.

from google import genai
from PIL import Image

client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.5-flash',
    contents=[
        'Tell me a story based on this image',
        Image.open(image_path)
    ]
)
print(response.text)

JavaScript

import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

const organ = await ai.files.upload({
  file: "path/to/organ.jpg",
});

const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: [
    createUserContent([
      "Tell me a story based on this image",
      createPartFromUri(organ.uri, organ.mimeType)
    ]),
  ],
});
console.log(response.text);

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

imgData, err := os.ReadFile("path/to/organ.jpg")
if err != nil {
    log.Fatal(err)
}

parts := []*genai.Part{
    {Text: "Tell me a story based on this image"},
    {InlineData: &genai.Blob{Data: imgData, MIMEType: "image/jpeg"}},
}
contents := []*genai.Content{
    {Parts: parts},
}

result, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
    log.Fatal(err)
}
debugPrint(result) // utility for printing result

Streaming

Prima

Python

import google.generativeai as genai

response = model.generate_content(
    "Write a cute story about cats.",
    stream=True)
for chunk in response:
    print(chunk.text)

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });

const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream(prompt);

// Print text as it comes in.
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-3.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
    resp, err := iter.Next()
    if err == iterator.Done {
        break
    }
    if err != nil {
        log.Fatal(err)
    }
    printResponse(resp) // utility for printing the response
}

Dopo

Python

from google import genai

client = genai.Client()

for chunk in client.models.generate_content_stream(
  model='gemini-3.5-flash',
  contents='Tell me a story in 300 words.'
):
    print(chunk.text)

JavaScript

import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

const response = await ai.models.generateContentStream({
  model: "gemini-3.5-flash",
  contents: "Write a story about a magic backpack.",
});
let text = "";
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

for result, err := range client.Models.GenerateContentStream(
    ctx,
    "gemini-3.5-flash",
    genai.Text("Write a story about a magic backpack."),
    nil,
) {
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}

Configurazione

Prima

Python

import google.generativeai as genai

model = genai.GenerativeModel(
  'gemini-3.5-flash',
    system_instruction='you are a story teller for kids under 5 years old',
    generation_config=genai.GenerationConfig(
      max_output_tokens=400,
      top_k=2,
      top_p=0.5,
      temperature=0.5,
      response_mime_type='application/json',
      stop_sequences=['\n'],
    )
)
response = model.generate_content('tell me a story in 100 words')

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({
  model: "gemini-3.5-flash",
  generationConfig: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

const result = await model.generateContent(
  "Tell me a story about a magic backpack.",
);
console.log(result.response.text())

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
if err != nil {
    log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-3.5-flash")
model.SetTemperature(0.5)
model.SetTopP(0.5)
model.SetTopK(2.0)
model.SetMaxOutputTokens(100)
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("Tell me about New York"))
if err != nil {
    log.Fatal(err)
}
printResponse(resp) // utility for printing response

Dopo

Python

Per tutti i metodi del nuovo SDK, gli argomenti obbligatori vengono forniti come argomenti con parole chiave. Tutti gli input facoltativi vengono forniti nell'argomento config. Gli argomenti di configurazione possono essere specificati come dizionari Python o come classi Config nello spazio dei nomi google.genai.types. Per utilità e uniformità, tutte le definizioni all'interno del modulo types sono classi pydantic.

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
  model='gemini-3.5-flash',
  contents='Tell me a story in 100 words.',
  config=types.GenerateContentConfig(
      system_instruction='you are a story teller for kids under 5 years old',
      max_output_tokens= 400,
      top_k= 2,
      top_p= 0.5,
      temperature= 0.5,
      response_mime_type= 'application/json',
      stop_sequences= ['\n'],
      seed=42,
  ),
)

JavaScript

import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: "Tell me a story about a magic backpack.",
  config: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

console.log(response.text);

Vai

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err