Using files

方法:media.upload

可建立 File

端點

上傳 URI (適用於媒體上傳要求):
`post
https://generativelanguage.googleapis.com/upload/v1beta/files

  • 適用於純中繼資料要求的中繼資料 URI:
    POST https://generativelanguage.googleapis.com/v1beta/files這個網址使用 gRPC 轉碼語法。

要求主體

要求主體的資料會採用以下結構:

欄位
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 的中繼資料。

端點

取得 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 中繼資料。

端點

取得 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

端點

刪除 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 資源:files

資源:檔案

上傳至 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

不可變動。ID。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 世界標準時間「Zulu」的時間戳記格式,解析度為奈秒,且最多 9 個小數位數。範例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

updateTime string (Timestamp format)

僅供輸出。上次更新 File 的時間戳記。

RFC3339 世界標準時間「Zulu」的時間戳記格式,解析度為奈秒,且最多 9 個小數位數。範例:"2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

expirationTime string (Timestamp format)

僅供輸出。File 遭到刪除的時間戳記。只有在 File 排定的到期時,才需要設定。

RFC3339 世界標準時間「Zulu」的時間戳記格式,解析度為奈秒,且最多 9 個小數位數。範例:"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)

影片的時間長度。

持續時間以秒為單位,最多 9 個小數位數,結尾為「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" }.