Repository Public
1# Files API23> [!NOTE]4> **Note** : This version of the page covers the new [Interactions API](https://ai.google.dev/gemini-api/docs/interactions/interactions-overview), which is currently in Beta. 5> For stable production deployments, we recommend you continue to use the `generateContent` API. You can use the toggle on this page to switch between the versions.67Gemini can handle various types of input data, including text, images, and8audio, at the same time.910This guide shows you how to work with media files using the Files API. The11basic operations are the same for audio files, images, videos, documents, and12other supported file types.1314For file prompting guidance, check out the [File prompt guide](https://ai.google.dev/gemini-api/docs/interactions/files#prompt-guide) section.1516## Upload a file1718You can use the Files API to upload a media file. Always use the Files API when19the total request size (including the files, text prompt, system instructions,20etc.) is larger than 100 MB. For PDF files, the limit is 50 MB.2122The following code uploads a file and then uses the file in a call to23`interactions.create`.2425### Python2627 from google import genai2829 client = genai.Client()3031 myfile = client.files.upload(file="path/to/sample.mp3")3233 interaction = client.interactions.create(34 model="gemini-3.5-flash",35 input=[36 {"type": "text", "text": "Describe this audio clip"},37 {"type": "audio", "uri": myfile.uri, "mime_type": myfile.mime_type}38 ]39 )4041 print(interaction.output_text)4243### JavaScript4445 import { GoogleGenAI } from "@google/genai";4647 const client = new GoogleGenAI({});4849 async function main() {50 const myfile = await client.files.upload({51 file: "path/to/sample.mp3",52 config: { mime_type: "audio/mpeg" },53 });5455 const interaction = await client.interactions.create({56 model: "gemini-3.5-flash",57 input: [58 { type: "text", text: "Describe this audio clip" },59 { type: "audio", uri: myfile.uri, mime_type: myfile.mimeType }60 ]61 });62 console.log(interaction.output_text);63 }6465 await main();6667### Go6869 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)70 if err != nil {71 log.Fatal(err)72 }73 defer client.Files.Delete(ctx, file.Name)7475 interaction, err := client.Interactions.Create(ctx, "gemini-3.5-flash", &genai.InteractionRequest{76 Input: []interface{}{77 genai.NewPartFromFile(*file),78 genai.NewPartFromText("Describe this audio clip"),79 },80 }, nil)8182 if err != nil {83 log.Fatal(err)84 }8586 // Print the model's text response87 for _, step := range interaction.Steps {88 if step.Type == "model_output" {89 for _, part := range step.Content {90 if part.Type == "text" {91 fmt.Println(part.Text)92 }93 }94 }95 }9697### REST9899 AUDIO_PATH="path/to/sample.mp3"100 MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")101 NUM_BYTES=$(wc -c < "${AUDIO_PATH}")102 DISPLAY_NAME=AUDIO103104 tmp_header_file=upload-header.tmp105106 # Initial resumable request defining metadata.107 # The upload url is in the response headers dump them to a file.108 curl "${BASE_URL}/upload/v1beta/files" \109 -H "x-goog-api-key: $GEMINI_API_KEY" \110 -D "${tmp_header_file}" \111 -H "X-Goog-Upload-Protocol: resumable" \112 -H "X-Goog-Upload-Command: start" \113 -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \114 -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \115 -H "Content-Type: application/json" \116 -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null117118 upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")119 rm "${tmp_header_file}"120121 # Upload the actual bytes.122 curl "${upload_url}" \123 -H "Content-Length: ${NUM_BYTES}" \124 -H "X-Goog-Upload-Offset: 0" \125 -H "X-Goog-Upload-Command: upload, finalize" \126 --data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json127128 file_uri=$(jq ".file.uri" file_info.json)129 echo file_uri=$file_uri130131 # Now create an interaction using the Interactions API132 curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \133 -H "x-goog-api-key: $GEMINI_API_KEY" \134 -H 'Content-Type: application/json' \135 -H "Api-Revision: 2026-05-20" \136 -d '{137 "model": "gemini-3.5-flash",138 "input": [139 {"type": "text", "text": "Describe this audio clip"},140 {"type": "audio", "uri": '$file_uri', "mime_type": "'${MIME_TYPE}'"}141 ]142 }' 2> /dev/null > response.json143144 cat response.json145 echo146147 jq ".outputs[] | select(.type == \"text\") | .text" response.json148149## Get metadata for a file150151You can verify that the API successfully stored the uploaded file and get its152metadata by calling `files.get`.153154### Python155156 from google import genai157158 client = genai.Client()159160 myfile = client.files.upload(file='path/to/sample.mp3')161 file_name = myfile.name162 myfile = client.files.get(name=file_name)163 print(myfile)164165### JavaScript166167 import {168 GoogleGenAI,169 } from "@google/genai";170171 const client = new GoogleGenAI({});172173 async function main() {174 const myfile = await client.files.upload({175 file: "path/to/sample.mp3",176 config: { mime_type: "audio/mpeg" },177 });178179 const fileName = myfile.name;180 const fetchedFile = await client.files.get({ name: fileName });181 console.log(fetchedFile);182 }183184 await main();185186### Go187188 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)189 if err != nil {190 log.Fatal(err)191 }192193 gotFile, err := client.Files.Get(ctx, file.Name)194 if err != nil {195 log.Fatal(err)196 }197 fmt.Println("Got file:", gotFile.Name)198199### REST200201 # file_info.json was created in the upload example202 name=$(jq -r ".file.name" file_info.json)203 # Get the file of interest to check state204 curl https://generativelanguage.googleapis.com/v1beta/$name \205 -H "x-goog-api-key: $GEMINI_API_KEY" > file_info.json206 # Print some information about the file you got207 name=$(jq -r ".name" file_info.json)208 echo name=$name209 file_uri=$(jq -r ".uri" file_info.json)210 echo file_uri=$file_uri211212## List uploaded files213214The following code gets a list of all the files uploaded:215216### Python217218 from google import genai219220 client = genai.Client()221222 print('My files:')223 for f in client.files.list():224 print(' ', f.name)225226### JavaScript227228 import {229 GoogleGenAI,230 } from "@google/genai";231232 const client = new GoogleGenAI({});233234 async function main() {235 const listResponse = await client.files.list({ config: { pageSize: 10 } });236 for await (const file of listResponse) {237 console.log(file.name);238 }239 }240241 await main();242243### Go244245 for file, err := range client.Files.All(ctx) {246 if err != nil {247 log.Fatal(err)248 }249 fmt.Println(file.Name)250 }251252### REST253254 echo "My files: "255256 curl "https://generativelanguage.googleapis.com/v1beta/files" \257 -H "x-goog-api-key: $GEMINI_API_KEY"258259## Delete uploaded files260261Files are automatically deleted after 48 hours. You can also manually delete an262uploaded file:263264### Python265266 from google import genai267268 client = genai.Client()269270 myfile = client.files.upload(file='path/to/sample.mp3')271 client.files.delete(name=myfile.name)272273### JavaScript274275 import {276 GoogleGenAI,277 } from "@google/genai";278279 const client = new GoogleGenAI({});280281 async function main() {282 const myfile = await client.files.upload({283 file: "path/to/sample.mp3",284 config: { mime_type: "audio/mpeg" },285 });286287 const fileName = myfile.name;288 await client.files.delete({ name: fileName });289 }290291 await main();292293### Go294295 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)296 if err != nil {297 log.Fatal(err)298 }299 client.Files.Delete(ctx, file.Name)300301### REST302303 curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/$name \304 -H "x-goog-api-key: $GEMINI_API_KEY"305306## Usage info307308You can use the Files API to upload and interact with media files. The Files API309lets you store up to 20 GB of files per project, with a per-file maximum310size of 2 GB. Files are stored for 48 hours. During that time, you can311use the API to get metadata about the files, but you can't download the files.312The Files API is available at no cost in all regions where the Gemini API is313available.314315## File prompting strategies316317This section provides guidance and best practices for using media files with318prompts for the Gemini API.319320Being able to use various types of data in your prompts gives you more321flexibility in terms of what tasks you can tackle with the Gemini API. For322example, you can send the model a photo of a delicious meal and ask it to write323a short blog about the meal.324325|---|---|326| **Prompt** | **Response** |327| Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping. <br />  | Meal prepping is a great way to save time and money, and it can also help you to eat healthier. This meal is a great example of a healthy and delicious meal that can be prepped ahead of time. This meal features brown rice, roasted vegetables, and chicken teriyaki. The brown rice is a healthy and complex carbohydrate that will give you sustained energy. The roasted vegetables are a great way to get your daily dose of vitamins and minerals, and the chicken teriyaki is a delicious and protein-rich option. This meal is also straightforward to prepare. Simply cook the brown rice, roast the vegetables, and cook the chicken teriyaki. Once everything is cooked, divide it into meal prep containers and store them in the refrigerator. You can then grab a container and go on busy mornings! If you're looking for a healthy and delicious meal that can be prepped ahead of time, this meal is a great option. It's packed with nutrients and flavor, and it's sure to keep you feeling full and satisfied. Here's to healthy and delicious meal prepping! |328329If you are having trouble getting the output you want from prompts that use330media files, there are some strategies that can help you get the results you331want. The following sections provide design approaches and troubleshooting332tips for improving prompts that use multimodal input.333334You can improve your multimodal prompts by following these best practices:335336-337338 ### [Prompt design fundamentals](https://ai.google.dev/gemini-api/docs/interactions/files#specific-instructions)339340 - **Be specific in your instructions**: Craft clear and concise instructions that leave minimal room for misinterpretation.341 - **Add a few examples to your prompt:** Use realistic few-shot examples to illustrate what you want to achieve.342 - **Break it down step-by-step**: Divide complex tasks into manageable sub-goals, guiding the model through the process.343 - **Specify the output format**: In your prompt, ask for the output to be in the format you want, like Markdown, JSON, HTML and more.344 - **Put your image first for single-image prompts**: While Gemini can handle image and text inputs in any order, for prompts containing a single image, it might perform better if that image (or video) is placed before the text prompt. However, for prompts that require images to be highly interleaved with texts to make sense, use whatever order is most natural.345-346347 ### [Troubleshooting your multimodal prompt](https://ai.google.dev/gemini-api/docs/interactions/files#troubleshooting)348349 - **If the model is not drawing information from the relevant part of the image:** Drop hints with which aspects of the image you want the prompt to draw information from.350 - **If the model output is too generic (not tailored enough to the image/video input):**At the start of the prompt, try asking the model to describe the image(s) or video before providing the task instruction, or try asking the model to refer to what's in the image.351 - **To troubleshoot which part failed:** Ask the model to describe the image, or ask the model to explain its reasoning, to gauge the model's initial understanding.352 - **If your prompt results in hallucinated content:** Try dialing down the temperature setting or asking the model for shorter descriptions so that it's less likely to extrapolate additional details.353 - **Tuning the sampling parameters:** Experiment with different temperature settings and top-k selections to adjust the model's creativity.354355 > [!NOTE]356 > When using Gemini 3 models, we strongly recommend keeping the `temperature` at its default value of 1.0. Changing the temperature (setting it to a value less than 1.0) may lead to unexpected behavior, such as looping or degraded performance, particularly in complex mathematical or reasoning tasks.357358### Be specific in your instructions359360Prompts have the most success when they are clear and detailed. If you have a361specific output in mind, it's better to include that requirement in the prompt362to ensure you get the output you want.363364For this image of an airport board, asking the model to just "describe this365image" could generate a general description. If you need the model to parse the366time and city from the image, you can include that request directly in your367prompt.368369| Prompt | Model response |370|---|---|371|  Describe this image. | The image shows an airport arrivals and departures board. |372373<br />374375| **Updated prompt** | **Improved response** |376|---|---|377|  Parse the time and city from the airport board shown in this image into a list. | <br /> - 10:50 Moscow - 11:05 Edinburgh - 11:05 London - 11:10 Bucharest - 11:30 Kiev - 11:35 Dublin - 11:45 East Midlands - 12:15 Sofia - 12:30 London - 12:30 Newcastle - 12:40 St Petersburg - 12:40 London - 12:45 Manchester |378379<br />380381### Add a few examples382383The Gemini model can accept multiple inputs which it can use as examples to384understand the output you want. Adding these examples can help the model385identify the patterns and apply the relationship between the given images and386responses to the new example. This is also called "few-shot" learning.387388In the following example, the initial output is written in sentence form,389and also contains the country (Brazil). Suppose you want the output in a390different format or style, and you want only the city, not the country. Adding391few-shot examples to your prompt can steer the model to respond in the way you392want.393394<br />395396| **Prompt** | **Model response** |397|---|---|398|  Determine the city along with the landmark. | The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil. |399400<br />401402| **Updated prompt** | **Improved response** |403|---|---|404| Determine the city along with the landmark.  | city: Rome, landmark: the Colosseum. |405|  | city: Beijing, landmark: Forbidden City |406|  | city: Rio de Janeiro, landmark: Christ the Redeemer statue |407408### Break it down step-by-step409410For complex tasks like the ones that require both visual understanding and411reasoning, it can be helpful to split the task into smaller, more412straightforward steps. Alternatively, it could also be effective if you413directly ask the model to "think step by step" in your prompt.414415| Prompt | Model response |416|---|---|417|  When will I run out of toilet paper? | Soon, you only have 3 rolls left. |418419| **Updated prompt** | **Improved response** |420|---|---|421|  1. First, count how many toilet paper rolls are in this picture. 2. Then, determine how much toilet paper a typical person uses per day. 3. Calculate how long these rolls of toilet paper will last. | 1. There are 3 rolls of toilet paper in this picture. 2. A typical person uses about 20 sheets of toilet paper per day. 3. If each roll contains 200 sheets, then each roll will last for about 10 days. Therefore, the 3 rolls will last for about a month. |422423Math problems or other types of word problems are great candidates for asking424the model to think step-by-step.425426| **Prompt** | **Response** |427|---|---|428|  What is the 4th term in the sequence? | -135 |429430The response from the model is incorrect. Some ways to improve this is to ask431the model to parse the problem before answering the prompt.432433| **Prompt** | **Response** |434|---|---|435|  Parse the formula in the image first. Then based on the formula, answer "what's the 4th term in the sequence?". | *Click to expand the result* $$ b(n) = b(n-1) \* (-3) $$ $$ b(1) = 15 $$ 1. Substitute n = 4 into the formula: $$ b(4) = b(4-1) \* (-3) $$ $$ b(4) = b(3) \* (-3) $$ 2. We don't know the value of b(3), so substitute n = 3 into the formula: $$ b(3) = b(3-1) \* (-3) $$ $$ b(3) = b(2) \* (-3) $$ 3. We don't know the value of b(2), so substitute n = 2 into the formula: $$ b(2) = b(2-1) \* (-3) $$ $$ b(2) = b(1) \* (-3) $$ 4. We know the value of b(1) is 15, so substitute it into the formula: $$ b(2) = 15 \* (-3) $$ $$ b(2) = -45 $$ 5. Now that we know the value of b(2), substitute it into the formula for b(3): $$ b(3) = b(2) \* (-3) $$ $$ b(3) = -45 \* (-3) $$ $$ b(3) = 135 $$ 6. Now that we know the value of b(3), substitute it into the formula for b(4): $$ b(4) = b(3) \* (-3) $$ $$ b(4) = 135 \* (-3) $$ $$ b(4) = -405 $$ Therefore, the 4th term in the sequence is -405. |436437This model response is correct - now to make the response even more streamlined,438you can ask the model to to think step-by-step.439440<br />441442| **Updated prompt** | **Improved response** |443|---|---|444|  What is the 4th term in the sequence? Think step by step. | The first term is 15. The second term is b(1) \* (-3) = 15 \* (-3) = -45. The third term is b(2) \* (-3) = -45 \* (-3) = 135. The fourth term is b(3) \* (-3) = 135 \* (-3) = -405. |445446<br />447448### Specify the output format449450A common problem is the need for model output to be in a certain format451(e.g. Markdown, JSON, HTML), especially if the model output needs to452be ingested by a downstream task. You can try to produce output in that format453by instructing the model to do so within the prompt. The following are two454examples:455456| Prompt | Model response |457|---|---|458|  Parse the table in this image into Markdown format | \`\`\`none \| Subject \| Status \| Time \| Start date \| Due on \| \| --- \| --- \| --- \| --- \| --- \| \| Math \| Done \| 1.5 hrs \| 11/29/2023 \| 12/1/2023 \| \| Geography \| Done \| 30 min \| 12/2/2023 \| 12/4/2023 \| \| Physics \| In progress \| 2 hrs \| 12/3/2023 \| 12/5/2023 \| \| Biology \| Not started \| 6 hrs \| 11/2/2016 \| 12/6/2023 \| \`\`\` |459460| **Prompt** | **Model response** |461|---|---|462|  Provide a list of all the following attributes: ingredients, type of cuisine, vegetarian or not, in JSON format | \`\`\`json { "ingredients": \[ "rice", "shrimp", "clams", "mussels", "peas", "tomatoes", "onions", "garlic", "olive oil", "paprika", "salt", "pepper" \], "type of cuisine": "Spanish", "vegetarian": false } \`\`\` |463464### Put your image first for single-image prompts465466While Gemini can interpret image and text in any order within a prompt, placing467a single image before the text prompt might lead to better results.468In the following samples, you'll notice the image comes first before the text in469each prompt.470471### Troubleshooting your multimodal prompt472473You might need to troubleshoot your prompt if you are not getting a helpful474response. Here are a few strategies you could try.475476#### If the model is not drawing information from the relevant part of the image477478To get a more specific response, you can point out which aspects of the image479you want the prompt to draw information from to inform its response.480481| Prompt | Model response |482|---|---|483|  How many days will these diapers last a baby? | The diapers will last for 198 days before they run out. |484485| **Updated prompt** | **Improved response** |486|---|---|487|  How long will these diapers last before I run out? Use the weight shown on the box to determine the child's age, and use the total number of diapers in the box. Divide the total number by how many diapers the child goes through per day. | The box contains 198 diapers. The box states the diapers are for a child weighing 22-37 lbs. The average child in this weight range is likely between 1 and 2 years old. A 2-year-old typically goes through 6 diapers per day, therefore, the diapers will last around 33 days (198/6). |488489#### If the model output is too generic and not tailored enough to the image input490491To help the model tailor its response to the image(s), try asking it to describe492the images before performing its reasoning task.493494| Prompt | Model response |495|---|---|496|     What is in common between these images? | All four images are examples of landscape photography. |497498| **Updated prompt** | **Improved response** |499|---|---|500|     First, describe what's in each image in detail. What's in common between these images? | The first image shows a person packing a suitcase. The second image shows an empty hallway in a shopping mall. The third image shows a roll of toilet paper. The fourth image shows a dark and stormy sea. The commonality between these images is that they are all examples of liminal spaces. Liminal spaces are places or situations that are in between two other places or situations. They are often characterized by a sense of uncertainty or ambiguity. The first image shows the person in between being at home and being on a trip. The second image shows the hallway in between two stores. The third image is of toilet paper, which can represent a bathroom. A bathroom is a transitional space between private and public realms. It's a place where we prepare ourselves to enter or leave the outside world. The fourth image shows the sea in between being calm and being stormy. Liminal spaces can be both exciting and unsettling. They can be a place of new beginning or a place of endings. They can be a place of reflection or a place of action. |501502You can also try explicitly asking the model to refer to what's in the image.503504| **Updated prompt** | **Improved response** |505|---|---|506|     What is in common between these images? Refer to what's in the images in your response. | All of the images are related to travel. The first image shows a person packing a suitcase, the second image shows an empty hallway in a shopping mall, the third image shows a stack of toilet paper, and the fourth image shows a dark and stormy sea. These images are all related to travel because they are all things that people need or use when they travel. The first image shows a person packing a suitcase, which is something that people do when they are going on a trip. The second image shows an empty hallway in a shopping mall, which is a place where people often go to buy things for their trips. The third image shows a stack of toilet paper, which is something that people often use when they are traveling. The fourth image shows a dark and stormy sea, which is something that people often encounter when they are traveling. |507508The same tips work for creative output from images. In the following example with509the rabbit, explicitly asking the model to include aspects from the image can510improve the output.511512| Prompt | Model response |513|---|---|514|  Can you write me a poem about this image? | Little bunny, so soft and brown, Hopping through the field, up and down. Your ears so long, your tail so small, You're the cutest creature of them all. You nibble on the grass, so green and sweet, And hop away when you see me. But I'll always be your friend, Little bunny, until the very end. |515516<br />517518| **Updated prompt** | **Improved response** |519|---|---|520|  Can you write me a descriptive and dramatic poem about this image and include the location? | Little bunny on the green, Ears so long, so keen. What do you see out there, In the distance, where you stare? Is it the ocean blue, Sparkling in the sun's hue? Or the waves that crash and roar, A rhythm that you adore? Little bunny, tell me true, What captures your attention so? Is it the salty breeze, Or the seagulls' cries that please? Perhaps it's the vastness of it all, A world so big and small. A place where dreams can roam, And adventures can be sown. Little bunny, I wonder what you dream, As you sit on the grass, so serene. Do you yearn to explore the deep, Or stay on land, where you can leap? Whatever it may be, little bunny, Keep that spark of wonder burning brightly. For in your dreams and aspirations, Lies a world waiting for your creation. |521522<br />523524#### Troubleshooting which part of the prompt failed525526It can be hard to know whether a prompt failed because the model527didn't **understand the image** to begin with, or if it did understand the image528but did not perform the correct **reasoning steps** afterward.529To disambiguate between those reasons, ask the model to describe what's in the image.530531In the following example, if the model responds with a snack that seems surprising532when paired with tea (e.g. popcorn), you can first troubleshoot to determine533whether the model correctly recognized that the image contains tea.534535| Prompt | Prompt for troubleshooting |536|---|---|537|  What's a snack I can make in 1 minute that would go well with this? |  Describe what's in this image. |538539Another strategy is to ask the model to explain its reasoning. That can help you540narrow down which part of the reasoning broke down, if any.541542| Prompt | Prompt for troubleshooting |543|---|---|544|  What's a snack I can make in 1 minute that would go well with this? |  What's a snack I can make in 1 minute that would go well with this? Please explain why. |545546## What's next547548- Try writing your own multimodal prompts using [Google AI549 Studio](http://aistudio.google.com).550- For information on using the Gemini Files API for uploading media files and including them in your prompts, see the [Vision](https://ai.google.dev/gemini-api/docs/interactions/vision), [Audio](https://ai.google.dev/gemini-api/docs/interactions/audio), and [Document processing](https://ai.google.dev/gemini-api/docs/interactions/document-processing) guides.551- For more guidance on prompt design, like tuning sampling parameters, see the [Prompt strategies](https://ai.google.dev/gemini-api/docs/prompting-strategies) page.