Using files

Phương thức: media.upload

Tạo File.

Điểm cuối

URI tải lên, đối với các yêu cầu tải nội dung nghe nhìn lên:
`post
https://generativelanguage.googleapis.com/upload/v1beta/files

  • URI siêu dữ liệu, đối với các yêu cầu chỉ dành cho siêu dữ liệu:
    POST https://generativelanguage.googleapis.com/v1beta/filesURL sử dụng cú pháp Chuyển mã gRPC.

Nội dung yêu cầu

Nội dung yêu cầu chứa dữ liệu có cấu trúc sau:

Số trường
file object (File)

Không bắt buộc. Siêu dữ liệu về tệp cần tạo.

Yêu cầu mẫu

Bài đăng có hình ảnh

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());

Âm thanh

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());

Văn bản

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());

Video

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());

Nội dung phản hồi

Câu trả lời cho media.upload.

Nếu thành công, phần nội dung phản hồi sẽ chứa dữ liệu có cấu trúc sau:

Số trường
file object (File)

Siêu dữ liệu cho tệp đã tạo.

Biểu diễn dưới dạng JSON
{
  "file": {
    object (File)
  }
}

Phương thức: files.get

Lấy siêu dữ liệu về File đã cho.

Điểm cuối

nhận https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Tham số đường dẫn

name string

Bắt buộc. Tên của File cần tải. Ví dụ: files/abc-123 Hàm này có dạng files/{file}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Yêu cầu mẫu

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}`,
);

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ chứa một phiên bản của File.

Phương thức: files.list

Liệt kê siêu dữ liệu của các File thuộc sở hữu của dự án yêu cầu.

Điểm cuối

nhận https://generativelanguage.googleapis.com/v1beta/files

Tham số truy vấn

pageSize integer

Không bắt buộc. Số giây tối đa File cần trả về trên mỗi trang. Nếu bạn không chỉ định, giá trị mặc định sẽ là 10. pageSize tối đa là 100.

pageToken string

Không bắt buộc. Mã thông báo trang từ lệnh gọi files.list trước đó.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Yêu cầu mẫu

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}`);
}

Nội dung phản hồi

Câu trả lời cho files.list.

Nếu thành công, phần nội dung phản hồi sẽ chứa dữ liệu có cấu trúc sau:

Số trường
files[] object (File)

Danh sách các File.

nextPageToken string

Mã thông báo có thể được gửi dưới dạng pageToken trong lệnh gọi files.list tiếp theo.

Biểu diễn dưới dạng JSON
{
  "files": [
    {
      object (File)
    }
  ],
  "nextPageToken": string
}

Phương thức: files.delete

Xoá File.

Điểm cuối

xoá https://generativelanguage.googleapis.com/v1beta/{name=files/*}

Tham số đường dẫn

name string

Bắt buộc. Tên của File cần xoá. Ví dụ: files/abc-123 Hàm này có dạng files/{file}.

Nội dung yêu cầu

Nội dung yêu cầu phải trống.

Yêu cầu mẫu

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}`);

Nội dung phản hồi

Nếu thành công, nội dung phản hồi sẽ trống.

Tài nguyên REST: tệp

Tài nguyên: Tệp

Một tệp đã tải lên API.

Biểu diễn dưới dạng 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.
}
Số trường
name string

Bất biến. Giá trị nhận dạng. Tên tài nguyên File. Mã nhận dạng (tên không bao gồm tiền tố "files/") có thể chứa tối đa 40 ký tự là chữ và số viết thường hoặc dấu gạch ngang (-). Mã nhận dạng không được bắt đầu hoặc kết thúc bằng dấu gạch ngang. Nếu tên trống khi tạo, một tên duy nhất sẽ được tạo. Ví dụ: files/123-456

displayName string

Không bắt buộc. Tên hiển thị mà con người có thể đọc được của File. Tên hiển thị không được dài quá 512 ký tự, kể cả dấu cách. Ví dụ: "Hình ảnh chào mừng"

mimeType string

Chỉ có đầu ra. Loại MIME của tệp.

sizeBytes string (int64 format)

Chỉ có đầu ra. Kích thước của tệp tính bằng byte.

createTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi File được tạo.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

updateTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian của lần cập nhật File gần đây nhất.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

expirationTime string (Timestamp format)

Chỉ có đầu ra. Dấu thời gian khi File sẽ bị xoá. Chỉ được đặt nếu File được lên lịch để hết hạn.

Dấu thời gian theo múi giờ "Zulu" RFC3339 (giờ UTC) với độ phân giải nano giây và lên đến 9 chữ số phân số. Ví dụ: "2014-10-02T15:01:23Z""2014-10-02T15:01:23.045123456Z".

sha256Hash string (bytes format)

Chỉ có đầu ra. Hàm băm SHA-256 của các byte đã tải lên.

Chuỗi được mã hoá base64.

uri string

Chỉ có đầu ra. URI của File.

state enum (State)

Chỉ có đầu ra. Trạng thái xử lý của Tệp.

error object (Status)

Chỉ có đầu ra. Trạng thái lỗi nếu Xử lý tệp không thành công.

Trường kết hợp metadata. Siêu dữ liệu cho tệp. metadata chỉ có thể là một trong những trạng thái sau đây:
videoMetadata object (VideoMetadata)

Chỉ có đầu ra. Siêu dữ liệu của video.

VideoMetadata

Siêu dữ liệu của video File.

Biểu diễn dưới dạng JSON
{
  "videoDuration": string
}
Số trường
videoDuration string (Duration format)

Thời lượng của video.

Thời lượng tính bằng giây với tối đa 9 chữ số phân số, kết thúc bằng "s". Ví dụ: "3.5s".

Tiểu bang

Các trạng thái trong vòng đời của một Tệp.

Enum
STATE_UNSPECIFIED Giá trị mặc định. Giá trị này được dùng nếu trạng thái bị bỏ qua.
PROCESSING Tệp đang được xử lý và chưa thể dùng để suy luận.
ACTIVE Tệp được xử lý và có sẵn để suy luận.
FAILED Không xử lý được tệp.

Trạng thái

Loại Status xác định mô hình lỗi logic phù hợp với nhiều môi trường lập trình, bao gồm cả API REST và API RPC. Hàm này được gRPC sử dụng. Mỗi thông báo Status chứa 3 phần dữ liệu: mã lỗi, thông báo lỗi và thông tin chi tiết về lỗi.

Bạn có thể tìm hiểu thêm về mô hình lỗi này cũng như cách xử lý trong Hướng dẫn thiết kế API.

Biểu diễn dưới dạng JSON
{
  "code": integer,
  "message": string,
  "details": [
    {
      "@type": string,
      field1: ...,
      ...
    }
  ]
}
Số trường
code integer

Mã trạng thái, phải là một giá trị enum của google.rpc.Code.

message string

Thông báo lỗi dành cho nhà phát triển, phải bằng tiếng Anh. Mọi thông báo lỗi dành cho người dùng đều phải được bản địa hoá và gửi trong trường google.rpc.Status.details hoặc để ứng dụng bản địa hoá.

details[] object

Danh sách các thông báo chứa thông tin chi tiết về lỗi. Có một nhóm loại thông báo phổ biến để API sử dụng.

Một đối tượng có chứa các trường thuộc loại tuỳ ý. Trường bổ sung "@type" chứa URI xác định kiểu. Ví dụ: { "id": 1234, "@type": "types.example.com/standard/id" }.