Using files

方法:media.upload

创建 File

端点

<ph type="x-smartling-placeholder"></ph> 上传 URI,用于媒体上传请求:
`post
https://generativelanguage.googleapis.com/upload/v1beta/files

  • 元数据 URI,适用于仅包含元数据的请求:
    POST https://generativelanguage.googleapis.com/v1beta/files该网址使用 gRPC 转码语法。

请求正文

请求正文中包含结构如下的数据:

<ph type="x-smartling-placeholder">
</ph> 田野
file object (File)

可选。要创建的文件的元数据。

示例请求

映像

Python

myfile = genai.upload_file(media / "Cajun_instruments.jpg")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content(
    [myfile, "\n\n", "Can you tell me about the instruments in this photo?"]
)
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);
// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this image.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

音频

Python

myfile = genai.upload_file(media / "sample.mp3")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content([myfile, "Describe this audio clip"])
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/samplesmall.mp3`,
  {
    mimeType: "audio/mp3",
    displayName: "Audio sample",
  },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Audio processing failed.");
}

// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this audio clip.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

文字

Python

myfile = genai.upload_file(media / "poem.txt")
print(f"{myfile=}")

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content(
    [myfile, "\n\n", "Can you add a few more lines to this poem?"]
)
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(`${mediaPath}/a11.txt`, {
  mimeType: "text/plain",
  displayName: "Apollo 11",
});
// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Transcribe the first few sentences of this document.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

视频

Python

import time

# Video clip (CC BY 3.0) from https://peach.blender.org/download/
myfile = genai.upload_file(media / "Big_Buck_Bunny.mp4")
print(f"{myfile=}")

# Videos need to be processed before you can use them.
while myfile.state.name == "PROCESSING":
    print("processing video...")
    time.sleep(5)
    myfile = genai.get_file(myfile.name)

model = genai.GenerativeModel("gemini-1.5-flash")
result = model.generate_content([myfile, "Describe this video clip"])
print(f"{result.text=}")

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
// import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/Big_Buck_Bunny.mp4`,
  {
    mimeType: "video/mp4",
    displayName: "Big Buck Bunny",
  },
);

let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
  process.stdout.write(".");
  // Sleep for 10 seconds
  await new Promise((resolve) => setTimeout(resolve, 10_000));
  // Fetch the file from the API again
  file = await fileManager.getFile(uploadResult.file.name);
}

if (file.state === FileState.FAILED) {
  throw new Error("Video processing failed.");
}

// View the response.
console.log(
  `Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`,
);

const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
  "Tell me about this video.",
  {
    fileData: {
      fileUri: uploadResult.file.uri,
      mimeType: uploadResult.file.mimeType,
    },
  },
]);
console.log(result.response.text());

响应正文

media.upload 的响应。

如果成功,响应正文将包含结构如下的数据:

田野
file object (File)

所创建文件的元数据。

JSON 表示法
{
  "file": {
    object (File)
  }
}

方法:files.get

获取给定 File 的元数据。

端点

<ph type="x-smartling-placeholder"></ph> 领取 https://generativelanguage.googleapis.com/v1beta/{name=files/*}

路径参数

name string

必需。要获取的 File 的名称。示例:files/abc-123 其格式为 files/{file}

请求正文

请求正文必须为空。

示例请求

Python

myfile = genai.upload_file(media / "poem.txt")
file_name = myfile.name
print(file_name)  # "files/*"

myfile = genai.get_file(file_name)
print(myfile)

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResponse = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);

// Get the previously uploaded file's metadata.
const getResponse = await fileManager.getFile(uploadResponse.file.name);

// View the response.
console.log(
  `Retrieved file ${getResponse.displayName} as ${getResponse.uri}`,
);

响应正文

如果成功,则响应正文包含一个 File 实例。

方法:files.list

列出发出请求的项目拥有的 File 的元数据。

端点

<ph type="x-smartling-placeholder"></ph> 领取 https://generativelanguage.googleapis.com/v1beta/files

查询参数

pageSize integer

可选。每页返回的 File 数量上限。如果未指定,则默认为 10。pageSize 的上限为 100。

pageToken string

可选。上一次 files.list 调用的页面令牌。

请求正文

请求正文必须为空。

示例请求

Python

print("My files:")
for f in genai.list_files():
    print("  ", f.name)

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const listFilesResponse = await fileManager.listFiles();

// View the response.
for (const file of listFilesResponse.files) {
  console.log(`name: ${file.name} | display name: ${file.displayName}`);
}

响应正文

files.list 的响应。

如果成功,响应正文将包含结构如下的数据:

田野
files[] object (File)

File 的列表。

nextPageToken string

可作为 pageToken 发送到后续 files.list 调用的令牌。

JSON 表示法
{
  "files": [
    {
      object (File)
    }
  ],
  "nextPageToken": string
}

方法:files.delete

删除 File

端点

<ph type="x-smartling-placeholder"></ph> 删除 https://generativelanguage.googleapis.com/v1beta/{name=files/*}

路径参数

name string

必需。要删除的 File 的名称。示例:files/abc-123 其格式为 files/{file}

请求正文

请求正文必须为空。

示例请求

Python

myfile = genai.upload_file(media / "poem.txt")

myfile.delete()

try:
    # Error.
    model = genai.GenerativeModel("gemini-1.5-flash")
    result = model.generate_content([myfile, "Describe this file."])
except google.api_core.exceptions.PermissionDenied:
    pass

Node.js

// Make sure to include these imports:
// import { GoogleAIFileManager } from "@google/generative-ai/server";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);

const uploadResult = await fileManager.uploadFile(
  `${mediaPath}/jetpack.jpg`,
  {
    mimeType: "image/jpeg",
    displayName: "Jetpack drawing",
  },
);

// Delete the file.
await fileManager.deleteFile(uploadResult.file.name);

console.log(`Deleted ${uploadResult.file.displayName}`);

响应正文

如果成功,则响应正文为空。

REST 资源:文件

资源:文件

上传到 API 的文件。

JSON 表示法
{
  "name": string,
  "displayName": string,
  "mimeType": string,
  "sizeBytes": string,
  "createTime": string,
  "updateTime": string,
  "expirationTime": string,
  "sha256Hash": string,
  "uri": string,
  "state": enum (State),
  "error": {
    object (Status)
  },

  // Union field metadata can be only one of the following:
  "videoMetadata": {
    object (VideoMetadata)
  }
  // End of list of possible types for union field metadata.
}
田野
name string

不可变。标识符。File 资源名称。ID(不包括“files/”前缀的名称)最多可包含 40 个字符,这些字符均为小写字母、数字或短划线 (-)。ID 不能以短划线开头或结尾。如果在创建时名称为空,系统会生成一个唯一名称。示例:files/123-456

displayName string

可选。直观易懂的 File 显示名。显示名称的长度不得超过 512 个字符(包括空格)。示例:“欢迎图片”

mimeType string

仅限输出。文件的 MIME 类型。

sizeBytes string (int64 format)

仅限输出。文件的大小(以字节为单位)。

createTime string (Timestamp format)

仅限输出。File 创建时的时间戳。

时间戳采用 RFC3339 世界协调时间(UTC,即“祖鲁时”)格式,精确到纳秒,最多九个小数位。示例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

updateTime string (Timestamp format)

仅限输出。上次更新 File 时的时间戳。

时间戳采用 RFC3339 世界协调时间(UTC,即“祖鲁时”)格式,精确到纳秒,最多九个小数位。示例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

expirationTime string (Timestamp format)

仅限输出。删除 File 时的时间戳。仅当 File 预定过期时设置。

时间戳采用 RFC3339 世界协调时间(UTC,即“祖鲁时”)格式,精确到纳秒,最多九个小数位。示例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

sha256Hash string (bytes format)

仅限输出。所上传字节的 SHA-256 哈希值。

使用 base64 编码的字符串。

uri string

仅限输出。File 的 URI。

state enum (State)

仅限输出。文件的处理状态。

error object (Status)

仅限输出。文件处理失败时显示的错误状态。

联合字段 metadata。文件的元数据。metadata 只能是下列其中一项:
videoMetadata object (VideoMetadata)

仅限输出。视频的元数据。

VideoMetadata

视频 File 的元数据。

JSON 表示法
{
  "videoDuration": string
}
田野
videoDuration string (Duration format)

视频的时长。

该时长以秒为单位,最多包含九个小数位,以“s”结尾。示例:"3.5s"

文件生命周期的状态。

枚举
STATE_UNSPECIFIED 默认值。如果省略州,系统就会使用此值。
PROCESSING 文件正在处理中,尚无法用于推理。
ACTIVE 文件已处理完毕,可用于推理。
FAILED 文件处理失败。

状态

Status 类型定义了适用于不同编程环境(包括 REST API 和 RPC API)的逻辑错误模型。此类型供 gRPC 使用。每条 Status 消息包含三部分数据:错误代码、错误消息和错误详细信息。

如需详细了解该错误模型及其使用方法,请参阅 API 设计指南

JSON 表示法
{
  "code": integer,
  "message": string,
  "details": [
    {
      "@type": string,
      field1: ...,
      ...
    }
  ]
}
田野
code integer

状态代码,应为 google.rpc.Code 的枚举值。

message string

面向开发者的错误消息(应采用英语)。任何向用户显示的错误消息都应进行本地化并通过 google.rpc.Status.details 字段发送,或者由客户端进行本地化。

details[] object

包含错误详细信息的消息列表。有一组通用的消息类型可供 API 使用。

可以包含任意类型字段的对象。附加字段 "@type" 包含用于标示相应类型的 URI。示例:{ "id": 1234, "@type": "types.example.com/standard/id" }