Using files

A API Gemini permite fazer upload de arquivos de mídia separadamente da entrada de comando, o que permite reutilizar sua mídia em várias solicitações e comandos. Para mais detalhes, consulte o guia Comandos com mídia.

Recurso REST: files

Recurso: File

Um arquivo enviado para a API. Próximo ID: 15

Campos
name string

Imutável. Identificador. O nome do recurso File. O ID (nome sem o prefixo "files/") pode conter até 40 caracteres alfanuméricos minúsculos ou traços (-). Ele não pode começar nem terminar com um traço. Se o nome estiver vazio na criação, um nome exclusivo será gerado. Exemplo: files/123-456

displayName string

Opcional. O nome de exibição legível para o File. O nome de exibição não pode ter mais de 512 caracteres, incluindo espaços. Exemplo: "Imagem de boas-vindas"

mimeType string

Apenas saída. Tipo MIME do arquivo.

sizeBytes string (int64 format)

Apenas saída. Tamanho do arquivo em bytes.

createTime string (Timestamp format)

Apenas saída. O carimbo de data/hora de quando o File foi criado.

Usa o padrão RFC 3339, em que a saída gerada é sempre convertida em Z e tem 0, 3, 6 ou 9 dígitos fracionários. Além de "Z", outros ajustes também são aceitos. Exemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" ou "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Apenas saída. O carimbo de data/hora da última atualização do File.

Usa o padrão RFC 3339, em que a saída gerada é sempre convertida em Z e tem 0, 3, 6 ou 9 dígitos fracionários. Além de "Z", outros ajustes também são aceitos. Exemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" ou "2014-10-02T15:01:23+05:30".

expirationTime string (Timestamp format)

Apenas saída. O carimbo de data/hora de quando o File será excluído. Só é definido se a File estiver programada para expirar.

Usa o padrão RFC 3339, em que a saída gerada é sempre convertida em Z e tem 0, 3, 6 ou 9 dígitos fracionários. Além de "Z", outros ajustes também são aceitos. Exemplos: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" ou "2014-10-02T15:01:23+05:30".

sha256Hash string (bytes format)

Apenas saída. Hash SHA-256 dos bytes enviados.

Uma string codificada em base64.

uri string

Apenas saída. O URI do File.

downloadUri string

Apenas saída. O URI de download do File.

state enum (State)

Apenas saída. Estado de processamento do arquivo.

source enum (Source)

Origem do arquivo.

error object (google.rpc.Status)

Apenas saída. Status de erro se o processamento do arquivo falhar.

metadata Union type
Metadados do arquivo. metadata pode ser apenas de um dos tipos a seguir:
videoMetadata object (VideoFileMetadata)

Apenas saída. Metadados de um vídeo.

Representação JSON
{
  "name": string,
  "displayName": string,
  "mimeType": string,
  "sizeBytes": string,
  "createTime": string,
  "updateTime": string,
  "expirationTime": string,
  "sha256Hash": string,
  "uri": string,
  "downloadUri": string,
  "state": enum (State),
  "source": enum (Source),
  "error": {
    object (google.rpc.Status)
  },

  // metadata
  "videoMetadata": {
    object (VideoFileMetadata)
  }
  // Union type
}

VideoFileMetadata

Metadados de um vídeo File.

Campos
videoDuration string (Duration format)

Duração do vídeo.

Duração em segundos com até nove dígitos fracionários, terminando em "s". Exemplo: "3.5s".

Representação JSON
{
  "videoDuration": string
}

Estado

Estados do ciclo de vida de um arquivo.

Tipos enumerados
STATE_UNSPECIFIED O valor padrão. Esse valor é usado se o estado for omitido.
PROCESSING O arquivo está sendo processado e ainda não pode ser usado para inferência.
ACTIVE O arquivo é processado e fica disponível para inferência.
FAILED Falha ao processar o arquivo.

Origem

Tipos enumerados
SOURCE_UNSPECIFIED Usado se a origem não for especificada.
UPLOADED Indica que o arquivo foi enviado pelo usuário.
GENERATED Indica que o arquivo foi gerado pelo Google.
REGISTERED Indica que o arquivo é registrado, ou seja, um arquivo do Google Cloud Storage.

Método: files.get

Recebe os metadados do File especificado.

Endpoint

get https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Parâmetros de caminho

name string

Obrigatório. O nome do File a ser recebido. Exemplo: files/abc-123. Ele assume a forma files/{file}.

Corpo da solicitação

O corpo da solicitação precisa estar vazio.

Exemplo de solicitação

Python

from google import genai

client = genai.Client()
myfile = client.files.upload(file=media / "poem.txt")
file_name = myfile.name
print(file_name)  # "files/*"

myfile = client.files.get(name=file_name)
print(myfile)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const myfile = await ai.files.upload({
  file: path.join(media, "poem.txt"),
});
const fileName = myfile.name;
console.log(fileName);

const fetchedFile = await ai.files.get({ name: fileName });
console.log(fetchedFile);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
myfile, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "poem.txt"), 
	&genai.UploadFileConfig{
		MIMEType: "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
fileName := myfile.Name
fmt.Println(fileName)
file, err := client.Files.Get(ctx, fileName, nil)
if err != nil {
	log.Fatal(err)
}
fmt.Println(file)

Shell

name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

Corpo da resposta

Se a solicitação for bem-sucedida, o corpo da resposta conterá uma instância de File.

Método: files.list

Lista os metadados dos Files pertencentes ao projeto solicitante.

Endpoint

get https://generativelanguage.googleapis.com/v1beta/files

Parâmetros de consulta

pageSize integer

Opcional. Número máximo de Files a serem retornados por página. Se não for especificado, o padrão será 10. O valor máximo de pageSize é 100.

pageToken string

Opcional. Um token de página de uma chamada files.list anterior.

Corpo da solicitação

O corpo da solicitação precisa estar vazio.

Exemplo de solicitação

Python

from google import genai

client = genai.Client()
print("My files:")
for f in client.files.list():
    print("  ", f.name)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
console.log("My files:");
// Using the pager style to list files
const pager = await ai.files.list({ config: { pageSize: 10 } });
let page = pager.page;
const names = [];
while (true) {
  for (const f of page) {
    console.log("  ", f.name);
    names.push(f.name);
  }
  if (!pager.hasNextPage()) break;
  page = await pager.nextPage();
}

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("My files:")
page, err := client.Files.List(ctx, nil)
if err != nil {
	log.Fatal(err)
}
for _, f := range page.Items {
	fmt.Println("  ", f.Name)
}

Shell

echo "My files: "

curl "https://generativelanguage.googleapis.com/v1beta/files?key=$GEMINI_API_KEY"

Corpo da resposta

Resposta para files.list.

Se bem-sucedido, o corpo da resposta incluirá dados com a estrutura a seguir:

Campos
files[] object (File)

A lista de Files.

nextPageToken string

Um token que pode ser enviado como um pageToken em uma chamada files.list subsequente.

Representação JSON
{
  "files": [
    {
      object (File)
    }
  ],
  "nextPageToken": string
}

Método: files.delete

Exclui o File.

Endpoint

delete https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Parâmetros de caminho

name string

Obrigatório. O nome do File a ser excluído. Exemplo: files/abc-123. Ele assume a forma files/{file}.

Corpo da solicitação

O corpo da solicitação precisa estar vazio.

Exemplo de solicitação

Python

from google import genai

client = genai.Client()
myfile = client.files.upload(file=media / "poem.txt")

client.files.delete(name=myfile.name)

try:
    result = client.models.generate_content(
        model="gemini-3.5-flash", contents=[myfile, "Describe this file."]
    )
    print(result)
except genai.errors.ClientError:
    pass

Node.js

// The Gen AI SDK for TypeScript and JavaScript is in preview.
// Some features have not been implemented.

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
myfile, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "poem.txt"), 
	&genai.UploadFileConfig{
		MIMEType: "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
// Delete the file.
_, err = client.Files.Delete(ctx, myfile.Name, nil)
if err != nil {
	log.Fatal(err)
}
// Attempt to use the deleted file.
parts := []*genai.Part{
	genai.NewPartFromURI(myfile.URI, myfile.MIMEType,),
	genai.NewPartFromText("Describe this file."),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

_, err = client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
// Expect an error when using a deleted file.
if err != nil {
	return nil
}
return fmt.Errorf("expected an error when using deleted file")

Shell

curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GEMINI_API_KEY

Corpo da resposta

Se não houver nenhum problema, o corpo da resposta será um objeto JSON vazio.

Método: files.register

Registra arquivos do Google Cloud Storage com o FileService. O usuário precisa fornecer URIs do Google Cloud Storage e vai receber um recurso "File" para cada URI em troca. Observação: os arquivos não são copiados, apenas registrados com a API File. Se um arquivo não for registrado, toda a solicitação vai falhar.

Endpoint

post https://generativelanguage.googleapis.com/v1beta/files:register

Corpo da solicitação

O corpo da solicitação contém dados com a seguinte estrutura:

Campos
uris[] string

Obrigatório. Os URIs do Google Cloud Storage a serem registrados. Exemplo: gs://bucket/object.

Corpo da resposta

Resposta para files.register.

Se bem-sucedido, o corpo da resposta incluirá dados com a estrutura a seguir:

Campos
files[] object (File)

Os arquivos registrados a serem usados ao chamar o GenerateContent.

Representação JSON
{
  "files": [
    {
      object (File)
    }
  ]
}

Método: media.upload

Cria uma File.

Endpoint

  • URI de upload, para solicitações de upload de mídia:
post https://generativelanguage.googleapis.com/upload/v1beta/files
  • URI de metadados, para solicitações somente de metadados:
post https://generativelanguage.googleapis.com/v1beta/files

Corpo da solicitação

O corpo da solicitação contém dados com a seguinte estrutura:

Campos
file object (File)

Opcional. Metadados do arquivo a ser criado.

Exemplo de solicitação

Imagem

Python

from google import genai

client = genai.Client()
myfile = client.files.upload(file=media / "Cajun_instruments.jpg")
print(f"{myfile=}")

result = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[
        myfile,
        "\n\n",
        "Can you tell me about the instruments in this photo?",
    ],
)
print(f"{result.text=}")

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const myfile = await ai.files.upload({
  file: path.join(media, "Cajun_instruments.jpg"),
  config: { mimeType: "image/jpeg" },
});
console.log("Uploaded file:", myfile);

const result = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "\n\n",
    "Can you tell me about the instruments in this photo?",
  ]),
});
console.log("result.text=", result.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
myfile, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "Cajun_instruments.jpg"), 
	&genai.UploadFileConfig{
		MIMEType : "image/jpeg",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("myfile=%+v\n", myfile)

parts := []*genai.Part{
	genai.NewPartFromURI(myfile.URI, myfile.MIMEType),
	genai.NewPartFromText("\n\n"),
	genai.NewPartFromText("Can you tell me about the instruments in this photo?"),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
text := response.Text()
fmt.Printf("result.text=%s\n", text)

Shell

MIME_TYPE=$(file -b --mime-type "${IMG_PATH_2}")
NUM_BYTES=$(wc -c < "${IMG_PATH_2}")
DISPLAY_NAME=TEXT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${IMG_PATH_2}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you tell me about the instruments in this photo?"},
          {"file_data":
            {"mime_type": "image/jpeg", 
            "file_uri": '$file_uri'}
        }]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Áudio

Python

from google import genai

client = genai.Client()
myfile = client.files.upload(file=media / "sample.mp3")
print(f"{myfile=}")

result = client.models.generate_content(
    model="gemini-3.5-flash", contents=[myfile, "Describe this audio clip"]
)
print(f"{result.text=}")

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const myfile = await ai.files.upload({
  file: path.join(media, "sample.mp3"),
  config: { mimeType: "audio/mpeg" },
});
console.log("Uploaded file:", myfile);

const result = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Describe this audio clip",
  ]),
});
console.log("result.text=", result.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
myfile, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "sample.mp3"), 
	&genai.UploadFileConfig{
		MIMEType : "audio/mpeg",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("myfile=%+v\n", myfile)

parts := []*genai.Part{
	genai.NewPartFromURI(myfile.URI, myfile.MIMEType),
	genai.NewPartFromText("Describe this audio clip"),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
text := response.Text()
fmt.Printf("result.text=%s\n", text)

Shell

MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this audio clip"},
          {"file_data":{"mime_type": "audio/mp3", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

Texto

Python

from google import genai

client = genai.Client()
myfile = client.files.upload(file=media / "poem.txt")
print(f"{myfile=}")

result = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=[myfile, "\n\n", "Can you add a few more lines to this poem?"],
)
print(f"{result.text=}")

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const myfile = await ai.files.upload({
  file: path.join(media, "poem.txt"),
});
console.log("Uploaded file:", myfile);

const result = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "\n\n",
    "Can you add a few more lines to this poem?",
  ]),
});
console.log("result.text=", result.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

myfile, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "poem.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("myfile=%+v\n", myfile)

parts := []*genai.Part{
	genai.NewPartFromURI(myfile.URI, myfile.MIMEType),
	genai.NewPartFromText("\n\n"),
	genai.NewPartFromText("Can you add a few more lines to this poem?"),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
text := response.Text()
fmt.Printf("result.text=%s\n", text)

Shell

MIME_TYPE=$(file -b --mime-type "${TEXT_PATH}")
NUM_BYTES=$(wc -c < "${TEXT_PATH}")
DISPLAY_NAME=TEXT

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${TEXT_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Can you add a few more lines to this poem?"},
          {"file_data":{"mime_type": "text/plain", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GEMINI_API_KEY

Vídeo

Python

from google import genai
import time

client = genai.Client()
# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = client.files.upload(file=media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Poll until the video file is completely processed (state becomes ACTIVE).
while not myfile.state or myfile.state.name != "ACTIVE":
    print("Processing video...")
    print("File state:", myfile.state)
    time.sleep(5)
    myfile = client.files.get(name=myfile.name)

result = client.models.generate_content(
    model="gemini-3.5-flash", contents=[myfile, "Describe this video clip"]
)
print(f"{result.text=}")

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
let myfile = await ai.files.upload({
  file: path.join(media, "Big_Buck_Bunny.mp4"),
  config: { mimeType: "video/mp4" },
});
console.log("Uploaded video file:", myfile);

// Poll until the video file is completely processed (state becomes ACTIVE).
while (!myfile.state || myfile.state.toString() !== "ACTIVE") {
  console.log("Processing video...");
  console.log("File state: ", myfile.state);
  await sleep(5000);
  myfile = await ai.files.get({ name: myfile.name });
}

const result = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Describe this video clip",
  ]),
});
console.log("result.text=", result.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
myfile, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "Big_Buck_Bunny.mp4"), 
	&genai.UploadFileConfig{
		MIMEType : "video/mp4",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("myfile=%+v\n", myfile)

// Poll until the video file is completely processed (state becomes ACTIVE).
for myfile.State == genai.FileStateUnspecified || myfile.State != genai.FileStateActive {
	fmt.Println("Processing video...")
	fmt.Println("File state:", myfile.State)
	time.Sleep(5 * time.Second)

	myfile, err = client.Files.Get(ctx, myfile.Name, nil)
	if err != nil {
		log.Fatal(err)
	}
}

parts := []*genai.Part{
	genai.NewPartFromURI(myfile.URI, myfile.MIMEType),
	genai.NewPartFromText("Describe this video clip"),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
text := response.Text()
fmt.Printf("result.text=%s\n", text)

Shell

MIME_TYPE=$(file -b --mime-type "${VIDEO_PATH}")
NUM_BYTES=$(wc -c < "${VIDEO_PATH}")
DISPLAY_NAME=VIDEO_PATH

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GEMINI_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${VIDEO_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

state=$(jq ".file.state" file_info.json)
echo state=$state

# Ensure the state of the video is 'ACTIVE'
while [[ "($state)" = *"PROCESSING"* ]];
do
  echo "Processing video..."
  sleep 5
  # Get the file of interest to check state
  curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
  state=$(jq ".file.state" file_info.json)
done

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this video clip"},
          {"file_data":{"mime_type": "video/mp4", "file_uri": '$file_uri'}}]
        }]
       }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

PDF

Python

from google import genai

client = genai.Client()
sample_pdf = client.files.upload(file=media / "test.pdf")
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents=["Give me a summary of this pdf file.", sample_pdf],
)
print(response.text)

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}
samplePdf, err := client.Files.UploadFromPath(
	ctx,
	filepath.Join(getMedia(), "test.pdf"),
	&genai.UploadFileConfig{
		MIMEType: "application/pdf",
	},
)
if err != nil {
	log.Fatal(err)
}

parts := []*genai.Part{
	genai.NewPartFromText("Give me a summary of this pdf file."),
	genai.NewPartFromURI(samplePdf.URI, samplePdf.MIMEType),
}

contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

response, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
	log.Fatal(err)
}
text := response.Text()
fmt.Println(text)

Corpo da resposta

Resposta para media.upload.

Se bem-sucedido, o corpo da resposta incluirá dados com a estrutura a seguir:

Campos
file object (File)

Metadados do arquivo criado.

Representação JSON
{
  "file": {
    object (File)
  }
}

Status

O status da interação.

Tipos enumerados
UNSPECIFIED Valor padrão. Esse valor não é usado.
IN_PROGRESS A interação está em andamento.
REQUIRES_ACTION A interação exige ação/entrada do usuário.
COMPLETED A interação é concluída.
FAILED A interação falhou.
CANCELLED A interação foi cancelada.
INCOMPLETE A interação foi concluída, mas contém resultados incompletos (por exemplo, atingiu maxTokens).
BUDGET_EXCEEDED A interação foi interrompida porque o orçamento de tokens foi excedido.