# Files API

Gemini可以同时处理多种类型的输入数据，包括文本、图像和音频。

本指南向您展示如何使用 Files API 处理媒体文件。音频文件、图像、视频、文档和其他支持的文件类型的基本操作相同。

有关文件提示指南，请查看 [文件提示引导](/docs/files#prompt-guide) 部分。

## 上传文件  {% #upload-audio %}

您可以使用Files API上传媒体文件。当总请求大小（包括文件、文本提示、系统指令等）大于 100 MB 时，请始终使用 Files API。对于 PDF 文件，限制为 50 MB。

以下代码上传一个文件，然后在调用中使用该文件 `interactions.create`.

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

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

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input=[
        {"type": "text", "text": "Describe this audio clip"},
        {"type": "audio", "uri": myfile.uri, "mime_type": myfile.mime_type}
    ]
)

print(interaction.output_text)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

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

  const interaction = await client.interactions.create({
    model: "gemini-4-hydrogen",
    input: [
      { type: "text", text: "Describe this audio clip" },
      { type: "audio", uri: myfile.uri, mime_type: myfile.mimeType }
    ]
  });
  console.log(interaction.output_text);
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.AudioContent;
import com.google.genai.gaos.models.interactions.AudioContentMimeType;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import com.google.genai.types.File;
import com.google.genai.types.UploadFileConfig;
import java.util.Arrays;
import java.util.List;

Client client = new Client();

File myFile =
    client.files.upload(
        new java.io.File("path/to/sample.mp3"),
        UploadFileConfig.builder().mimeType("audio/mp3").build());

Content textContent = TextContent.builder().text("Describe this audio clip").build();
Content audioContent =
    AudioContent.builder()
        .uri(myFile.uri().orElse(""))
        .mimeType(AudioContentMimeType.of(myFile.mimeType().orElse("audio/mp3")))
        .build();

List<Content> contents = Arrays.asList(textContent, audioContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-4-hydrogen"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    myFile, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", &genai.UploadFileConfig{
        MIMEType: "audio/mp3",
    })
    if err != nil {
        log.Fatal(err)
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-4-hydrogen"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: "Describe this audio clip",
                }),
                interactions.NewContent(interactions.AudioContent{
                    URI:      genai.Ptr(myFile.URI),
                    MimeType: interactions.AudioContentMimeType(myFile.MIMEType).ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
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 create an interaction using the Interactions API
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -H "Api-Revision: 2026-05-20" \
    -d '{
      "model": "gemini-4-hydrogen",
      "input": [
        {"type": "text", "text": "Describe this audio clip"},
        {"type": "audio", "uri": '$file_uri', "mime_type": "'${MIME_TYPE}'"}
      ]
    }' 2> /dev/null > response.json

cat response.json
echo

jq ".outputs[] | select(.type == \"text\") | .text" response.json
```
{% /tab %}

{% tab label="CLI" %}
```bash
FILE=$(gemini-api files upload path/to/sample.mp3 --wait)
gemini-api generate "Describe this audio clip" -m gemini-4-hydrogen -i "$FILE"
```
{% /tab %}
{% /tabs %}

## 获取文件的元数据  {% #get-metadata %}

您可以通过调用验证API是否成功存储了上传的文件并获取其元数据 `files.get`.

{% tabs %}
{% tab label="Python" %}
```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)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import {
  GoogleGenAI,
} from "@google/genai";

const client = new GoogleGenAI({});

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

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

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.File;
import com.google.genai.types.UploadFileConfig;

Client client = new Client();

File myFile =
    client.files.upload(
        new java.io.File("path/to/sample.mp3"),
        UploadFileConfig.builder().mimeType("audio/mp3").build());

String fileName = myFile.name().orElse("");
File fileMetadata = client.files.get(fileName, null);
System.out.println(fileMetadata);
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    myFile, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", &genai.UploadFileConfig{
        MIMEType: "audio/mp3",
    })
    if err != nil {
        log.Fatal(err)
    }

    fileMetadata, err := client.Files.Get(ctx, myFile.Name, nil)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(fileMetadata)
}
```
{% /tab %}

{% tab label="REST" %}
```shell
# file_info.json was created in the upload example
name=$(jq -r ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/$name \
-H "x-goog-api-key: $GEMINI_API_KEY" > file_info.json
# Print some information about the file you got
name=$(jq -r ".name" file_info.json)
echo name=$name
file_uri=$(jq -r ".uri" file_info.json)
echo file_uri=$file_uri
```
{% /tab %}

{% tab label="CLI" %}
```bash
FILE=$(gemini-api files upload path/to/sample.mp3)
gemini-api files get "$FILE"
```
{% /tab %}
{% /tabs %}

## 列出已上传的文件  {% #list-uploaded %}

以下代码获取所有上传文件的列表：

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

print('My files:')
for f in client.files.list():
    print(' ', f.name)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import {
  GoogleGenAI,
} from "@google/genai";

const client = new GoogleGenAI({});

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

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.File;

Client client = new Client();

System.out.println("My files:");
for (File f : client.files.list(null)) {
  System.out.println("  " + f.name().orElse(""));
}
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("My files:")
    for f, err := range client.Files.All(ctx) {
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(" ", f.Name)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
echo "My files: "

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

{% tab label="CLI" %}
```bash
gemini-api files list --all --jq '.files[]?.name'
```
{% /tab %}
{% /tabs %}

## 删除上传的文件  {% #delete-uploaded %}

文件将在 48 小时后自动删除。您还可以手动删除上传的文件：

{% tabs %}
{% tab label="Python" %}
```python
from google import genai

client = genai.Client()

myfile = client.files.upload(file='path/to/sample.mp3')
client.files.delete(name=myfile.name)
```
{% /tab %}

{% tab label="JavaScript" %}
```javascript
import {
  GoogleGenAI,
} from "@google/genai";

const client = new GoogleGenAI({});

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

  const fileName = myfile.name;
  await client.files.delete({ name: fileName || '' });
}

await main();
```
{% /tab %}

{% tab label="Java" %}
```java
import com.google.genai.Client;
import com.google.genai.types.File;
import com.google.genai.types.UploadFileConfig;

Client client = new Client();

File myFile =
    client.files.upload(
        new java.io.File("path/to/sample.mp3"),
        UploadFileConfig.builder().mimeType("audio/mp3").build());

client.files.delete(myFile.name().orElse(""), null);
```
{% /tab %}

{% tab label="Go" %}
```go
package main

import (
    "context"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }

    myFile, err := client.Files.UploadFromPath(ctx, "path/to/sample.mp3", &genai.UploadFileConfig{
        MIMEType: "audio/mp3",
    })
    if err != nil {
        log.Fatal(err)
    }

    if _, err := client.Files.Delete(ctx, myFile.Name, nil); err != nil {
        log.Fatal(err)
    }
}
```
{% /tab %}

{% tab label="REST" %}
```shell
curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/$name \
  -H "x-goog-api-key: $GEMINI_API_KEY"
```
{% /tab %}

{% tab label="CLI" %}
```bash
FILE=$(gemini-api files upload path/to/sample.mp3)
gemini-api files delete "$FILE"
```
{% /tab %}
{% /tabs %}

## 使用信息  {% #usage-info %}

您可以使用 Files API 上传媒体文件并与之交互。 Files API 允许您为每个项目存储最多 20 GB 的文件，每个文件的最大大小为 2 GB。文件存储时间为 48 小时。

在此期间，您可以使用 API 获取有关文件的元数据。但是，您无法下载用户上传的文件。您可以使用以下命令下载模型生成的文件，例如视频 `files.download` 方法。 Files API 在提供 Gemini API 的所有地区免费提供。

## 文件提示策略  {% #prompt-guide %}

本节提供有关使用带有 Gemini API 提示的媒体文件的指南和最佳实践。

能够在提示中使用各种类型的数据，使您可以更灵活地使用 Gemini API 处理哪些任务。例如，您可以向模型发送一张美味佳肴的照片，并要求其写一篇关于这顿饭的简短博客。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**提示**
{% /doc-cell %}

{% doc-cell %}
**回应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
根据这张图片写一篇简短、引人入胜的博客文章。它应该包括照片中餐食的描述，并谈论我的旅途餐食准备过程。

![](https://www.gstatic.com/cloud-cms/16043e598e2b76cf73c90625b5cd4202.png)
{% /doc-cell %}

{% doc-cell %}
准备饭菜是节省时间和金钱的好方法，而且还可以帮助您吃得更健康。这顿饭是可以提前准备的健康美味膳食的一个很好的例子。这顿饭的特色是糙米、烤蔬菜和照烧鸡肉。糙米是一种健康且复杂的碳水化合物，可为您提供持续的能量。烤蔬菜是获取每日维生素和矿物质的好方法，而照烧鸡肉是美味且富含蛋白质的选择。这顿饭准备起来也很简单。只需煮糙米，烤蔬菜，然后煮照烧鸡肉。一切煮熟后，将其放入备餐容器中并存放在冰箱中。然后您就可以拿起一个容器，开始忙碌的早晨！如果您正在寻找一顿可以提前准备的健康美味的饭菜，那么这顿饭是一个不错的选择。它富含营养和风味，一定会让您感到饱足和满足。这是准备健康美味的饭菜！
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

如果您无法从使用媒体文件的提示中获得所需的输出，有一些策略可以帮助您获得所需的结果。以下部分提供了改进使用多模态输入的提示的设计方法和故障排除技巧。

您可以通过遵循以下最佳实践来改进多模态提示：

* **[快速设计基础](/docs/files#specific-instructions)**  *   **请在您的说明中具体说明**：制定清晰简洁的说明，尽量减少误解的空间。

  * **在提示中添加一些示例**：使用现实的小例子来说明您想要实现的目标。
  * **一步步分解**：将复杂的任务划分为可管理的子目标，指导模型完成整个过程。
  * **指定输出格式**：在提示中，要求输出采用您想要的格式，例如 Markdown、JSON、HTML 等。
  * **对于单图像提示，请将您的图像放在第一位**：虽然 Gemini 可以按任何顺序处理图像和文本输入，但对于包含单个图像的提示，如果将该图像放置在文本提示之前，效果可能会更好。

* **[对多模态提示进行故障排除](/docs/files#troubleshooting)**  *   **如果模型没有从图像的相关部分绘制信息**：删除提示，提示您希望提示从图像的哪些方面提取信息。

  * **如果模型输出太通用（没有针对图像进行足够的定制）**：在提示开始时，尝试要求模型在提供任务说明之前描述图像，或者尝试要求模型参考图像中的内容。

### 请在您的说明中具体说明  {% #specific-instructions %}

当提示清晰且详细时，它会取得最大的成功。如果您有特定的输出，最好在提示中包含该要求，以确保获得所需的输出。

对于这张机场董事会的图像，要求模型仅“描述该图像”就可以生成一般描述。如果您需要模型从图像中解析时间和城市，您可以直接在提示中包含该请求。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/ce337b5b79a15e364db421596f86353c.png)
{% /doc-cell %}

{% doc-cell %}
该图显示了机场到达和出发板。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/ce337b5b79a15e364db421596f86353c.png)
将此图中显示的机场板中的时间和城市解析为列表。
{% /doc-cell %}

{% doc-cell %}
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 曼彻斯特
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

### 添加几个例子  {% #add-a-few-examples %}

Gemini 模型可以接受多个输入，它可以用作示例来了解您想要的输出。添加这些示例可以帮助模型识别模式并将给定图像和响应之间的关系应用到新示例。这也称为“小样本”学习。

在以下示例中，初始输出以句子形式编写，并且还包含国家/地区（巴西）。假设您希望以不同的格式或样式输出，并且您只需要城市，而不需要国家/地区。在提示中添加少量示例可以引导模型按照您想要的方式做出响应。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**提示**
{% /doc-cell %}

{% doc-cell %}
**模型响应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/c75f4d57229a316cefb7e84b9d6f6458.png)确定城市以及地标。
{% /doc-cell %}

{% doc-cell %}
标志性建筑是巴西里约热内卢的基督救世主雕像。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
确定城市以及地标。 ![](https://www.gstatic.com/cloud-cms/6764f6e86aaa8af76882b09d37fc5e23.png)
{% /doc-cell %}

{% doc-cell %}
城市：罗马，地标：罗马斗兽场。
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/1e37dfdd70d0b6ff26e5fffb0a04b71f.png)
{% /doc-cell %}

{% doc-cell %}
城市: 北京, 地标: 紫禁城
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/c75f4d57229a316cefb7e84b9d6f6458.png)
{% /doc-cell %}

{% doc-cell %}
城市：里约热内卢，地标：基督救世主雕像
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

### 一步步分解  {% #break-it-down-step-by-step %}

对于复杂的任务，例如需要视觉理解和推理的任务，将任务分成更小、更简单的步骤可能会有所帮助。或者，如果您直接要求模型在提示中“逐步思考”，也可能会有效。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/556c63543fcbb2efc7696a0d5d85ce44.jpg)
我什么时候会用完卫生纸？
{% /doc-cell %}

{% doc-cell %}
很快，您就只剩下 3 卷了。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/556c63543fcbb2efc7696a0d5d85ce44.jpg)
首先，数一数这张图中有多少卷卫生纸。然后，确定一个人每天使用多少卫生纸。计算一下这些卫生纸卷能用多久。
{% /doc-cell %}

{% doc-cell %}
这张图中有 3 卷卫生纸。一般人每天大约使用 20 张卫生纸。如果每卷包含 200 纸张，则每卷将持续大约 10 天。因此，3 卷的使用寿命约为一个月。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

数学问题或其他类型的文字问题非常适合要求模型逐步思考。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**提示**
{% /doc-cell %}

{% doc-cell %}
**回应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/1713c829afa7fa9b5250dc43e703cc70.jpg)
序列中的第四项是什么？
{% /doc-cell %}

{% doc-cell %}
-135
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

模型的响应不正确。改进这一点的一些方法是要求模型在回答提示之前解析问题。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**提示**
{% /doc-cell %}

{% doc-cell %}
**回应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/1713c829afa7fa9b5250dc43e703cc70.jpg)
首先解析图像中的公式。然后根据公式回答“序列中的第四项是什么？”。
{% /doc-cell %}

{% doc-cell %}
*点击展开结果*
$ b(n) = b(n-1) * (-3) $ $ b(1) = 15 $ 将 n = 4 代入公式： $ b(4) = b(4-1) * (-3) $ $ b(4) = b(3) * (-3) $ 我们不知道 b(3) 的值，因此替换 n =将 3 代入公式： $ b(3) = b(3-1) * (-3) $ $ b(3) = b(2) * (-3) $ 我们不知道 b(2) 的值，因此将 n = 2 代入公式中： $ b(2) = b(2-1) * (-3) $ $ b(2) = b(1) * (-3) $ 我们知道 b(1) 的值为 15,，因此将其代入公式： $ b(2) = 15 * (-3) $ $ b(2) = -45 $ 现在我们知道了 b(2) 的值，将其代入 b(3) 的公式中： $ b(3) = b(2) * (-3) $ $ b(3) = -45 * (-3) $ $ b(3) = 135 $ 现在我们知道了 b(3) 的值，将其代入 b(4) 的公式中： $ b(4) = b(3) * (-3) $ $ b(4) = 135 * (-3) $ $ b(4) = -405 $ 因此，序列中的第四项是 -405.
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

该模型响应是正确的 - 现在为了使响应更加简化，您可以要求模型逐步思考。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/1713c829afa7fa9b5250dc43e703cc70.jpg)
序列中的第四项是什么？一步步思考。
{% /doc-cell %}

{% doc-cell %}
第一项是 15. 第二项是 b(1) * (-3) = 15 * (-3) = -45. 第三项是 b(2) * (-3) = -45 * (-3) = 135. 第四项是 b(3) * (-3) = 135 * (-3) = -405.
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

### 指定输出格式  {% #specify-the-output-format %}

一个常见的问题是模型输出需要采用某种格式（例如 Markdown、JSON、HTML），特别是当模型输出需要由下游任务摄取时。您可以通过在提示中指示模型执行此操作来尝试生成该格式的输出。下面是两个例子：

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/7dad070133c3c7ffb409a80bd2e17f92.png)
将此图像中的表格解析为 Markdown 格式
{% /doc-cell %}

{% doc-cell %}
```none
  | Subject | Status | Time | Start date | Due on |
  | ------- | ------ | ---- | ---------- | ------ |
  | Math | Done | 1.5 hrs | 11/29/2023 | 12/1/2023 |
  | Geography | Done | 30 min | 12/2/2023 | 12/4/2023 |
  | Physics | In progress | 2 hrs | 12/3/2023 | 12/5/2023 |
  | Biology | Not started | 6 hrs | 11/2/2016 | 12/6/2023 |
```
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**提示**
{% /doc-cell %}

{% doc-cell %}
**模型响应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/09e773a60f61717072e458669e53119e.png)
提供以下所有属性的列表：成分、菜肴类型、素食与否，采用 JSON 格式
{% /doc-cell %}

{% doc-cell %}
```json
  {
  "ingredients": [
  "rice",
  "shrimp",
  "clams",
  "mussels",
  "peas",
  "tomatoes",
  "onions",
  "garlic",
  "olive oil",
  "paprika",
  "salt",
  "pepper"
  ],
  "type of cuisine": "Spanish",
  "vegetarian": false
  }
```
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

### 对于单图像提示，请将您的图像放在第一位  {% #single-image-prompts %}

虽然 Gemini 可以在提示中以任意顺序解释图像和文本，但在文本提示之前放置单个图像可能会产生更好的结果。在以下示例中，您会注意到每个提示中图像首先出现在文本之前。

### 对多模态提示进行故障排除  {% #troubleshooting %}

如果您没有得到有用的回复，您可能需要对提示进行故障排除。以下是您可以尝试的一些策略。

#### 如果模型没有从图像的相关部分绘制信息  {% #if-the-model-is-not-drawing-information-from-the-relevant-part-of-the-image %}

要获得更具体的响应，您可以指出您希望提示从图像的哪些方面提取信息以告知其响应。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/34f7e4cef20c432692eccd6714a0dfc5.png)
这些尿布可以给宝宝用几天？
{% /doc-cell %}

{% doc-cell %}
尿布在用完之前可以使用 198 天。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/34f7e4cef20c432692eccd6714a0dfc5.png)
这些尿布能用多久？使用盒子上显示的重量来确定孩子的年龄，并使用盒子中尿布的总数。将总数除以孩子每天换尿布的数量。
{% /doc-cell %}

{% doc-cell %}
盒子里装有 198 尿布。盒子上注明尿布适用于体重为 22-37 磅的儿童。此体重范围内的儿童平均年龄可能在 1 至 2 岁之间。 2 岁的儿童通常每天都会使用 6 尿布，因此，尿布将持续大约 33 天（198/6）。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

#### 如果模型输出过于通用并且没有针对图像输入进行足够的定制  {% #if-the-model-output-is-too-generic-and-not-tailored-enough-to-the-image-input %}

为了帮助模型调整其对图像的响应，请尝试要求其在执行推理任务之前描述图像。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/11ccc8ffe775cf47201136a3c0563144.jpg)
![](https://www.gstatic.com/cloud-cms/7d1f11cedb5f37ff8937b90f18eacf50.jpg)
![](https://www.gstatic.com/cloud-cms/556c63543fcbb2efc7696a0d5d85ce44.jpg)
![](https://www.gstatic.com/cloud-cms/8f7351fd5648f2d710f74c0bd1e62afa.jpg)
这些图像之间有什么共同点？
{% /doc-cell %}

{% doc-cell %}
所有四幅图像都是风景摄影的例子。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/11ccc8ffe775cf47201136a3c0563144.jpg)
![](https://www.gstatic.com/cloud-cms/7d1f11cedb5f37ff8937b90f18eacf50.jpg)
![](https://www.gstatic.com/cloud-cms/556c63543fcbb2efc7696a0d5d85ce44.jpg)
![](https://www.gstatic.com/cloud-cms/8f7351fd5648f2d710f74c0bd1e62afa.jpg)
首先，详细描述每张图像中的内容。这些图像之间有什么共同点？
{% /doc-cell %}

{% doc-cell %}
第一张图片显示一个人收拾行李箱。第二张图片显示了购物中心空荡荡的走廊。第三张图片显示了一卷卫生纸。第四张图片显示了一片黑暗且波涛汹涌的大海。

这些图像的共同点是它们都是阈限空间的例子。阈限空间是位于两个其他地方或情况之间的地方或情况。它们通常具有不确定性或模糊性的特点。

第一张图片显示了一个人在家里和旅行之间的状态。第二张图显示了两家商店之间的走廊。第三张图片是卫生纸，它可以代表浴室。浴室是私人领域和公共领域之间的过渡空间。这是我们为进入或离开外部世界做好准备的地方。

第四张图片显示了介于平静和暴风雨之间的大海。

阈限空间既令人兴奋又令人不安。它们可以是新的开始的地方，也可以是结束的地方。它们可以是反思的场所，也可以是行动的场所。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

您还可以尝试明确要求模型参考图像中的内容。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/11ccc8ffe775cf47201136a3c0563144.jpg)
![](https://www.gstatic.com/cloud-cms/7d1f11cedb5f37ff8937b90f18eacf50.jpg)
![](https://www.gstatic.com/cloud-cms/556c63543fcbb2efc7696a0d5d85ce44.jpg)
![](https://www.gstatic.com/cloud-cms/8f7351fd5648f2d710f74c0bd1e62afa.jpg)
这些图像之间有什么共同点？请参阅您回复中的图片内容。
{% /doc-cell %}

{% doc-cell %}
所有图像都与旅行有关。第一张图片显示一个人正在收拾行李箱，第二张图片显示购物中心空荡荡的走廊，第三张图片显示一叠卫生纸，第四张图片显示黑暗和波涛汹涌的大海。

这些图像都与旅行有关，因为它们都是人们在旅行时需要或使用的东西。第一张图片显示一个人收拾行李，这是人们在旅行时所做的事情。第二张图片显示了购物中心空荡荡的走廊，这是人们经常去购买旅行物品的地方。第三张图显示了一叠卫生纸，这是人们在旅行时经常使用的东西。第四张图展示了一片漆黑、波涛汹涌的大海，这是人们在旅行时经常遇到的情况。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

同样的技巧也适用于图像的创意输出。在下面的兔子示例中，明确要求模型包含图像中的各个方面可以改善输出。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
模型响应
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/c3755985176e1cba66432e301b16b92c.jpg)
你能为我写一首关于这个图像的诗吗？
{% /doc-cell %}

{% doc-cell %}
小兔子，那么柔软，棕色，在田野里跳来跳去。你的耳朵那么长，你的尾巴那么小，你是所有生物中最可爱的。

你轻咬青草，青翠欲滴，看到我就跳开。但我永远是你的朋友，小兔子，直到最后。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
**更新提示**
{% /doc-cell %}

{% doc-cell %}
**改善反应**
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/c3755985176e1cba66432e301b16b92c.jpg)
你能为我写一首关于这张照片的描述性和戏剧性的诗并包括地点吗？
{% /doc-cell %}

{% doc-cell %}
绿色的小兔子，耳朵那么长，那么敏锐。在你凝视的远方，你看到了什么？

是海洋的蓝色，在阳光的色调下闪闪发光吗？还是汹涌澎湃的海浪，你喜欢的节奏？

小兔子，告诉我实话，什么如此吸引你的注意力？是咸咸的微风，还是海鸥的叫声？

也许这就是一切的浩瀚，世界如此之大和如此之小。一个可以漫游梦想、可以播种冒险的地方。

小兔子，我不知道你做了什么梦，你坐在草地上，那么安详。您是否渴望探索深处，还是留在陆地上，在那里您可以跳跃？

不管是什么，小兔子，让奇迹的火花永远燃烧吧。因为在你的梦想和抱负中，蕴藏着一个等待你创造的世界。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

#### 排除提示的哪一部分失败的问题  {% #troubleshooting-which-part-of-the-prompt-failed %}

很难知道提示是否失败，因为模型没有 **理解图像** 首先，或者如果它确实理解图像但没有执行正确的操作 **推理步骤** 之后。为了消除这些原因之间的歧义，请要求模型描述图像中的内容。

在以下示例中，如果模型响应与茶搭配时看起来令人惊讶的零食（例如爆米花），您可以首先进行故障排除以确定模型是否正确识别出图像中包含茶。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
提示故障排除
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/dc5ca83828db596dd80c52488447cb47.png)
我可以在 1 分钟内制作什么零食来搭配这个？
{% /doc-cell %}

{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/dc5ca83828db596dd80c52488447cb47.png)
描述一下这张图片中的内容。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

另一种策略是要求模型解释其推理。这可以帮助你缩小推理失败的部分（如果有）。

{% doc-table %}
{% doc-row header="true" %}
{% doc-cell %}
提示
{% /doc-cell %}

{% doc-cell %}
提示故障排除
{% /doc-cell %}
{% /doc-row %}

{% doc-row header="false" %}
{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/dc5ca83828db596dd80c52488447cb47.png)
我可以在 1 分钟内制作什么零食来搭配这个？
{% /doc-cell %}

{% doc-cell %}
![](https://www.gstatic.com/cloud-cms/dc5ca83828db596dd80c52488447cb47.png)
我可以在 1 分钟内制作什么零食来搭配这个？请解释原因。
{% /doc-cell %}
{% /doc-row %}
{% /doc-table %}

## 后续步骤  {% #whats-next %}

- 尝试使用以下命令编写您自己的多模态提示 [Google AI Studio](http://aistudio.google.com).

- 有关使用 Gemini Files API 上传媒体文件并将其包含在提示中的信息，请参阅 [愿景](/docs/image-understanding), [音频](/docs/audio), 和 [文件处理](/docs/document-processing) 指南。

- 有关提示设计的更多指导，例如调整采样参数，请参阅 [即时策略](/docs/prompting-strategies) 页。
