Using files

メソッド: media.upload

File を作成します。

エンドポイント

<ph type="x-smartling-placeholder"></ph> <ph type="x-smartling-placeholder"></ph> アップロード URI、メディア アップロード リクエストの場合:
`post
をご覧ください。 https://generativelanguage.googleapis.com/upload/v1beta/files

  • メタデータ URI(メタデータのみのリクエストの場合):
    POST https://generativelanguage.googleapis.com/v1beta/filesこの URL は gRPC Transcoding 構文を使用します。

リクエスト本文

リクエストの本文には、次の構造のデータが含まれます。

<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 へのレスポンス。

成功した場合、レスポンスの本文には次の構造のデータが含まれます。

<ph type="x-smartling-placeholder">
</ph> フィールド
file object (File)

作成されたファイルのメタデータ。

JSON 表現
{
  "file": {
    object (File)
  }
}

メソッド: files.get

指定された File のメタデータを取得します。

エンドポイント

<ph type="x-smartling-placeholder"></ph> <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> <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 へのレスポンス。

成功した場合、レスポンスの本文には次の構造のデータが含まれます。

<ph type="x-smartling-placeholder">
</ph> フィールド
files[] object (File)

File のリスト。

nextPageToken string

後続の files.list 呼び出しに pageToken として送信できるトークン。

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

メソッド: files.delete

File を削除します。

エンドポイント

<ph type="x-smartling-placeholder"></ph> <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 リソース: ファイル

リソース: File

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.
}
<ph type="x-smartling-placeholder">
</ph> フィールド
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 UTC「Zulu」形式のタイムスタンプ。精度はナノ秒まで、小数点以下は最大 9 桁。例: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

updateTime string (Timestamp format)

出力専用。File が最後に更新されたときのタイムスタンプ。

RFC3339 UTC「Zulu」形式のタイムスタンプ。精度はナノ秒まで、小数点以下は最大 9 桁。例: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z"

expirationTime string (Timestamp format)

出力専用。File が削除されるときのタイムスタンプ。File の有効期限が設定されている場合にのみ設定します。

RFC3339 UTC「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
}
<ph type="x-smartling-placeholder">
</ph> フィールド
videoDuration string (Duration format)

動画の再生時間。

s で終わる小数 9 桁までの秒単位の期間。例: "3.5s"

ファイルのライフサイクルの状態。

列挙型
STATE_UNSPECIFIED デフォルト値。この値は、州が省略されている場合に使用されます。
PROCESSING ファイルは処理中のため、まだ推論に使用できません。
ACTIVE ファイルが処理され、推論に使用できるようになりました。
FAILED ファイルの処理に失敗しました。

ステータス

Status 型は、REST API や RPC API など、さまざまなプログラミング環境に適した論理エラーモデルを定義します。gRPC により使用されます。各 Status メッセージには、エラーコード、エラー メッセージ、エラーの詳細という 3 種類のデータが含まれます。

このエラーモデルと操作方法について詳しくは、API 設計ガイドをご覧ください。

JSON 表現
{
  "code": integer,
  "message": string,
  "details": [
    {
      "@type": string,
      field1: ...,
      ...
    }
  ]
}
<ph type="x-smartling-placeholder">
</ph> フィールド
code integer

ステータス コード。google.rpc.Code の列挙値である必要があります。

message string

デベロッパー向けのエラー メッセージ。英語で記述します。ユーザー向けのエラー メッセージは、ローカライズして google.rpc.Status.details フィールドで送信するか、クライアントでローカライズする必要があります。

details[] object

エラーの詳細を保持するメッセージのリスト。API が使用する共通のメッセージ タイプのセットがあります。

任意のデータ型のフィールドを含むオブジェクト。型を識別する URI を含むフィールド "@type" を追加できます。例: { "id": 1234, "@type": "types.example.com/standard/id" }