Repository Public
1Gemini can handle various types of input data, including text, images, and2audio, at the same time.34This guide shows you how to work with media files using the Files API. The5basic operations are the same for audio files, images, videos, documents, and6other supported file types.78For file prompting guidance, check out the [File prompt guide](https://ai.google.dev/gemini-api/docs/files#prompt-guide) section.910## Upload a file1112You can use the Files API to upload a media file. Always use the Files API when13the total request size (including the files, text prompt, system instructions,14etc.) is larger than 100 MB. For PDF files, the limit is 50 MB.1516The following code uploads a file and then uses the file in a call to17`generateContent`.1819### Python2021 from google import genai2223 client = genai.Client()2425 myfile = client.files.upload(file="path/to/sample.mp3")2627 response = client.models.generate_content(28 model="gemini-3.8-flash", contents=["Describe this audio clip", myfile]29 )3031 print(response.text)3233### JavaScript3435 import {36 GoogleGenAI,37 createUserContent,38 createPartFromUri,39 } from "@google/genai";4041 const ai = new GoogleGenAI({});4243 async function main() {44 const myfile = await ai.files.upload({45 file: "path/to/sample.mp3",46 config: { mimeType: "audio/mpeg" },47 });4849 const response = await ai.models.generateContent({50 model: "gemini-3.8-flash",51 contents: createUserContent([52 createPartFromUri(myfile.uri, myfile.mimeType),53 "Describe this audio clip",54 ]),55 });56 console.log(response.text);57 }5859 await main();6061### Go6263 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)64 if err != nil {65 log.Fatal(err)66 }67 defer client.Files.Delete(ctx, file.Name)6869 resp, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", []*genai.Content{70 {71 Parts: []*genai.Part{72 genai.NewPartFromFile(*file),73 genai.NewPartFromText("Describe this audio clip"),74 },75 },76 }, nil)7778 if err != nil {79 log.Fatal(err)80 }8182 printResponse(resp)8384### REST8586 AUDIO_PATH="path/to/sample.mp3"87 MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")88 NUM_BYTES=$(wc -c < "${AUDIO_PATH}")89 DISPLAY_NAME=AUDIO9091 tmp_header_file=upload-header.tmp9293 # Initial resumable request defining metadata.94 # The upload url is in the response headers dump them to a file.95 curl "${BASE_URL}/upload/v1beta/files" \96 -H "x-goog-api-key: $GEMINI_API_KEY" \97 -D "${tmp_header_file}" \98 -H "X-Goog-Upload-Protocol: resumable" \99 -H "X-Goog-Upload-Command: start" \100 -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \101 -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \102 -H "Content-Type: application/json" \103 -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null104105 upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")106 rm "${tmp_header_file}"107108 # Upload the actual bytes.109 curl "${upload_url}" \110 -H "Content-Length: ${NUM_BYTES}" \111 -H "X-Goog-Upload-Offset: 0" \112 -H "X-Goog-Upload-Command: upload, finalize" \113 --data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json114115 file_uri=$(jq ".file.uri" file_info.json)116 echo file_uri=$file_uri117118 # Now generate content using that file119 curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \120 -H "x-goog-api-key: $GEMINI_API_KEY" \121 -H 'Content-Type: application/json' \122 -X POST \123 -d '{124 "contents": [{125 "parts":[126 {"text": "Describe this audio clip"},127 {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]128 }]129 }' 2> /dev/null > response.json130131 cat response.json132 echo133134 jq ".candidates[].content.parts[].text" response.json135136## Get metadata for a file137138You can verify that the API successfully stored the uploaded file and get its139metadata by calling `files.get`.140141### Python142143 from google import genai144145 client = genai.Client()146147 myfile = client.files.upload(file='path/to/sample.mp3')148 file_name = myfile.name149 myfile = client.files.get(name=file_name)150 print(myfile)151152### JavaScript153154 import {155 GoogleGenAI,156 } from "@google/genai";157158 const ai = new GoogleGenAI({});159160 async function main() {161 const myfile = await ai.files.upload({162 file: "path/to/sample.mp3",163 config: { mimeType: "audio/mpeg" },164 });165166 const fileName = myfile.name;167 const fetchedFile = await ai.files.get({ name: fileName });168 console.log(fetchedFile);169 }170171 await main();172173### Go174175 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)176 if err != nil {177 log.Fatal(err)178 }179180 gotFile, err := client.Files.Get(ctx, file.Name)181 if err != nil {182 log.Fatal(err)183 }184 fmt.Println("Got file:", gotFile.Name)185186### REST187188 # file_info.json was created in the upload example189 name=$(jq ".file.name" file_info.json)190 # Get the file of interest to check state191 curl https://generativelanguage.googleapis.com/v1beta/files/$name \192 -H "x-goog-api-key: $GEMINI_API_KEY" > file_info.json193 # Print some information about the file you got194 name=$(jq ".file.name" file_info.json)195 echo name=$name196 file_uri=$(jq ".file.uri" file_info.json)197 echo file_uri=$file_uri198199## List uploaded files200201The following code gets a list of all the files uploaded:202203### Python204205 from google import genai206207 client = genai.Client()208209 print('My files:')210 for f in client.files.list():211 print(' ', f.name)212213### JavaScript214215 import {216 GoogleGenAI,217 } from "@google/genai";218219 const ai = new GoogleGenAI({});220221 async function main() {222 const listResponse = await ai.files.list({ config: { pageSize: 10 } });223 for await (const file of listResponse) {224 console.log(file.name);225 }226 }227228 await main();229230### Go231232 for file, err := range client.Files.All(ctx) {233 if err != nil {234 log.Fatal(err)235 }236 fmt.Println(file.Name)237 }238239### REST240241 echo "My files: "242243 curl "https://generativelanguage.googleapis.com/v1beta/files" \244 -H "x-goog-api-key: $GEMINI_API_KEY"245246## Delete uploaded files247248Files are automatically deleted after 48 hours. You can also manually delete an249uploaded file:250251### Python252253 from google import genai254255 client = genai.Client()256257 myfile = client.files.upload(file='path/to/sample.mp3')258 client.files.delete(name=myfile.name)259260### JavaScript261262 import {263 GoogleGenAI,264 } from "@google/genai";265266 const ai = new GoogleGenAI({});267268 async function main() {269 const myfile = await ai.files.upload({270 file: "path/to/sample.mp3",271 config: { mimeType: "audio/mpeg" },272 });273274 const fileName = myfile.name;275 await ai.files.delete({ name: fileName });276 }277278 await main();279280### Go281282 file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)283 if err != nil {284 log.Fatal(err)285 }286 client.Files.Delete(ctx, file.Name)287288### REST289290 curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name \291 -H "x-goog-api-key: $GEMINI_API_KEY"292293## Usage information294295You can use the Files API to upload and interact with media files. The Files API296lets you store up to 20 GB of files per project, with a per-file maximum297size of 2 GB. Files are stored for 48 hours.298299During that time, you can use the API to get metadata about the files. However,300you can't download user-uploaded files. You can download files generated by301models, such as videos, using the `files.download` method. The Files API is302available at no cost in all regions where the Gemini API is available.303304## File prompting strategies305306This section provides guidance and best practices for using media files with307prompts for the Gemini API.308309Being able to use various types of data in your prompts gives you more310flexibility in terms of what tasks you can tackle with the Gemini API. For311example, you can send the model a photo of a delicious meal and ask it to write312a short blog about the meal.313314|---|---|315| **Prompt** | **Response** |316| 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 easily 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 very easy 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 easily 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! |317318If you are having trouble getting the output you want from prompts that use319media files, there are some strategies that can help you get the results you320want. The following sections provide design approaches and troubleshooting321tips for improving prompts that use multimodal input.322323You can improve your multimodal prompts by following these best practices:324325-326327 ### [Prompt design fundamentals](https://ai.google.dev/gemini-api/docs/generate-content/files#specific-instructions)328329 - **Be specific in your instructions**: Craft clear and concise instructions that leave minimal room for misinterpretation.330 - **Add a few examples to your prompt:** Use realistic few-shot examples to illustrate what you want to achieve.331 - **Break it down step-by-step**: Divide complex tasks into manageable sub-goals, guiding the model through the process.332 - **Specify the output format**: In your prompt, ask for the output to be in the format you want, like markdown, JSON, HTML and more.333 - **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.334-335336 ### [Troubleshooting your multimodal prompt](https://ai.google.dev/gemini-api/docs/generate-content/files#troubleshooting)337338 - **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.339 - **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.340 - **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.341 - **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.342 - **Tuning the sampling parameters:** Experiment with different temperature settings and top-k selections to adjust the model's creativity.343344### Be specific in your instructions345346Prompts have the most success when they are clear and detailed. If you have a347specific output in mind, it's better to include that requirement in the prompt348to ensure you get the output you want.349350For this image of an airport board, asking the model to just "describe this351image" could generate a general description. If you need the model to parse the352time and city from the image, you can include that request directly in your prompt.353354| Prompt | Model response |355|---|---|356|  Describe this image. | The image shows an airport arrivals and departures board. |357358<br />359360| **Updated prompt** | **Improved response** |361|---|---|362|  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 |363364<br />365366### Add a few examples367368The Gemini model can accept multiple inputs which it can use as examples to understand the369output you want. Adding these examples can help the model identify the patterns and apply the370relationship between the given images and responses to the new example. This is also called371"few-shot" learning.372373In the example below, the initial output is written in sentence form, and also contains the374country (Brazil). Suppose you want the output in a different format or style, and you want375only the city, not the country. Adding few-shot examples to your prompt can steer the model376to respond in the way you want.377378<br />379380| **Prompt** | **Model response** |381|---|---|382|  Determine the city along with the landmark. | The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil. |383384<br />385386| **Updated prompt** | **Improved response** |387|---|---|388| Determine the city along with the landmark.  | city: Rome, landmark: the Colosseum. |389|  | city: Beijing, landmark: Forbidden City |390|  | city: Rio de Janeiro, landmark: Christ the Redeemer statue |391392### Break it down step-by-step393394For complex tasks like the ones that require both visual understanding and395reasoning, it can be helpful to split the task into smaller, more straightforward396steps. Alternatively, it could also be effective if you397directly ask the model to "think step by step" in your prompt.398399| Prompt | Model response |400|---|---|401|  When will I run out of toilet paper? | Soon, you only have 3 rolls left. |402403| **Updated prompt** | **Improved response** |404|---|---|405|  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. <br /> | 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. <br /> |406407Math problems or other types of word problems are great candidates for asking408the model to think step-by-step.409410| **Prompt** | **Response** |411|---|---|412|  What is the 4th term in the sequence? <br /> | -135 |413414The response from the model is incorrect. Some ways to improve this is to ask415the model to parse the problem before answering the prompt.416417| **Prompt** | **Response** |418|---|---|419|  Parse the formula in the image first. Then based on the formula, answer "what's the 4th term in the sequence?". <br /> | <br /> *Click to expand the result* $$ b(n) = b(n-1) \* (-3) $$ $$ b(1) = 15 $$ 1. Substitute n = 4 into the formula: 2. $$ b(4) = b(4-1) \* (-3) $$ 3. $$ b(4) = b(3) \* (-3) $$ 4. We don't know the value of b(3), so substitute n = 3 into the formula: 5. $$ b(3) = b(3-1) \* (-3) $$ 6. $$ b(3) = b(2) \* (-3) $$ 7. We don't know the value of b(2), so substitute n = 2 into the formula: 8. $$ b(2) = b(2-1) \* (-3) $$ 9. $$ b(2) = b(1) \* (-3) $$ 10. We know the value of b(1) is 15, so substitute it into the formula: 11. $$ b(2) = 15 \* (-3) $$ 12. $$ b(2) = -45 $$ 13. Now that we know the value of b(2), substitute it into the formula for b(3): 14. $$ b(3) = b(2) \* (-3) $$ 15. $$ b(3) = -45 \* (-3) $$ 16. $$ b(3) = 135 $$ 17. Now that we know the value of b(3), substitute it into the formula for b(4): 18. $$ b(4) = b(3) \* (-3) $$ 19. $$ b(4) = 135 \* (-3) $$ 20. $$ b(4) = -405 $$ Therefore, the 4th term in the sequence is -405. <br /> |420421This model response is correct - now to make the response even more streamlined,422you can ask the model to to think step-by-step.423424<br />425426| **Updated prompt** | **Improved response** |427|---|---|428|  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. |429430<br />431432### Specify the output format433434A common problem is the need for model output to be in a certain format435(e.g. markdown, JSON, HTML), especially if the model output needs to436be ingested by a downstream task. You can try to produce output in that format437by instructing the model to do so within the prompt. Below are two examples:438439| Prompt | Model response |440|---|---|441|  Parse the table in this image into markdown format | \| 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 \| |442443| **Prompt** | **Model response** |444|---|---|445|  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 } \`\`\` `` <br /> |446447### Put your image first for single-image prompts448449While Gemini can interpret image and text in any order within a prompt, placing450a single image before the text prompt might lead to better results.451In the following samples, you'll notice the image comes first before the text in452each prompt.453454### Troubleshooting your multimodal prompt455456You might need to troubleshoot your prompt if you are not getting a helpful457response. Here are a few strategies you could try.458459#### If the model is not drawing information from the relevant part of the image460461To get a more specific response, you can point out which aspects of the image462you want the prompt to draw information from to inform its response.463464| Prompt | Model response |465|---|---|466|  How many days will these diapers last a baby? | The diapers will last for 198 days before they run out. |467468| **Updated prompt** | **Improved response** |469|---|---|470|  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). |471472#### If the model output is too generic and not tailored enough to the image input473474To help the model tailor its response to the image(s), try asking it to describe475the images before performing its reasoning task.476477| Prompt | Model response |478|---|---|479|     What is in common between these images? | All four images are examples of landscape photography. |480481| **Updated prompt** | **Improved response** |482|---|---|483|     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. |484485You can also try explicitly asking the model to refer to what's in the image.486487| **Updated prompt** | **Improved response** |488|---|---|489|     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. |490491The same tips work for creative output from images. In the following example with492the rabbit, explicitly asking the model to include aspects from the image can493improve the output.494495| Prompt | Model response |496|---|---|497|  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. |498499<br />500501| **Updated prompt** | **Improved response** |502|---|---|503|  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. |504505<br />506507#### Troubleshooting which part of the prompt failed508509It can be hard to know whether a prompt failed because the model510didn't **understand the image** to begin with, or if it did understand the image511but did not perform the correct **reasoning steps** afterward.512To disambiguate between those reasons, ask the model to describe what's in the image.513514In the following example, if the model responds with a snack that seems surprising515when paired with tea (e.g. popcorn), you can first troubleshoot to determine516whether the model correctly recognized that the image contains tea.517518| Prompt | Prompt for troubleshooting |519|---|---|520|  What's a snack I can make in 1 minute that would go well with this? |  Describe what's in this image. |521522Another strategy is to ask the model to explain its reasoning. That can help you523narrow down which part of the reasoning broke down, if any.524525| Prompt | Prompt for troubleshooting |526|---|---|527|  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. |528529## What's next530531- Try writing your own multimodal prompts using [Google AI532 Studio](http://aistudio.google.com).533- 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/vision), [Audio](https://ai.google.dev/gemini-api/docs/audio), and [Document processing](https://ai.google.dev/gemini-api/docs/document-processing) guides.534- For more guidance on prompt design, like tuning sampling parameters, see the [Prompt strategies](https://ai.google.dev/gemini-api/docs/prompting-strategies) page.