Файловый API

Gemini может одновременно обрабатывать различные типы входных данных, включая текст, изображения и аудио.

В этом руководстве показано, как работать с медиафайлами с помощью Files API. Основные операции одинаковы для аудиофайлов, изображений, видео, документов и других поддерживаемых типов файлов.

Инструкции по настройке параметров файлов см. в разделе « Руководство по настройке параметров файлов» .

Загрузите файл

Для загрузки медиафайлов можно использовать Files API. Всегда используйте Files API, если общий размер запроса (включая файлы, текстовое сообщение, системные инструкции и т. д.) превышает 100 МБ. Для файлов PDF лимит составляет 50 МБ.

Следующий код загружает файл, а затем использует этот файл в вызове функции generateContent .

Python

from google import genai

client = genai.Client()

myfile = client.files.upload(file="path/to/sample.mp3")

response = client.models.generate_content(
    model="gemini-3.8-flash", contents=["Describe this audio clip", myfile]
)

print(response.text)

JavaScript

import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.mp3",
    config: { mimeType: "audio/mpeg" },
  });

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

await main();

Идти

file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
    log.Fatal(err)
}
defer client.Files.Delete(ctx, file.Name)

resp, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", []*genai.Content{
  {
    Parts: []*genai.Part{
      genai.NewPartFromFile(*file),
      genai.NewPartFromText("Describe this audio clip"),
    },
  },
}, nil)

if err != nil {
    log.Fatal(err)
}

printResponse(resp)

ОТДЫХ

AUDIO_PATH="path/to/sample.mp3"
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" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -D "${tmp_header_file}" \
  -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-3.8-flash:generateContent" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this audio clip"},
          {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

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

Получить метаданные для файла

Вы можете убедиться в успешном сохранении загруженного файла через API и получить его метаданные, вызвав метод files.get .

Python

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)

JavaScript

import {
  GoogleGenAI,
} from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.mp3",
    config: { mimeType: "audio/mpeg" },
  });

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

await main();

Идти

file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
    log.Fatal(err)
}

gotFile, err := client.Files.Get(ctx, file.Name)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Got file:", gotFile.Name)

ОТДЫХ

# file_info.json was created in the upload example
name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name \
-H "x-goog-api-key: $GEMINI_API_KEY" > 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

Список загруженных файлов

Следующий код получает список всех загруженных файлов:

Python

from google import genai

client = genai.Client()

print('My files:')
for f in client.files.list():
    print(' ', f.name)

JavaScript

import {
  GoogleGenAI,
} from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const listResponse = await ai.files.list({ config: { pageSize: 10 } });
  for await (const file of listResponse) {
    console.log(file.name);
  }
}

await main();

Идти

for file, err := range client.Files.All(ctx) {
  if err != nil {
    log.Fatal(err)
  }
  fmt.Println(file.Name)
}

ОТДЫХ

echo "My files: "

curl "https://generativelanguage.googleapis.com/v1beta/files" \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Удалить загруженные файлы

Файлы автоматически удаляются через 48 часов. Вы также можете удалить загруженный файл вручную:

Python

from google import genai

client = genai.Client()

myfile = client.files.upload(file='path/to/sample.mp3')
client.files.delete(name=myfile.name)

JavaScript

import {
  GoogleGenAI,
} from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.mp3",
    config: { mimeType: "audio/mpeg" },
  });

  const fileName = myfile.name;
  await ai.files.delete({ name: fileName });
}

await main();

Идти

file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
    log.Fatal(err)
}
client.Files.Delete(ctx, file.Name)

ОТДЫХ

curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name \
  -H "x-goog-api-key: $GEMINI_API_KEY"

Информация об использовании

Вы можете использовать Files API для загрузки медиафайлов и взаимодействия с ними. Files API позволяет хранить до 20 ГБ файлов на проект, при этом максимальный размер каждого файла составляет 2 ГБ. Файлы хранятся в течение 48 часов.

В течение этого времени вы можете использовать API для получения метаданных о файлах. Однако вы не можете загружать файлы, загруженные пользователями. Вы можете загружать файлы, созданные моделями, например, видео, используя метод files.download . API файлов доступен бесплатно во всех регионах, где доступен API Gemini.

стратегии запроса файлов

В этом разделе представлены рекомендации и лучшие практики использования медиафайлов с запросами к API Gemini.

Возможность использовать различные типы данных в ваших запросах дает вам большую гибкость в плане того, какие задачи вы можете решать с помощью API Gemini. Например, вы можете отправить модели фотографию вкусного блюда и попросить ее написать короткий пост в блоге об этом блюде.

Быстрый Ответ

Напишите короткий, увлекательный пост в блоге, основанный на этой фотографии. Он должен включать описание блюда на фото и рассказ о моем опыте приготовления еды заранее.


Печенье

Предварительная подготовка еды — отличный способ сэкономить время и деньги, а также помочь вам питаться здоровее. Это блюдо — прекрасный пример полезного и вкусного блюда, которое легко приготовить заранее.

В состав этого блюда входят бурый рис, запеченные овощи и курица терияки. Бурый рис — это полезный и сложный источник углеводов, который обеспечит вас энергией на длительное время. Запеченные овощи — отличный способ получить ежедневную дозу витаминов и минералов, а курица терияки — вкусный и богатый белком вариант.

Это блюдо очень легко приготовить. Просто сварите коричневый рис, запеките овощи и приготовьте курицу терияки. После того, как все будет готово, разложите по контейнерам для хранения и уберите в холодильник. Тогда вы сможете взять контейнер и отправиться готовить по утрам, когда у вас мало времени!

Если вы ищете полезное и вкусное блюдо, которое легко приготовить заранее, это отличный вариант. Оно богато питательными веществами и обладает насыщенным вкусом, и гарантированно обеспечит вам чувство сытости и удовлетворения.

Желаем вам здорового и вкусного питания при приготовлении еды заранее!

Если у вас возникли проблемы с получением желаемого результата от запросов, использующих медиафайлы, существуют стратегии, которые могут помочь вам добиться желаемого результата. В следующих разделах представлены подходы к проектированию и советы по устранению неполадок для улучшения запросов, использующих мультимодальный ввод.

Вы можете улучшить свои мультимодальные подсказки, следуя этим рекомендациям:

  • Основы оперативного проектирования

    • Будьте конкретны в своих инструкциях : составьте четкие и лаконичные инструкции, которые сведут к минимуму возможность неправильного толкования.
    • Добавьте несколько примеров к своему заданию: используйте реалистичные примеры из нескольких кадров, чтобы проиллюстрировать, чего вы хотите достичь.
    • Разбейте задачу на этапы : разделите сложные задачи на выполнимые подзадачи, направляя модель на протяжении всего процесса.
    • Укажите формат вывода : в командной строке укажите желаемый формат вывода, например, Markdown, JSON, HTML и другие.
    • В подсказках с одним изображением размещайте изображение первым : хотя Gemini может обрабатывать изображения и текст в любом порядке, для подсказок, содержащих одно изображение, может быть эффективнее, если это изображение (или видео) будет размещено перед текстовой подсказкой. Однако для подсказок, требующих частого чередования изображений и текста для обеспечения осмысленности, используйте тот порядок, который вам наиболее естественен.
  • Устранение неполадок с многомодальным приглашением

    • Если модель не получает информацию из соответствующей части изображения: укажите, из каких аспектов изображения вы хотите, чтобы модель получала информацию.
    • Если выходные данные модели слишком общие (недостаточно адаптированы к входному изображению/видео): в начале запроса попробуйте попросить модель описать изображение(я) или видео до предоставления инструкции к заданию, или попробуйте попросить модель сослаться на то, что изображено на картинке.
    • Чтобы определить, какая именно часть не сработала: попросите модель описать изображение или объяснить свои рассуждения, чтобы оценить ее первоначальное понимание.
    • Если ваш запрос приводит к галлюцинациям: попробуйте уменьшить температуру или попросить модель дать более короткие описания, чтобы она с меньшей вероятностью могла додумать дополнительные детали.
    • Настройка параметров выборки: поэкспериментируйте с различными настройками температуры и выбором k лучших результатов, чтобы отрегулировать творческие возможности модели.

Будьте конкретны в своих инструкциях.

Наиболее эффективные запросы достигаются, когда они ясны и подробны. Если у вас есть конкретное требование к результату, лучше указать его в запросе, чтобы гарантировать получение желаемого результата.

В случае с этим изображением табло аэропорта, запрос к модели просто «опишите это изображение» может сгенерировать общее описание. Если вам нужно, чтобы модель определила время и город на изображении, вы можете включить этот запрос непосредственно в ваше сообщение.

Быстрый Ответ модели

Опишите это изображение.

На изображении показано табло прибытия и отправления рейсов в аэропорту.

Обновлено сообщение Улучшенная реакция
Расписание поездок

С помощью программы для обработки времени и названия города, отображаемых на табло аэропорта на этом изображении, сформируйте список.

  • 10:50 Москва
  • 11:05 Эдинбург
  • 11:05 Лондон
  • 11:10 Бухарест
  • 11:30 Киев
  • 11:35 Дублин
  • 11:45 Ист-Мидлендс
  • 12:15 София
  • 12:30 Лондон
  • 12:30 Ньюкасл
  • 12:40 Санкт-Петербург
  • 12:40 Лондон
  • 12:45 Манчестер
  • Приведите несколько примеров.

    Модель Gemini может принимать несколько входных данных, которые она может использовать в качестве примеров для понимания желаемого результата. Добавление этих примеров помогает модели выявлять закономерности и применять взаимосвязь между заданными изображениями и ответами к новому примеру. Это также называется обучением с малым количеством примеров.

    В приведенном ниже примере исходный вывод представлен в виде предложения и содержит название страны (Бразилия). Предположим, вам нужен вывод в другом формате или стиле, и вы хотите получить только название города, а не страны. Добавление нескольких примеров к вашему запросу может направить модель к нужному вам способу ответа.

    Быстрый Ответ модели
    Расписание поездок

    Определите город и достопримечательность.

    Главная достопримечательность — статуя Христа-Искупителя в Рио-де-Жанейро, Бразилия.

    Обновлено сообщение Улучшенная реакция

    Определите город и достопримечательность.

    Колизей

    Город: Рим, достопримечательность: Колизей.

    Запретный город

    Город: Пекин, достопримечательность: Запретный город.

    запретный город

    Город: Рио-де-Жанейро, достопримечательность: статуя Христа-Искупителя.

    Разберите это пошагово.

    Для сложных задач, требующих как визуального восприятия, так и логического мышления, может быть полезно разбить задачу на более мелкие, простые шаги. В качестве альтернативы, может быть эффективно, если вы прямо попросите модель «думать шаг за шагом» в своем задании.

    Быстрый Ответ модели

    Когда у меня закончится туалетная бумага?

    Вскоре у вас останется всего 3 рулона.

    Обновлено сообщение Улучшенная реакция

      1. Сначала посчитайте, сколько рулонов туалетной бумаги изображено на этом рисунке.
      2. Затем определите, сколько туалетной бумаги использует среднестатистический человек в день.
      3. Рассчитайте, на сколько рулонов туалетной бумаги хватит.

      1. На этом изображении 3 рулона туалетной бумаги.
      2. Обычный человек использует около 20 листов туалетной бумаги в день.
      3. Если в каждом рулоне 200 листов, то каждого рулона хватит примерно на 10 дней. Следовательно, 3 рулонов хватит примерно на месяц.

    Математические задачи или другие виды текстовых задач отлично подходят для того, чтобы попросить модель мыслить пошагово.

    Быстрый Ответ

    Какой четвертый член последовательности?

    -135

    Ответ модели неверен. Для улучшения ситуации можно попросить модель проанализировать задачу перед тем, как ответить на вопрос.

    Быстрый Ответ

    Сначала разберите формулу на изображении.

    Затем, опираясь на формулу, ответьте на вопрос: «Какой четвертый член последовательности?».

    Нажмите, чтобы развернуть результат

    $$ b(n) = b(n-1) * (-3) $$

    $$ b(1) = 15 $$

    1. Подставьте n = 4 в формулу:
    2. $$ b(4) = b(4-1) * (-3) $$

      $$ b(4) = b(3) * (-3) $$

    3. Мы не знаем значения b(3), поэтому подставим n = 3 в формулу:
    4. $$ b(3) = b(3-1) * (-3) $$

      $$ b(3) = b(2) * (-3) $$

    5. Мы не знаем значения b(2), поэтому подставим n = 2 в формулу:
    6. $$ b(2) = b(2-1) * (-3) $$

      $$ b(2) = b(1) * (-3) $$

    7. Мы знаем, что значение b(1) равно 15, поэтому подставим его в формулу:
    8. $$ b(2) = 15 * (-3) $$

      $$ b(2) = -45 $$

    9. Теперь, когда мы знаем значение b(2), подставим его в формулу для b(3):
    10. $$ b(3) = b(2) * (-3) $$

      $$ b(3) = -45 * (-3) $$

      $$ b(3) = 135 $$

    11. Теперь, когда мы знаем значение b(3), подставим его в формулу для b(4):
    12. $$ b(4) = b(3) * (-3) $$

      $$ b(4) = 135 * (-3) $$

      $$ b(4) = -405 $$

    Следовательно, четвертый член последовательности равен -405.

    Этот ответ модели верен — теперь, чтобы сделать ответ еще более понятным, вы можете попросить модель думать пошагово.

    Обновлено сообщение Улучшенная реакция

    Какой четвёртый член последовательности? Подумайте пошагово.

    Первый семестр — 15.

    Второй член равен b(1) * (-3) = 15 * (-3) = -45.

    Третий член равен b(2) * (-3) = -45 * (-3) = 135.

    Четвертый член равен b(3) * (-3) = 135 * (-3) = -405.

    Укажите формат вывода

    Распространенная проблема — необходимость получения выходных данных модели в определенном формате (например, Markdown, JSON, HTML), особенно если эти данные должны быть обработаны последующей задачей. Вы можете попытаться получить выходные данные в этом формате, указав модели это в командной строке. Ниже приведены два примера:

    Быстрый Ответ модели

    Преобразуйте таблицу на этом изображении в формат Markdown.

    | Тема | Статус | Время | Дата начала | Дата окончания |

    | ------- | ------ | ---- | ---------- | ------ |

    | Математика | Выполнено | 1,5 часа | 29.11.2023 | 01.12.2023 |

    | География | Готово | 30 мин | 02.12.2023 | 04.12.2023 |

    | Физика | В процессе | 2 часа | 03.12.2023 | 05.12.2023 |

    | Биология | Не начато | 6 часов | 02.11.2016 | 06.12.2023 |

    Быстрый Ответ модели

    Предоставьте список всех следующих атрибутов:

    Ингредиенты, тип кухни, вегетарианская или нет, в формате JSON.

    ```json

    {

    "ингредиенты": [

    "рис",

    "креветка",

    "моллюски",

    "моллюски",

    "горох",

    «помидоры»,

    «лук»,

    "чеснок",

    "оливковое масло",

    «паприка»

    "соль",

    "перец"

    ],

    «Тип кухни»: «испанская».

    "вегетарианец": ложь

    }

    ```

    При выборе одного изображения, разместите ваше изображение первым.

    Хотя Близнецы могут интерпретировать изображение и текст в любом порядке в рамках подсказки, размещение одного изображения перед текстовой подсказкой может привести к лучшим результатам. В следующих примерах вы заметите, что в каждой подсказке изображение стоит перед текстом.

    Устранение неполадок с многомодальным приглашением

    Если вы не получаете полезного ответа, возможно, вам потребуется устранить неполадки в работе командной строки. Вот несколько стратегий, которые вы можете попробовать.

    Если модель не извлекает информацию из соответствующей части изображения

    Чтобы получить более конкретный ответ, вы можете указать, какие аспекты изображения вы хотите, чтобы система использовала для формирования ответа.

    Быстрый Ответ модели

    На сколько дней хватит этих подгузников для ребенка?

    Подгузников хватит на 198 дней.

    Обновлено сообщение Улучшенная реакция

    На сколько мне хватит этих подгузников, прежде чем они закончатся?

    Используйте вес, указанный на коробке, чтобы определить возраст ребенка, и общее количество подгузников в коробке.

    Разделите общее количество на число подгузников, которые ребенок использует в день.

    В коробке 198 подгузников. На коробке указано, что подгузники предназначены для ребенка весом от 22 до 37 фунтов.

    В среднем, ребенку в этом весовом диапазоне, вероятно, от 1 до 2 лет.

    Двухлетний ребенок обычно использует 6 подгузников в день, поэтому подгузников хватит примерно на 33 дня (198/6).

    Если выходные данные модели слишком общие и недостаточно адаптированы к входному изображению,

    Чтобы помочь модели адаптировать свой ответ к изображению (изображениям), попробуйте попросить ее описать изображения, прежде чем выполнять задачу рассуждения.

    Быстрый Ответ модели

    Что общего между этими изображениями?

    Все четыре изображения являются примерами пейзажной фотографии.

    Обновлено сообщение Улучшенная реакция

    Для начала подробно опишите, что изображено на каждом изображении. Что общего у этих изображений?

    На первом изображении человек упаковывает чемодан. На втором изображении — пустой коридор в торговом центре. На третьем изображении — рулон туалетной бумаги. На четвёртом изображении — тёмное и бушующее море.

    Общим для всех этих изображений является то, что все они являются примерами пограничных пространств. Пограничные пространства — это места или ситуации, находящиеся между двумя другими местами или ситуациями. Они часто характеризуются чувством неопределенности или двусмысленности.

    На первом изображении человек находится в промежутке между домом и поездкой. На втором изображении показан коридор между двумя магазинами. На третьем изображении — туалетная бумага, которая может символизировать ванную комнату. Ванная комната — это переходное пространство между частной и общественной сферами. Это место, где мы готовимся войти во внешний мир или покинуть его.

    На четвертом изображении показано море в периоды между спокойствием и штормом.

    Пограничные пространства могут быть одновременно захватывающими и тревожными. Они могут быть местом новых начал или местом завершения. Они могут быть местом для размышлений или местом для действий.

    Вы также можете попробовать явно попросить модель ссылаться на то, что изображено на картинке.

    Обновлено сообщение Улучшенная реакция

    Что общего между этими изображениями? В своем ответе укажите, что изображено на картинках.

    Все изображения связаны с путешествиями. На первом изображении человек упаковывает чемодан, на втором — пустой коридор в торговом центре, на третьем — стопка туалетной бумаги, а на четвёртом — тёмное и бушующее море.

    Все эти изображения связаны с путешествиями, поскольку на них изображены вещи, которые нужны или используются людьми во время поездок. На первом изображении человек упаковывает чемодан, что является обычным делом для тех, кто отправляется в путешествие. На втором изображении показан пустой коридор в торговом центре, где люди часто покупают вещи для своих поездок. На третьем изображении показана стопка туалетной бумаги, что также часто используется в путешествиях. На четвертом изображении показано темное и бушующее море, с которым люди часто сталкиваются во время путешествий.

    Те же советы применимы и к созданию креативных работ на основе изображений. В следующем примере с кроликом, явное указание модели включить элементы изображения может улучшить результат.

    Быстрый Ответ модели

    Можете написать стихотворение об этом изображении?

    Маленький кролик, такой мягкий и коричневый,
    Прыгает по полю, вверх и вниз.
    У тебя такие длинные уши, а хвост такой маленький,
    Ты самое милое создание на свете.

    Ты пощипываешь траву, такую ​​зеленую и сладкую.
    И убегайте, когда меня увидите.
    Но я всегда буду твоим другом.
    Маленький кролик, до самого конца.

    Обновлено сообщение Улучшенная реакция

    Не могли бы вы написать для меня описательное и драматичное стихотворение об этом изображении, указав при этом место съемки?

    Маленький кролик на зелёном газоне,
    Такие длинные и такие чуткие уши.
    Что вы там видите?
    Вдали, куда ты смотришь?

    Это синева океана?
    Сверкает в лучах солнца?
    Или волны, которые разбиваются и ревут,
    Какой ритм вам нравится?

    Маленький кролик, скажи мне правду,
    Что именно так привлекло ваше внимание?
    Это из-за соленого бриза?
    Или, может быть, приятны крики чаек?

    Возможно, дело в масштабах всего происходящего.
    Мир одновременно и большой, и маленький.
    Место, где могут бродить мечты.
    И приключения можно посеять.

    Маленький зайчик, интересно, что тебе снится?
    Сидя на траве, испытываешь такое спокойствие.
    Вы стремитесь исследовать глубины?
    Или остаться на суше, где можно прыгать?

    Что бы это ни было, маленький зайчик,
    Пусть эта искра чуда продолжает ярко гореть.
    Ибо в ваших мечтах и ​​стремлениях,
    Существует мир, ожидающий вашего сотворения.

    Выявление причины сбоя части запроса.

    Трудно определить, почему запрос не сработал: либо модель изначально не поняла изображение , либо поняла его, но не выполнила необходимые шаги рассуждения . Чтобы разграничить эти причины, попросите модель описать, что изображено на картинке.

    В следующем примере, если модель выдает в ответ закуску, которая кажется неожиданной в сочетании с чаем (например, попкорн), вы можете сначала провести диагностику, чтобы определить, правильно ли модель распознала наличие чая на изображении.

    Быстрый Запрос на устранение неполадок

    Какую закуску можно приготовить за 1 минуту, которая хорошо бы к этому подошла?

    Опишите, что изображено на этом снимке.

    Ещё одна стратегия — попросить модель объяснить свои рассуждения. Это поможет вам определить, какая часть рассуждений оказалась неверной, если таковая имелась.

    Быстрый Запрос на устранение неполадок

    Какую закуску можно приготовить за 1 минуту, которая хорошо бы к этому подошла?

    Какую закуску можно приготовить за 1 минуту, которая хорошо бы к этому подошла? Пожалуйста, объясните, почему.

    Что дальше?

    • Попробуйте создать собственные мультимодальные подсказки с помощью Google AI Studio .
    • Для получения информации об использовании API Gemini Files для загрузки медиафайлов и их включения в запросы см. руководства по обработке видео , аудио и документов .
    • Дополнительные рекомендации по разработке подсказок, например, по настройке параметров выборки, см. на странице «Стратегии подсказок» .
    ,

    Gemini может одновременно обрабатывать различные типы входных данных, включая текст, изображения и аудио.

    В этом руководстве показано, как работать с медиафайлами с помощью Files API. Основные операции одинаковы для аудиофайлов, изображений, видео, документов и других поддерживаемых типов файлов.

    Инструкции по настройке параметров файлов см. в разделе « Руководство по настройке параметров файлов» .

    Загрузите файл

    Для загрузки медиафайлов можно использовать Files API. Всегда используйте Files API, если общий размер запроса (включая файлы, текстовое сообщение, системные инструкции и т. д.) превышает 100 МБ. Для файлов PDF лимит составляет 50 МБ.

    Следующий код загружает файл, а затем использует этот файл в вызове функции generateContent .

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file="path/to/sample.mp3")
    
    response = client.models.generate_content(
        model="gemini-3.8-flash", contents=["Describe this audio clip", myfile]
    )
    
    print(response.text)
    

    JavaScript

    import {
      GoogleGenAI,
      createUserContent,
      createPartFromUri,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const response = await ai.models.generateContent({
        model: "gemini-3.8-flash",
        contents: createUserContent([
          createPartFromUri(myfile.uri, myfile.mimeType),
          "Describe this audio clip",
        ]),
      });
      console.log(response.text);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Files.Delete(ctx, file.Name)
    
    resp, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", []*genai.Content{
      {
        Parts: []*genai.Part{
          genai.NewPartFromFile(*file),
          genai.NewPartFromText("Describe this audio clip"),
        },
      },
    }, nil)
    
    if err != nil {
        log.Fatal(err)
    }
    
    printResponse(resp)
    

    ОТДЫХ

    AUDIO_PATH="path/to/sample.mp3"
    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" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -D "${tmp_header_file}" \
      -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-3.8-flash:generateContent" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H 'Content-Type: application/json' \
        -X POST \
        -d '{
          "contents": [{
            "parts":[
              {"text": "Describe this audio clip"},
              {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
            }]
          }' 2> /dev/null > response.json
    
    cat response.json
    echo
    
    jq ".candidates[].content.parts[].text" response.json
    

    Получить метаданные для файла

    Вы можете убедиться в успешном сохранении загруженного файла через API и получить его метаданные, вызвав метод files.get .

    Python

    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)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      const fetchedFile = await ai.files.get({ name: fileName });
      console.log(fetchedFile);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    
    gotFile, err := client.Files.Get(ctx, file.Name)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Got file:", gotFile.Name)
    

    ОТДЫХ

    # file_info.json was created in the upload example
    name=$(jq ".file.name" file_info.json)
    # Get the file of interest to check state
    curl https://generativelanguage.googleapis.com/v1beta/files/$name \
    -H "x-goog-api-key: $GEMINI_API_KEY" > 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
    

    Список загруженных файлов

    Следующий код получает список всех загруженных файлов:

    Python

    from google import genai
    
    client = genai.Client()
    
    print('My files:')
    for f in client.files.list():
        print(' ', f.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const listResponse = await ai.files.list({ config: { pageSize: 10 } });
      for await (const file of listResponse) {
        console.log(file.name);
      }
    }
    
    await main();
    

    Идти

    for file, err := range client.Files.All(ctx) {
      if err != nil {
        log.Fatal(err)
      }
      fmt.Println(file.Name)
    }
    

    ОТДЫХ

    echo "My files: "
    
    curl "https://generativelanguage.googleapis.com/v1beta/files" \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Удалить загруженные файлы

    Файлы автоматически удаляются через 48 часов. Вы также можете удалить загруженный файл вручную:

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file='path/to/sample.mp3')
    client.files.delete(name=myfile.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      await ai.files.delete({ name: fileName });
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    client.Files.Delete(ctx, file.Name)
    

    ОТДЫХ

    curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Информация об использовании

    Вы можете использовать Files API для загрузки медиафайлов и взаимодействия с ними. Files API позволяет хранить до 20 ГБ файлов на проект, при этом максимальный размер каждого файла составляет 2 ГБ. Файлы хранятся в течение 48 часов.

    В течение этого времени вы можете использовать API для получения метаданных о файлах. Однако вы не можете загружать файлы, загруженные пользователями. Вы можете загружать файлы, созданные моделями, например, видео, используя метод files.download . API файлов доступен бесплатно во всех регионах, где доступен API Gemini.

    стратегии запроса файлов

    В этом разделе представлены рекомендации и лучшие практики использования медиафайлов с запросами к API Gemini.

    Возможность использовать различные типы данных в ваших запросах дает вам большую гибкость в плане того, какие задачи вы можете решать с помощью API Gemini. Например, вы можете отправить модели фотографию вкусного блюда и попросить ее написать короткий пост в блоге об этом блюде.

    Быстрый Ответ

    Напишите короткий, увлекательный пост в блоге, основанный на этой фотографии. Он должен включать описание блюда на фото и рассказ о моем опыте приготовления еды заранее.


    Печенье

    Предварительная подготовка еды — отличный способ сэкономить время и деньги, а также помочь вам питаться здоровее. Это блюдо — прекрасный пример полезного и вкусного блюда, которое легко приготовить заранее.

    В состав этого блюда входят бурый рис, запеченные овощи и курица терияки. Бурый рис — это полезный и сложный источник углеводов, который обеспечит вас энергией на длительное время. Запеченные овощи — отличный способ получить ежедневную дозу витаминов и минералов, а курица терияки — вкусный и богатый белком вариант.

    Это блюдо очень легко приготовить. Просто сварите коричневый рис, запеките овощи и приготовьте курицу терияки. После того, как все будет готово, разложите по контейнерам для хранения и уберите в холодильник. Тогда вы сможете взять контейнер и отправиться готовить по утрам, когда у вас мало времени!

    Если вы ищете полезное и вкусное блюдо, которое легко приготовить заранее, это отличный вариант. Оно богато питательными веществами и обладает насыщенным вкусом, и гарантированно обеспечит вам чувство сытости и удовлетворения.

    Желаем вам здорового и вкусного питания при приготовлении еды заранее!

    Если у вас возникли проблемы с получением желаемого результата от запросов, использующих медиафайлы, существуют стратегии, которые могут помочь вам добиться желаемого результата. В следующих разделах представлены подходы к проектированию и советы по устранению неполадок для улучшения запросов, использующих мультимодальный ввод.

    Вы можете улучшить свои мультимодальные подсказки, следуя этим рекомендациям:

    • Основы оперативного проектирования

      • Будьте конкретны в своих инструкциях : составьте четкие и лаконичные инструкции, которые сведут к минимуму возможность неправильного толкования.
      • Добавьте несколько примеров к своему заданию: используйте реалистичные примеры из нескольких кадров, чтобы проиллюстрировать, чего вы хотите достичь.
      • Разбейте задачу на этапы : разделите сложные задачи на выполнимые подзадачи, направляя модель на протяжении всего процесса.
      • Укажите формат вывода : в командной строке укажите желаемый формат вывода, например, Markdown, JSON, HTML и другие.
      • В подсказках с одним изображением размещайте изображение первым : хотя Gemini может обрабатывать изображения и текст в любом порядке, для подсказок, содержащих одно изображение, может быть эффективнее, если это изображение (или видео) будет размещено перед текстовой подсказкой. Однако для подсказок, требующих частого чередования изображений и текста для обеспечения осмысленности, используйте тот порядок, который вам наиболее естественен.
    • Устранение неполадок с многомодальным приглашением

      • Если модель не получает информацию из соответствующей части изображения: укажите, из каких аспектов изображения вы хотите, чтобы модель получала информацию.
      • Если выходные данные модели слишком общие (недостаточно адаптированы к входному изображению/видео): в начале запроса попробуйте попросить модель описать изображение(я) или видео до предоставления инструкции к заданию, или попробуйте попросить модель сослаться на то, что изображено на картинке.
      • Чтобы определить, какая именно часть не сработала: попросите модель описать изображение или объяснить свои рассуждения, чтобы оценить ее первоначальное понимание.
      • Если ваш запрос приводит к галлюцинациям: попробуйте уменьшить температуру или попросить модель дать более короткие описания, чтобы она с меньшей вероятностью могла додумать дополнительные детали.
      • Настройка параметров выборки: поэкспериментируйте с различными настройками температуры и выбором k лучших результатов, чтобы отрегулировать творческие возможности модели.

    Будьте конкретны в своих инструкциях.

    Наиболее эффективные запросы достигаются, когда они ясны и подробны. Если у вас есть конкретное требование к результату, лучше указать его в запросе, чтобы гарантировать получение желаемого результата.

    В случае с этим изображением табло аэропорта, запрос к модели просто «опишите это изображение» может сгенерировать общее описание. Если вам нужно, чтобы модель определила время и город на изображении, вы можете включить этот запрос непосредственно в ваше сообщение.

    Быстрый Ответ модели

    Опишите это изображение.

    На изображении показано табло прибытия и отправления рейсов в аэропорту.

    Обновлено сообщение Улучшенная реакция
    Расписание поездок

    С помощью программы для обработки времени и названия города, отображаемых на табло аэропорта на этом изображении, сформируйте список.

  • 10:50 Москва
  • 11:05 Эдинбург
  • 11:05 Лондон
  • 11:10 Бухарест
  • 11:30 Киев
  • 11:35 Дублин
  • 11:45 Ист-Мидлендс
  • 12:15 София
  • 12:30 Лондон
  • 12:30 Ньюкасл
  • 12:40 Санкт-Петербург
  • 12:40 Лондон
  • 12:45 Манчестер
  • Приведите несколько примеров.

    Модель Gemini может принимать несколько входных данных, которые она может использовать в качестве примеров для понимания желаемого результата. Добавление этих примеров помогает модели выявлять закономерности и применять взаимосвязь между заданными изображениями и ответами к новому примеру. Это также называется обучением с малым количеством примеров.

    В приведенном ниже примере исходный вывод представлен в виде предложения и содержит название страны (Бразилия). Предположим, вам нужен вывод в другом формате или стиле, и вы хотите получить только название города, а не страны. Добавление нескольких примеров к вашему запросу может направить модель к нужному вам способу ответа.

    Быстрый Ответ модели
    Расписание поездок

    Определите город и достопримечательность.

    Главная достопримечательность — статуя Христа-Искупителя в Рио-де-Жанейро, Бразилия.

    Обновлено сообщение Улучшенная реакция

    Определите город и достопримечательность.

    Колизей

    Город: Рим, достопримечательность: Колизей.

    Запретный город

    Город: Пекин, достопримечательность: Запретный город.

    запретный город

    Город: Рио-де-Жанейро, достопримечательность: статуя Христа-Искупителя.

    Разберите это пошагово.

    Для сложных задач, требующих как визуального восприятия, так и логического мышления, может быть полезно разбить задачу на более мелкие, простые шаги. В качестве альтернативы, может быть эффективно, если вы прямо попросите модель «думать шаг за шагом» в своем задании.

    Быстрый Ответ модели

    Когда у меня закончится туалетная бумага?

    Вскоре у вас останется всего 3 рулона.

    Обновлено сообщение Улучшенная реакция

      1. Сначала посчитайте, сколько рулонов туалетной бумаги изображено на этом рисунке.
      2. Затем определите, сколько туалетной бумаги использует среднестатистический человек в день.
      3. Рассчитайте, на сколько рулонов туалетной бумаги хватит.

      1. На этом изображении 3 рулона туалетной бумаги.
      2. Обычный человек использует около 20 листов туалетной бумаги в день.
      3. Если в каждом рулоне 200 листов, то каждого рулона хватит примерно на 10 дней. Следовательно, 3 рулонов хватит примерно на месяц.

    Математические задачи или другие виды текстовых задач отлично подходят для того, чтобы попросить модель мыслить пошагово.

    Быстрый Ответ

    Какой четвертый член последовательности?

    -135

    Ответ модели неверен. Для улучшения ситуации можно попросить модель проанализировать задачу перед тем, как ответить на вопрос.

    Быстрый Ответ

    Сначала разберите формулу на изображении.

    Затем, опираясь на формулу, ответьте на вопрос: «Какой четвертый член последовательности?».

    Нажмите, чтобы развернуть результат

    $$ b(n) = b(n-1) * (-3) $$

    $$ b(1) = 15 $$

    1. Подставьте n = 4 в формулу:
    2. $$ b(4) = b(4-1) * (-3) $$

      $$ b(4) = b(3) * (-3) $$

    3. Мы не знаем значения b(3), поэтому подставим n = 3 в формулу:
    4. $$ b(3) = b(3-1) * (-3) $$

      $$ b(3) = b(2) * (-3) $$

    5. Мы не знаем значения b(2), поэтому подставим n = 2 в формулу:
    6. $$ b(2) = b(2-1) * (-3) $$

      $$ b(2) = b(1) * (-3) $$

    7. Мы знаем, что значение b(1) равно 15, поэтому подставим его в формулу:
    8. $$ b(2) = 15 * (-3) $$

      $$ b(2) = -45 $$

    9. Теперь, когда мы знаем значение b(2), подставим его в формулу для b(3):
    10. $$ b(3) = b(2) * (-3) $$

      $$ b(3) = -45 * (-3) $$

      $$ b(3) = 135 $$

    11. Теперь, когда мы знаем значение b(3), подставим его в формулу для b(4):
    12. $$ b(4) = b(3) * (-3) $$

      $$ b(4) = 135 * (-3) $$

      $$ b(4) = -405 $$

    Следовательно, четвертый член последовательности равен -405.

    Этот ответ модели верен — теперь, чтобы сделать ответ еще более понятным, вы можете попросить модель думать пошагово.

    Обновлено сообщение Улучшенная реакция

    Какой четвёртый член последовательности? Подумайте пошагово.

    Первый семестр — 15.

    Второй член равен b(1) * (-3) = 15 * (-3) = -45.

    Третий член равен b(2) * (-3) = -45 * (-3) = 135.

    Четвертый член равен b(3) * (-3) = 135 * (-3) = -405.

    Укажите формат вывода

    Распространенная проблема — необходимость получения выходных данных модели в определенном формате (например, Markdown, JSON, HTML), особенно если эти данные должны быть обработаны последующей задачей. Вы можете попытаться получить выходные данные в этом формате, указав модели это в командной строке. Ниже приведены два примера:

    Быстрый Ответ модели

    Преобразуйте таблицу на этом изображении в формат Markdown.

    | Тема | Статус | Время | Дата начала | Дата окончания |

    | ------- | ------ | ---- | ---------- | ------ |

    | Математика | Выполнено | 1,5 часа | 29.11.2023 | 01.12.2023 |

    | География | Готово | 30 мин | 02.12.2023 | 04.12.2023 |

    | Физика | В процессе | 2 часа | 03.12.2023 | 05.12.2023 |

    | Биология | Не начато | 6 часов | 02.11.2016 | 06.12.2023 |

    Быстрый Ответ модели

    Предоставьте список всех следующих атрибутов:

    Ингредиенты, тип кухни, вегетарианская или нет, в формате JSON.

    ```json

    {

    "ингредиенты": [

    "рис",

    "креветка",

    "моллюски",

    "моллюски",

    "горох",

    «помидоры»,

    «лук»,

    "чеснок",

    "оливковое масло",

    «паприка»

    "соль",

    "перец"

    ],

    «Тип кухни»: «испанская».

    "вегетарианец": ложь

    }

    ```

    При выборе одного изображения, разместите ваше изображение первым.

    Хотя Близнецы могут интерпретировать изображение и текст в любом порядке в рамках подсказки, размещение одного изображения перед текстовой подсказкой может привести к лучшим результатам. В следующих примерах вы заметите, что в каждой подсказке изображение стоит перед текстом.

    Устранение неполадок с многомодальным приглашением

    Если вы не получаете полезного ответа, возможно, вам потребуется устранить неполадки в работе командной строки. Вот несколько стратегий, которые вы можете попробовать.

    Если модель не извлекает информацию из соответствующей части изображения

    Чтобы получить более конкретный ответ, вы можете указать, какие аспекты изображения вы хотите, чтобы система использовала для формирования ответа.

    Быстрый Ответ модели

    На сколько дней хватит этих подгузников для ребенка?

    Подгузников хватит на 198 дней.

    Обновлено сообщение Улучшенная реакция

    На сколько мне хватит этих подгузников, прежде чем они закончатся?

    Используйте вес, указанный на коробке, чтобы определить возраст ребенка, и общее количество подгузников в коробке.

    Разделите общее количество на число подгузников, которые ребенок использует в день.

    В коробке 198 подгузников. На коробке указано, что подгузники предназначены для ребенка весом от 22 до 37 фунтов.

    В среднем, ребенку в этом весовом диапазоне, вероятно, от 1 до 2 лет.

    Двухлетний ребенок обычно использует 6 подгузников в день, поэтому подгузников хватит примерно на 33 дня (198/6).

    Если выходные данные модели слишком общие и недостаточно адаптированы к входному изображению,

    Чтобы помочь модели адаптировать свой ответ к изображению (изображениям), попробуйте попросить ее описать изображения, прежде чем выполнять задачу рассуждения.

    Быстрый Ответ модели

    Что общего между этими изображениями?

    Все четыре изображения являются примерами пейзажной фотографии.

    Обновлено сообщение Улучшенная реакция

    Для начала подробно опишите, что изображено на каждом изображении. Что общего у этих изображений?

    На первом изображении человек упаковывает чемодан. На втором изображении — пустой коридор в торговом центре. На третьем изображении — рулон туалетной бумаги. На четвёртом изображении — тёмное и бушующее море.

    Общим для всех этих изображений является то, что все они являются примерами пограничных пространств. Пограничные пространства — это места или ситуации, находящиеся между двумя другими местами или ситуациями. Они часто характеризуются чувством неопределенности или двусмысленности.

    На первом изображении человек находится в промежутке между домом и поездкой. На втором изображении показан коридор между двумя магазинами. На третьем изображении — туалетная бумага, которая может символизировать ванную комнату. Ванная комната — это переходное пространство между частной и общественной сферами. Это место, где мы готовимся войти во внешний мир или покинуть его.

    На четвертом изображении показано море в периоды между спокойствием и штормом.

    Пограничные пространства могут быть одновременно захватывающими и тревожными. Они могут быть местом новых начал или местом завершения. Они могут быть местом для размышлений или местом для действий.

    Вы также можете попробовать явно попросить модель ссылаться на то, что изображено на картинке.

    Обновлено сообщение Улучшенная реакция

    Что общего между этими изображениями? В своем ответе укажите, что изображено на картинках.

    Все изображения связаны с путешествиями. На первом изображении человек упаковывает чемодан, на втором — пустой коридор в торговом центре, на третьем — стопка туалетной бумаги, а на четвёртом — тёмное и бушующее море.

    Все эти изображения связаны с путешествиями, поскольку на них изображены вещи, которые нужны или используются людьми во время поездок. На первом изображении человек упаковывает чемодан, что является обычным делом для тех, кто отправляется в путешествие. На втором изображении показан пустой коридор в торговом центре, где люди часто покупают вещи для своих поездок. На третьем изображении показана стопка туалетной бумаги, что также часто используется в путешествиях. На четвертом изображении показано темное и бушующее море, с которым люди часто сталкиваются во время путешествий.

    Те же советы применимы и к созданию креативных работ на основе изображений. В следующем примере с кроликом, явное указание модели включить элементы изображения может улучшить результат.

    Быстрый Ответ модели

    Можете написать стихотворение об этом изображении?

    Маленький кролик, такой мягкий и коричневый,
    Прыгает по полю, вверх и вниз.
    У тебя такие длинные уши, а хвост такой маленький,
    Ты самое милое создание на свете.

    Ты пощипываешь траву, такую ​​зеленую и сладкую.
    И убегайте, когда меня увидите.
    Но я всегда буду твоим другом.
    Маленький кролик, до самого конца.

    Обновлено сообщение Улучшенная реакция

    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.

    Troubleshooting which part of the prompt failed

    It can be hard to know whether a prompt failed because the model didn't understand the image to begin with, or if it did understand the image but did not perform the correct reasoning steps afterward. To disambiguate between those reasons, ask the model to describe what's in the image.

    In the following example, if the model responds with a snack that seems surprising when paired with tea (eg popcorn), you can first troubleshoot to determine whether the model correctly recognized that the image contains tea.

    Быстрый Prompt for troubleshooting

    What's a snack I can make in 1 minute that would go well with this?

    Describe what's in this image.

    Another strategy is to ask the model to explain its reasoning. That can help you narrow down which part of the reasoning broke down, if any.

    Быстрый Prompt for troubleshooting

    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.

    Что дальше?

    • Try writing your own multimodal prompts using Google AI Studio .
    • For information on using the Gemini Files API for uploading media files and including them in your prompts, see the Vision , Audio , and Document processing guides.
    • For more guidance on prompt design, like tuning sampling parameters, see the Prompt strategies page.
    ,

    Gemini can handle various types of input data, including text, images, and audio, at the same time.

    This guide shows you how to work with media files using the Files API. The basic operations are the same for audio files, images, videos, documents, and other supported file types.

    For file prompting guidance, check out the File prompt guide section.

    Загрузите файл

    You can use the Files API to upload a media file. Always use the Files API when the total request size (including the files, text prompt, system instructions, etc.) is larger than 100 MB. For PDF files, the limit is 50 MB.

    The following code uploads a file and then uses the file in a call to generateContent .

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file="path/to/sample.mp3")
    
    response = client.models.generate_content(
        model="gemini-3.8-flash", contents=["Describe this audio clip", myfile]
    )
    
    print(response.text)
    

    JavaScript

    import {
      GoogleGenAI,
      createUserContent,
      createPartFromUri,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const response = await ai.models.generateContent({
        model: "gemini-3.8-flash",
        contents: createUserContent([
          createPartFromUri(myfile.uri, myfile.mimeType),
          "Describe this audio clip",
        ]),
      });
      console.log(response.text);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Files.Delete(ctx, file.Name)
    
    resp, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", []*genai.Content{
      {
        Parts: []*genai.Part{
          genai.NewPartFromFile(*file),
          genai.NewPartFromText("Describe this audio clip"),
        },
      },
    }, nil)
    
    if err != nil {
        log.Fatal(err)
    }
    
    printResponse(resp)
    

    ОТДЫХ

    AUDIO_PATH="path/to/sample.mp3"
    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" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -D "${tmp_header_file}" \
      -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-3.8-flash:generateContent" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H 'Content-Type: application/json' \
        -X POST \
        -d '{
          "contents": [{
            "parts":[
              {"text": "Describe this audio clip"},
              {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
            }]
          }' 2> /dev/null > response.json
    
    cat response.json
    echo
    
    jq ".candidates[].content.parts[].text" response.json
    

    Получить метаданные для файла

    You can verify that the API successfully stored the uploaded file and get its metadata by calling files.get .

    Python

    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)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      const fetchedFile = await ai.files.get({ name: fileName });
      console.log(fetchedFile);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    
    gotFile, err := client.Files.Get(ctx, file.Name)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Got file:", gotFile.Name)
    

    ОТДЫХ

    # file_info.json was created in the upload example
    name=$(jq ".file.name" file_info.json)
    # Get the file of interest to check state
    curl https://generativelanguage.googleapis.com/v1beta/files/$name \
    -H "x-goog-api-key: $GEMINI_API_KEY" > 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
    

    Список загруженных файлов

    The following code gets a list of all the files uploaded:

    Python

    from google import genai
    
    client = genai.Client()
    
    print('My files:')
    for f in client.files.list():
        print(' ', f.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const listResponse = await ai.files.list({ config: { pageSize: 10 } });
      for await (const file of listResponse) {
        console.log(file.name);
      }
    }
    
    await main();
    

    Идти

    for file, err := range client.Files.All(ctx) {
      if err != nil {
        log.Fatal(err)
      }
      fmt.Println(file.Name)
    }
    

    ОТДЫХ

    echo "My files: "
    
    curl "https://generativelanguage.googleapis.com/v1beta/files" \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Delete uploaded files

    Files are automatically deleted after 48 hours. You can also manually delete an uploaded file:

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file='path/to/sample.mp3')
    client.files.delete(name=myfile.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      await ai.files.delete({ name: fileName });
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    client.Files.Delete(ctx, file.Name)
    

    ОТДЫХ

    curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Информация об использовании

    You can use the Files API to upload and interact with media files. The Files API lets you store up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours.

    During that time, you can use the API to get metadata about the files. However, you can't download user-uploaded files. You can download files generated by models, such as videos, using the files.download method. The Files API is available at no cost in all regions where the Gemini API is available.

    File prompting strategies

    This section provides guidance and best practices for using media files with prompts for the Gemini API.

    Being able to use various types of data in your prompts gives you more flexibility in terms of what tasks you can tackle with the Gemini API. For example, you can send the model a photo of a delicious meal and ask it to write a short blog about the meal.

    Быстрый Ответ

    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.


    Печенье

    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!

    If you are having trouble getting the output you want from prompts that use media files, there are some strategies that can help you get the results you want. The following sections provide design approaches and troubleshooting tips for improving prompts that use multimodal input.

    You can improve your multimodal prompts by following these best practices:

    • Prompt design fundamentals

      • Be specific in your instructions : Craft clear and concise instructions that leave minimal room for misinterpretation.
      • Add a few examples to your prompt: Use realistic few-shot examples to illustrate what you want to achieve.
      • Break it down step-by-step : Divide complex tasks into manageable sub-goals, guiding the model through the process.
      • Specify the output format : In your prompt, ask for the output to be in the format you want, like markdown, JSON, HTML and more.
      • 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.
    • Troubleshooting your multimodal prompt

      • 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.
      • 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.
      • 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.
      • 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.
      • Tuning the sampling parameters: Experiment with different temperature settings and top-k selections to adjust the model's creativity.

    Be specific in your instructions

    Prompts have the most success when they are clear and detailed. If you have a specific output in mind, it's better to include that requirement in the prompt to ensure you get the output you want.

    For this image of an airport board, asking the model to just "describe this image" could generate a general description. If you need the model to parse the time and city from the image, you can include that request directly in your prompt.

    Быстрый Ответ модели

    Опишите это изображение.

    The image shows an airport arrivals and departures board.

    Updated prompt Improved response
    Travel timetable

    Parse the time and city from the airport board shown in this image into a list.

  • 10:50 Moscow
  • 11:05 Edinburgh
  • 11:05 London
  • 11:10 Бухарест
  • 11:30 Kiev
  • 11:35 Dublin
  • 11:45 East Midlands
  • 12:15 Sofia
  • 12:30 Лондон
  • 12:30 Newcastle
  • 12:40 St Petersburg
  • 12:40 London
  • 12:45 Manchester
  • Add a few examples

    The Gemini model can accept multiple inputs which it can use as examples to understand the output you want. Adding these examples can help the model identify the patterns and apply the relationship between the given images and responses to the new example. This is also called "few-shot" learning.

    In the example below, the initial output is written in sentence form, and also contains the country (Brazil). Suppose you want the output in a different format or style, and you want only the city, not the country. Adding few-shot examples to your prompt can steer the model to respond in the way you want.

    Быстрый Ответ модели
    Travel timetable

    Determine the city along with the landmark.

    The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil.

    Updated prompt Improved response

    Determine the city along with the landmark.

    Колизей

    city: Rome, landmark: the Colosseum.

    Запретный город

    city: Beijing, landmark: Forbidden City

    forbidden-city

    city: Rio de Janeiro, landmark: Christ the Redeemer statue

    Break it down step-by-step

    For complex tasks like the ones that require both visual understanding and reasoning, it can be helpful to split the task into smaller, more straightforward steps. Alternatively, it could also be effective if you directly ask the model to “think step by step” in your prompt.

    Быстрый Ответ модели

    When will I run out of toilet paper?

    Soon, you only have 3 rolls left.

    Updated prompt Improved response

      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.

    Math problems or other types of word problems are great candidates for asking the model to think step-by-step.

    Быстрый Ответ

    What is the 4th term in the sequence?

    -135

    The response from the model is incorrect. Some ways to improve this is to ask the model to parse the problem before answering the prompt.

    Быстрый Ответ

    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:
    2. $$ b(4) = b(4-1) * (-3) $$

      $$ b(4) = b(3) * (-3) $$

    3. We don't know the value of b(3), so substitute n = 3 into the formula:
    4. $$ b(3) = b(3-1) * (-3) $$

      $$ b(3) = b(2) * (-3) $$

    5. We don't know the value of b(2), so substitute n = 2 into the formula:
    6. $$ b(2) = b(2-1) * (-3) $$

      $$ b(2) = b(1) * (-3) $$

    7. We know the value of b(1) is 15, so substitute it into the formula:
    8. $$ b(2) = 15 * (-3) $$

      $$ b(2) = -45 $$

    9. Now that we know the value of b(2), substitute it into the formula for b(3):
    10. $$ b(3) = b(2) * (-3) $$

      $$ b(3) = -45 * (-3) $$

      $$ b(3) = 135 $$

    11. Now that we know the value of b(3), substitute it into the formula for b(4):
    12. $$ b(4) = b(3) * (-3) $$

      $$ b(4) = 135 * (-3) $$

      $$ b(4) = -405 $$

    Therefore, the 4th term in the sequence is -405.

    This model response is correct - now to make the response even more streamlined, you can ask the model to to think step-by-step.

    Updated prompt Improved response

    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.

    Specify the output format

    A common problem is the need for model output to be in a certain format (eg markdown, JSON, HTML), especially if the model output needs to be ingested by a downstream task. You can try to produce output in that format by instructing the model to do so within the prompt. Below are two examples:

    Быстрый Ответ модели

    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 |

    Быстрый Ответ модели

    Provide a list of all the following attributes:

    ingredients, type of cuisine, vegetarian or not, in JSON format

    ```json

    {

    "ingredients": [

    "рис",

    "креветка",

    "моллюски",

    "моллюски",

    "горох",

    "tomatoes",

    "onions",

    "чеснок",

    "оливковое масло",

    "paprika",

    "соль",

    "перец"

    ],

    "type of cuisine": "Spanish",

    "vegetarian": false

    }

    ```

    Put your image first for single-image prompts

    While Gemini can interpret image and text in any order within a prompt, placing a single image before the text prompt might lead to better results. In the following samples, you'll notice the image comes first before the text in each prompt.

    Troubleshooting your multimodal prompt

    You might need to troubleshoot your prompt if you are not getting a helpful response. Here are a few strategies you could try.

    If the model is not drawing information from the relevant part of the image

    To get a more specific response, you can point out which aspects of the image you want the prompt to draw information from to inform its response.

    Быстрый Ответ модели

    How many days will these diapers last a baby?

    The diapers will last for 198 days before they run out.

    Updated prompt Improved response

    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).

    If the model output is too generic and not tailored enough to the image input

    To help the model tailor its response to the image(s), try asking it to describe the images before performing its reasoning task.

    Быстрый Ответ модели

    What is in common between these images?

    All four images are examples of landscape photography.

    Updated prompt Improved response

    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.

    You can also try explicitly asking the model to refer to what's in the image.

    Updated prompt Improved response

    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.

    The same tips work for creative output from images. In the following example with the rabbit, explicitly asking the model to include aspects from the image can improve the output.

    Быстрый Ответ модели

    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.

    Updated prompt Improved response

    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.

    Troubleshooting which part of the prompt failed

    It can be hard to know whether a prompt failed because the model didn't understand the image to begin with, or if it did understand the image but did not perform the correct reasoning steps afterward. To disambiguate between those reasons, ask the model to describe what's in the image.

    In the following example, if the model responds with a snack that seems surprising when paired with tea (eg popcorn), you can first troubleshoot to determine whether the model correctly recognized that the image contains tea.

    Быстрый Prompt for troubleshooting

    What's a snack I can make in 1 minute that would go well with this?

    Describe what's in this image.

    Another strategy is to ask the model to explain its reasoning. That can help you narrow down which part of the reasoning broke down, if any.

    Быстрый Prompt for troubleshooting

    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.

    Что дальше?

    • Try writing your own multimodal prompts using Google AI Studio .
    • For information on using the Gemini Files API for uploading media files and including them in your prompts, see the Vision , Audio , and Document processing guides.
    • For more guidance on prompt design, like tuning sampling parameters, see the Prompt strategies page.
    ,

    Gemini can handle various types of input data, including text, images, and audio, at the same time.

    This guide shows you how to work with media files using the Files API. The basic operations are the same for audio files, images, videos, documents, and other supported file types.

    For file prompting guidance, check out the File prompt guide section.

    Загрузите файл

    You can use the Files API to upload a media file. Always use the Files API when the total request size (including the files, text prompt, system instructions, etc.) is larger than 100 MB. For PDF files, the limit is 50 MB.

    The following code uploads a file and then uses the file in a call to generateContent .

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file="path/to/sample.mp3")
    
    response = client.models.generate_content(
        model="gemini-3.8-flash", contents=["Describe this audio clip", myfile]
    )
    
    print(response.text)
    

    JavaScript

    import {
      GoogleGenAI,
      createUserContent,
      createPartFromUri,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const response = await ai.models.generateContent({
        model: "gemini-3.8-flash",
        contents: createUserContent([
          createPartFromUri(myfile.uri, myfile.mimeType),
          "Describe this audio clip",
        ]),
      });
      console.log(response.text);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Files.Delete(ctx, file.Name)
    
    resp, err := client.Models.GenerateContent(ctx, "gemini-3.8-flash", []*genai.Content{
      {
        Parts: []*genai.Part{
          genai.NewPartFromFile(*file),
          genai.NewPartFromText("Describe this audio clip"),
        },
      },
    }, nil)
    
    if err != nil {
        log.Fatal(err)
    }
    
    printResponse(resp)
    

    ОТДЫХ

    AUDIO_PATH="path/to/sample.mp3"
    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" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -D "${tmp_header_file}" \
      -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-3.8-flash:generateContent" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H 'Content-Type: application/json' \
        -X POST \
        -d '{
          "contents": [{
            "parts":[
              {"text": "Describe this audio clip"},
              {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
            }]
          }' 2> /dev/null > response.json
    
    cat response.json
    echo
    
    jq ".candidates[].content.parts[].text" response.json
    

    Получить метаданные для файла

    You can verify that the API successfully stored the uploaded file and get its metadata by calling files.get .

    Python

    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)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      const fetchedFile = await ai.files.get({ name: fileName });
      console.log(fetchedFile);
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    
    gotFile, err := client.Files.Get(ctx, file.Name)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Got file:", gotFile.Name)
    

    ОТДЫХ

    # file_info.json was created in the upload example
    name=$(jq ".file.name" file_info.json)
    # Get the file of interest to check state
    curl https://generativelanguage.googleapis.com/v1beta/files/$name \
    -H "x-goog-api-key: $GEMINI_API_KEY" > 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
    

    Список загруженных файлов

    The following code gets a list of all the files uploaded:

    Python

    from google import genai
    
    client = genai.Client()
    
    print('My files:')
    for f in client.files.list():
        print(' ', f.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const listResponse = await ai.files.list({ config: { pageSize: 10 } });
      for await (const file of listResponse) {
        console.log(file.name);
      }
    }
    
    await main();
    

    Идти

    for file, err := range client.Files.All(ctx) {
      if err != nil {
        log.Fatal(err)
      }
      fmt.Println(file.Name)
    }
    

    ОТДЫХ

    echo "My files: "
    
    curl "https://generativelanguage.googleapis.com/v1beta/files" \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Delete uploaded files

    Files are automatically deleted after 48 hours. You can also manually delete an uploaded file:

    Python

    from google import genai
    
    client = genai.Client()
    
    myfile = client.files.upload(file='path/to/sample.mp3')
    client.files.delete(name=myfile.name)
    

    JavaScript

    import {
      GoogleGenAI,
    } from "@google/genai";
    
    const ai = new GoogleGenAI({});
    
    async function main() {
      const myfile = await ai.files.upload({
        file: "path/to/sample.mp3",
        config: { mimeType: "audio/mpeg" },
      });
    
      const fileName = myfile.name;
      await ai.files.delete({ name: fileName });
    }
    
    await main();
    

    Идти

    file, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", nil)
    if err != nil {
        log.Fatal(err)
    }
    client.Files.Delete(ctx, file.Name)
    

    ОТДЫХ

    curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name \
      -H "x-goog-api-key: $GEMINI_API_KEY"
    

    Информация об использовании

    You can use the Files API to upload and interact with media files. The Files API lets you store up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours.

    During that time, you can use the API to get metadata about the files. However, you can't download user-uploaded files. You can download files generated by models, such as videos, using the files.download method. The Files API is available at no cost in all regions where the Gemini API is available.

    File prompting strategies

    This section provides guidance and best practices for using media files with prompts for the Gemini API.

    Being able to use various types of data in your prompts gives you more flexibility in terms of what tasks you can tackle with the Gemini API. For example, you can send the model a photo of a delicious meal and ask it to write a short blog about the meal.

    Быстрый Ответ

    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.


    Печенье

    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!

    If you are having trouble getting the output you want from prompts that use media files, there are some strategies that can help you get the results you want. The following sections provide design approaches and troubleshooting tips for improving prompts that use multimodal input.

    You can improve your multimodal prompts by following these best practices:

    • Prompt design fundamentals

      • Be specific in your instructions : Craft clear and concise instructions that leave minimal room for misinterpretation.
      • Add a few examples to your prompt: Use realistic few-shot examples to illustrate what you want to achieve.
      • Break it down step-by-step : Divide complex tasks into manageable sub-goals, guiding the model through the process.
      • Specify the output format : In your prompt, ask for the output to be in the format you want, like markdown, JSON, HTML and more.
      • 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.
    • Troubleshooting your multimodal prompt

      • 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.
      • 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.
      • 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.
      • 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.
      • Tuning the sampling parameters: Experiment with different temperature settings and top-k selections to adjust the model's creativity.

    Be specific in your instructions

    Prompts have the most success when they are clear and detailed. If you have a specific output in mind, it's better to include that requirement in the prompt to ensure you get the output you want.

    For this image of an airport board, asking the model to just "describe this image" could generate a general description. If you need the model to parse the time and city from the image, you can include that request directly in your prompt.

    Быстрый Ответ модели

    Опишите это изображение.

    The image shows an airport arrivals and departures board.

    Updated prompt Improved response
    Travel timetable

    Parse the time and city from the airport board shown in this image into a list.

  • 10:50 Moscow
  • 11:05 Edinburgh
  • 11:05 London
  • 11:10 Бухарест
  • 11:30 Kiev
  • 11:35 Dublin
  • 11:45 East Midlands
  • 12:15 Sofia
  • 12:30 Лондон
  • 12:30 Newcastle
  • 12:40 St Petersburg
  • 12:40 London
  • 12:45 Manchester
  • Add a few examples

    The Gemini model can accept multiple inputs which it can use as examples to understand the output you want. Adding these examples can help the model identify the patterns and apply the relationship between the given images and responses to the new example. This is also called "few-shot" learning.

    In the example below, the initial output is written in sentence form, and also contains the country (Brazil). Suppose you want the output in a different format or style, and you want only the city, not the country. Adding few-shot examples to your prompt can steer the model to respond in the way you want.

    Быстрый Ответ модели
    Travel timetable

    Determine the city along with the landmark.

    The landmark is the Christ the Redeemer statue in Rio de Janeiro, Brazil.

    Updated prompt Improved response

    Determine the city along with the landmark.

    Колизей

    city: Rome, landmark: the Colosseum.

    Запретный город

    city: Beijing, landmark: Forbidden City

    forbidden-city

    city: Rio de Janeiro, landmark: Christ the Redeemer statue

    Break it down step-by-step

    For complex tasks like the ones that require both visual understanding and reasoning, it can be helpful to split the task into smaller, more straightforward steps. Alternatively, it could also be effective if you directly ask the model to “think step by step” in your prompt.

    Быстрый Ответ модели

    When will I run out of toilet paper?

    Soon, you only have 3 rolls left.

    Updated prompt Improved response

      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.

    Math problems or other types of word problems are great candidates for asking the model to think step-by-step.

    Быстрый Ответ

    What is the 4th term in the sequence?

    -135

    The response from the model is incorrect. Some ways to improve this is to ask the model to parse the problem before answering the prompt.

    Быстрый Ответ

    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:
    2. $$ b(4) = b(4-1) * (-3) $$

      $$ b(4) = b(3) * (-3) $$

    3. We don't know the value of b(3), so substitute n = 3 into the formula:
    4. $$ b(3) = b(3-1) * (-3) $$

      $$ b(3) = b(2) * (-3) $$

    5. We don't know the value of b(2), so substitute n = 2 into the formula:
    6. $$ b(2) = b(2-1) * (-3) $$

      $$ b(2) = b(1) * (-3) $$

    7. We know the value of b(1) is 15, so substitute it into the formula:
    8. $$ b(2) = 15 * (-3) $$

      $$ b(2) = -45 $$

    9. Now that we know the value of b(2), substitute it into the formula for b(3):
    10. $$ b(3) = b(2) * (-3) $$

      $$ b(3) = -45 * (-3) $$

      $$ b(3) = 135 $$

    11. Now that we know the value of b(3), substitute it into the formula for b(4):
    12. $$ b(4) = b(3) * (-3) $$

      $$ b(4) = 135 * (-3) $$

      $$ b(4) = -405 $$

    Therefore, the 4th term in the sequence is -405.

    This model response is correct - now to make the response even more streamlined, you can ask the model to to think step-by-step.

    Updated prompt Improved response

    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.

    Specify the output format

    A common problem is the need for model output to be in a certain format (eg markdown, JSON, HTML), especially if the model output needs to be ingested by a downstream task. You can try to produce output in that format by instructing the model to do so within the prompt. Below are two examples:

    Быстрый Ответ модели

    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 |

    Быстрый Ответ модели

    Provide a list of all the following attributes:

    ingredients, type of cuisine, vegetarian or not, in JSON format

    ```json

    {

    "ingredients": [

    "рис",

    "креветка",

    "моллюски",

    "моллюски",

    "горох",

    "tomatoes",

    "onions",

    "чеснок",

    "оливковое масло",

    "paprika",

    "соль",

    "перец"

    ],

    "type of cuisine": "Spanish",

    "vegetarian": false

    }

    ```

    Put your image first for single-image prompts

    While Gemini can interpret image and text in any order within a prompt, placing a single image before the text prompt might lead to better results. In the following samples, you'll notice the image comes first before the text in each prompt.

    Troubleshooting your multimodal prompt

    You might need to troubleshoot your prompt if you are not getting a helpful response. Here are a few strategies you could try.

    If the model is not drawing information from the relevant part of the image

    To get a more specific response, you can point out which aspects of the image you want the prompt to draw information from to inform its response.

    Быстрый Ответ модели

    How many days will these diapers last a baby?

    The diapers will last for 198 days before they run out.

    Updated prompt Improved response

    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).

    If the model output is too generic and not tailored enough to the image input

    To help the model tailor its response to the image(s), try asking it to describe the images before performing its reasoning task.

    Быстрый Ответ модели

    What is in common between these images?

    All four images are examples of landscape photography.

    Updated prompt Improved response

    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.

    You can also try explicitly asking the model to refer to what's in the image.

    Updated prompt Improved response

    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.

    The same tips work for creative output from images. In the following example with the rabbit, explicitly asking the model to include aspects from the image can improve the output.

    Быстрый Ответ модели

    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.

    Updated prompt Improved response

    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.

    Troubleshooting which part of the prompt failed

    It can be hard to know whether a prompt failed because the model didn't understand the image to begin with, or if it did understand the image but did not perform the correct reasoning steps afterward. To disambiguate between those reasons, ask the model to describe what's in the image.

    In the following example, if the model responds with a snack that seems surprising when paired with tea (eg popcorn), you can first troubleshoot to determine whether the model correctly recognized that the image contains tea.

    Быстрый Prompt for troubleshooting

    What's a snack I can make in 1 minute that would go well with this?

    Describe what's in this image.

    Another strategy is to ask the model to explain its reasoning. That can help you narrow down which part of the reasoning broke down, if any.

    Быстрый Prompt for troubleshooting

    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.

    Что дальше?

    • Try writing your own multimodal prompts using Google AI Studio .
    • For information on using the Gemini Files API for uploading media files and including them in your prompts, see the Vision , Audio , and Document processing guides.
    • For more guidance on prompt design, like tuning sampling parameters, see the Prompt strategies page.