Neste guia de início rápido, mostramos como instalar nossas bibliotecas e fazer sua primeira solicitação à API Gemini.
Antes de começar
Você precisa de uma chave da API Gemini. Se você ainda não tiver uma, crie uma sem custo financeiro no Google AI Studio.
Instalar o SDK da IA generativa do Google
Python
Usando o Python 3.9 ou mais recente, instale o
pacote google-genai
com o seguinte
comando pip:
pip install -q -U google-genai
JavaScript
Usando o Node.js v18+, instale o SDK da IA generativa do Google para TypeScript e JavaScript usando o seguinte comando npm:
npm install @google/genai
Go
Instale google.golang.org/genai no diretório do módulo usando o comando go get:
go get google.golang.org/genai
Java
Se você estiver usando o Maven, instale google-genai adicionando o seguinte às suas dependências:
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
Apps Script
- Para criar um projeto do Apps Script, acesse script.new.
- Clique em Projeto sem título.
- Renomeie o projeto do Apps Script como AI Studio e clique em Renomear.
- Defina sua chave de API
- À esquerda, clique em Configurações do projeto
.
- Em Propriedades do script, clique em Adicionar propriedade do script.
- Em Propriedade, insira o nome da chave:
GEMINI_API_KEY
. - Em Valor, insira o valor da chave de API.
- Clique em Salvar propriedades do script.
- À esquerda, clique em Configurações do projeto
- Substitua o conteúdo do arquivo
Code.gs
pelo seguinte código:
Faça sua primeira solicitação
Este é um exemplo que usa o método
generateContent
para enviar uma solicitação à API Gemini usando o modelo Gemini 2.5 Flash.
Se você definir sua chave de API como a
variável de ambiente GEMINI_API_KEY
, ela será selecionada automaticamente pelo
cliente ao usar as bibliotecas da API Gemini.
Caso contrário, será necessário transmitir a chave de API como
um argumento ao inicializar o cliente.
Todas as amostras de código na documentação da API Gemini pressupõem que você definiu a variável de ambiente GEMINI_API_KEY
.
Python
from google import genai
# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash", contents="Explain how AI works in a few words"
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain how AI works in a few words",
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("Explain how AI works in a few words"),
nil,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
Java
package com.example;
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateTextFromTextInput {
public static void main(String[] args) {
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
Client client = new Client();
GenerateContentResponse response =
client.models.generateContent(
"gemini-2.5-flash",
"Explain how AI works in a few words",
null);
System.out.println(response.text());
}
}
Apps Script
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
const payload = {
contents: [
{
parts: [
{ text: 'Explain how AI works in a few words' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
const options = {
method: 'POST',
contentType: 'application/json',
headers: {
'x-goog-api-key': apiKey,
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response);
const content = data['candidates'][0]['content']['parts'][0]['text'];
console.log(content);
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in a few words"
}
]
}
]
}'
O "Pensamento" está ativado por padrão em muitos dos nossos exemplos de código.
Muitos exemplos de código neste site usam o modelo Gemini 2.5 Flash, que tem o recurso "pensamento" ativado por padrão para melhorar a qualidade da resposta. Isso pode aumentar o tempo de resposta e o uso de tokens. Se você priorizar a velocidade ou quiser minimizar os custos, desative esse recurso definindo o orçamento de pensamento como zero, conforme mostrado nos exemplos abaixo. Para mais detalhes, consulte o guia de reflexão.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain how AI works in a few words",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking
),
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain how AI works in a few words",
config: {
thinkingConfig: {
thinkingBudget: 0, // Disables thinking
},
}
});
console.log(response.text);
}
await main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("Explain how AI works in a few words"),
&genai.GenerateContentConfig{
ThinkingConfig: &genai.ThinkingConfig{
ThinkingBudget: int32(0), // Disables thinking
},
}
)
fmt.Println(result.Text())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in a few words"
}
]
}
]
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 0
}
}
}'
Apps Script
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
const payload = {
contents: [
{
parts: [
{ text: 'Explain how AI works in a few words' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
const options = {
method: 'POST',
contentType: 'application/json',
headers: {
'x-goog-api-key': apiKey,
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response);
const content = data['candidates'][0]['content']['parts'][0]['text'];
console.log(content);
}
A seguir
Agora que você fez sua primeira solicitação de API, talvez queira conferir os seguintes guias que mostram o Gemini em ação: