Gemini Files API: upload media, use its URI, and clean up the file
Upload one audio file with Python, describe it via its uri, then inspect and delete it by name. Based on the official page; nothing was run.
Task and deliverable · Prepare the input and environment · Mechanism and data flow
At a glance
This tutorial follows one audio file through the Gemini Files API: upload, a description request, a metadata check, a list check and deletion. It relies only on the official Files API page and its Python excerpts. No product or API was run while writing it.
Task workflow
Two identifiers, two jobs
After
files.uploadreturns, the object inmyfilecarries several fields that the excerpts use.myfile.uriandmyfile.mime_typego into theaudiopart of theinteractions.createinput, next to atextpart with the prompt.myfile.nameis what the excerpts pass tofiles.getandfiles.delete. The page uses the URI for the model request and the name for metadata and deletion, so save both. The page also notes that URIs returned byfiles.uploadandfiles.getwork interchangeably acrossv1andv1betarequests.Storage rules reported by the page
Files are stored for 48 hours and are deleted automatically after that. The Files API holds up to 20 GB per project, with a 2 GB maximum per file. During the storage window you can get metadata, but you cannot download user-uploaded files;
files.downloadis documented for files generated by models, such as videos. It also says the API is available at no cost in all regions where the Gemini API is available, so check current terms yourself. For request size, the page says to always use the Files API when the total, counting files, text prompt and system instructions, is larger than 100 MB, and the limit for PDF files is 50 MB.Four excerpts, not one program
The page presents the four Python excerpts as independent examples. The describe, get and delete excerpts each call
files.upload. Running all four successfully in order performs three uploads, and the delete excerpt immediately deletes the third uploaded file. The first two remain stored until separately deleted or automatically expired. The list excerpt only printsf.namefor stored files. The get excerpt callsfiles.getonce and prints the result; it has no loop and does not wait for any state. The workflow below is an editorial combination that uploads once and reuses the samenameanduri. The page does not present it as a single sample.Editorial controls
The page does not describe success checks, cancellation or credential handling for this task. This tutorial's checks, stop rules and credential cleanup are editorial recommendations. Delete only files positively identified as belonging to this task. If identity is uncertain, or listing, deletion or verification fails, record cleanup as unresolved and retain known names and the credential configuration needed to retry later. The source documents no cancellation API, and none is assumed here.
Task and deliverable
This tutorial follows one audio file through the Gemini Files API: upload, a description request, a metadata check, a list check and deletion. It relies only on the official Files API page and its Python excerpts. No product or API was run while writing it.
Prepare the input and environment
- A Gemini API account and credentials. The REST excerpt on the source page sends a key from the variable
GEMINI_API_KEYin thex-goog-api-keyheader, while the Python excerpt callsgenai.Client()with no arguments and does not say where credentials come from. Confirm that setup in the official documentation before running anything. - A Python environment where
from google import genaiworks. The source page gives no install command or supported versions, so check them yourself. - A local audio file you are allowed to upload. The excerpts use the placeholder
path/to/sample.mp3; replace it with a real path. The per-file maximum is 2 GB, and the storage limit is 20 GB per project. - Network access to the API and permission to delete the files you upload.
Mechanism and data flow
Two identifiers, two jobs: After files.upload returns, the object in myfile carries several fields that the excerpts use. myfile.uri and myfile.mime_type go into the audio part of the interactions.create input, next to a text part with the prompt. myfile.name is what the excerpts pass to files.get and files.delete. The page uses the URI for the model request and the name for metadata and deletion, so save both. The page also notes that URIs returned by files.upload and files.get work interchangeably across v1 and v1beta requests.
Storage rules reported by the page: Files are stored for 48 hours and are deleted automatically after that. The Files API holds up to 20 GB per project, with a 2 GB maximum per file. During the storage window you can get metadata, but you cannot download user-uploaded files; files.download is documented for files generated by models, such as videos. It also says the API is available at no cost in all regions where the Gemini API is available, so check current terms yourself. For request size, the page says to always use the Files API when the total, counting files, text prompt and system instructions, is larger than 100 MB, and the limit for PDF files is 50 MB.
Four excerpts, not one program: The page presents the four Python excerpts as independent examples. The describe, get and delete excerpts each call files.upload. Running all four successfully in order performs three uploads, and the delete excerpt immediately deletes the third uploaded file. The first two remain stored until separately deleted or automatically expired. The list excerpt only prints f.name for stored files. The get excerpt calls files.get once and prints the result; it has no loop and does not wait for any state. The workflow below is an editorial combination that uploads once and reuses the same name and uri. The page does not present it as a single sample.
Editorial controls: The page does not describe success checks, cancellation or credential handling for this task. This tutorial's checks, stop rules and credential cleanup are editorial recommendations. Delete only files positively identified as belonging to this task. If identity is uncertain, or listing, deletion or verification fails, record cleanup as unresolved and retain known names and the credential configuration needed to retry later. The source documents no cancellation API, and none is assumed here.
Workflow map
| Stage | What happens |
|---|---|
| Two identifiers, two jobs | After files.upload returns, the object in myfile carries several fields that the excerpts use. |
| Storage rules reported by the page | Files are stored for 48 hours and are deleted automatically after that. |
| Four excerpts, not one program | The page shows the four Python excerpts as separate examples. |
| Editorial controls | The page does not describe success checks, cancellation or credential handling for this task. |
Complete the task
Prepare the environment and input: Confirm the prerequisites before calling anything. Check that the local file exists, is an audio file you may upload, and is under the 2 GB per-file maximum; confirm the project has room under the 20 GB limit. As an editorial precaution, note which credential you will use so you can remove it at the end. Nothing is uploaded yet, so a failure here needs no cleanup beyond that credential.
Upload once and keep the handles: Create the client with genai.Client() and call files.upload once with your local path. From the returned object keep name, uri and mime_type in variables or notes; the excerpts read them as myfile.name, myfile.uri and myfile.mime_type. If the call raises an error, this attempt may not have returned a name you can save. The source does not establish whether a remote file was created or what the error looks like. As an editorial recommendation, stop, record the error and check the list; if you cannot establish the file's identity, record cleanup as unresolved.
Ask the model to describe the audio: Call interactions.create with model set to gemini-4-hydrogen and an input list of two parts: a text part reading Describe this audio clip, and an audio part holding the saved uri and mime_type. The page prints interaction.output_text. Use the saved values rather than uploading again, so the request refers to the same stored file you will later inspect and delete. The page shows no sample output for this audio request, so what the description contains is not documented here.
Get metadata by name: Call files.get with the saved name and print the result, as the get excerpt does. The page says this verifies that the API stored the uploaded file and returns its metadata. It is a single call, not a polling routine, and the page does not say that it waits for processing. Compare the returned name with the one you saved. Metadata is available only during the 48-hour storage period.
Check the output: Judge the description against the rules below, which are editorial recommendations. Success: the request returned without error, output_text has non-empty text, and a person who listens to the clip finds the description reasonable. Failure: an error is raised, or the text contradicts the audio; stop and go to cleanup. Empty output: treat empty or missing text as not complete even without an error; the page does not say when this happens. Checking that names and variables match is a static check, and checking the description against the audio is a semantic check. You need both, since the code cannot prove the description is right.
List files and check leftovers: Run the list excerpt, which loops over client.files.list() and prints each f.name. Compare the results with the saved name and handle only files positively identified as belonging to this task. Earlier failed or interrupted attempts may have left files; the page does not describe how to establish their identity from other information. As an editorial recommendation, do not delete unidentified list entries, and retain a cleanup task when identity remains uncertain. If listing fails, record the error and retain known names, project information and the credential configuration needed to retry later.
Delete the file and verify cleanup: As an editorial recommendation, clean up files positively identified as belonging to this task after success, an error, empty output or an early stop. Call files.delete with the saved, verified name. Do not rerun the delete excerpt to clean up an earlier file: that excerpt uploads and deletes a new file. The source documents no cancellation call, so an early stop means ending your script or session yourself. Without a saved name, you may check the list, but delete only a specific name positively identified as belonging to this task. List files again after deletion and confirm that name no longer appears; files also expire automatically after 48 hours. If identity cannot be established, or listing, deletion or verification fails, record cleanup as unresolved, retain known names and the credential configuration needed to retry, then retry and verify later. Once cleanup is verified, remove the temporary API key configured for this task under your own security practice. Do not clear credentials still needed for cleanup. These are editorial recommendations, not API behavior documented by the source.
Worked example
A reader has a local file at the placeholder path path/to/sample.mp3. They upload it once and record name, uri and mime_type. They send Describe this audio clip together with the audio part to gemini-4-hydrogen, print output_text, call files.get with the name, list names to confirm the file exists, and delete it by name. The page supplies the individual excerpts but no recorded output, and this batch ran none of them, so no description text or metadata values are reported here. The combined sequence is an editorial arrangement of the documented calls.
from google import genai
client = genai.Client()
myfile = client.files.upload(file="path/to/sample.mp3")
interaction = client.interactions.create(
model="gemini-4-hydrogen",
input=[
{"type": "text", "text": "Describe this audio clip"},
{"type": "audio", "uri": myfile.uri, "mime_type": myfile.mime_type}
]
)
print(interaction.output_text)
from google import genai
client = genai.Client()
myfile = client.files.upload(file='path/to/sample.mp3')
file_name = myfile.name
myfile = client.files.get(name=file_name)
print(myfile)
from google import genai
client = genai.Client()
print('My files:')
for f in client.files.list():
print(' ', f.name)
from google import genai
client = genai.Client()
myfile = client.files.upload(file='path/to/sample.mp3')
client.files.delete(name=myfile.name)
Check the result and failure paths
- Success (editorial): the model call returned without error,
output_textis non-empty and matches the audio,files.getreturned metadata for the savedname, and the positively identified task file no longer appears in the list after deletion. - Failure (editorial): if any call raises an error, the description contradicts the audio, or
files.getfails for the saved name, stop and record the error. Delete only files positively identified as belonging to this task. If identity is uncertain or cleanup calls fail, retain the cleanup task, known names and required credential configuration, then retry later. - Empty output (editorial): if
output_textis empty or absent, do not count it as complete. Check that the audio part used the saveduriandmime_type, then decide whether to retry or end the current attempt. When ending it, follow the identity checks and failure rules above for cleanup. - User stop (editorial): the source documents no cancellation call. Clean up by the saved
name, or a name positively identified as belonging to this task after checking the list, and verify the result. If identity is uncertain or cleanup fails, retain the cleanup task and required credential configuration; clear temporary credentials once verification is complete.
Scope and limits
- Source-reported: 48-hour storage, 20 GB per project, 2 GB per file, the 100 MB total request threshold, 50 MB for PDF files, no download of user-uploaded files,
files.downloadfor model-generated files, and no cost in regions where the Gemini API is available. Editorial: success checks, stop rules and credential cleanup. - The page does not state install steps, credential setup for Python, supported versions, waiting for an ACTIVE state, error formats, or output samples for audio. This tutorial does not supply them.
- The Python excerpts are documentation fragments. The list excerpt creates its own client with
genai.Client()and requires a configured Python SDK, credentials and an accessible project; no preexisting client object is needed. None of the four excerpts proves a description is correct. The page also shows JavaScript, Java, Go, REST and CLI variants, which are outside this tutorial. - The page says the API is free; confirm current terms before relying on that.
This tutorial is based on the official Files API page only. No product or API was run in this batch: no package was installed, no credentials were used, no file was uploaded, and no output was observed. The code excerpts are official documentation examples, not results from this batch.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.