Using files

เมธอด: media.upload

สร้าง File

ปลายทาง

อัปโหลด URI สำหรับคำขออัปโหลดสื่อ:
`post
https://generativelanguage.googleapis.com/upload/v1beta/files

  • URI ของข้อมูลเมตา สำหรับคำขอที่มีข้อมูลเมตาเท่านั้น:
    POST https://generativelanguage.googleapis.com/v1beta/filesURL ใช้ไวยากรณ์การแปลง 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 วินาทีที่จะแสดงผลต่อ 1 หน้า หากไม่ระบุ ค่าเริ่มต้นจะเป็น 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: ไฟล์

ทรัพยากร: ไฟล์

ไฟล์ที่อัปโหลดไปยัง 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 รหัส (ชื่อที่ไม่รวมคำนำหน้า "files/") มีอักขระได้สูงสุด 40 ตัวซึ่งเป็นอักขระที่เป็นตัวอักษรพิมพ์เล็กและตัวเลขคละกันหรือขีดกลาง (-) รหัสต้องไม่ขึ้นต้นหรือลงท้ายด้วยขีดกลาง หากไม่มีชื่อปรากฏในการสร้าง ระบบจะสร้างชื่อที่ไม่ซ้ำกันขึ้นมา ตัวอย่าง: 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 ของไบต์ที่อัปโหลด

สตริงที่เข้ารหัสฐาน 64

uri string

เอาต์พุตเท่านั้น URI ของ File

state enum (State)

เอาต์พุตเท่านั้น สถานะการประมวลผลไฟล์

error object (Status)

เอาต์พุตเท่านั้น สถานะข้อผิดพลาดหากประมวลผลไฟล์ไม่สำเร็จ

ช่องการรวม metadata ข้อมูลเมตาสำหรับไฟล์ metadata ต้องเป็นค่าใดค่าหนึ่งต่อไปนี้
videoMetadata object (VideoMetadata)

เอาต์พุตเท่านั้น ข้อมูลเมตาสำหรับวิดีโอ

VideoMetadata

ข้อมูลเมตาสำหรับวิดีโอ File

การแสดง JSON
{
  "videoDuration": string
}
ช่อง
videoDuration string (Duration format)

ระยะเวลาของวิดีโอ

ระยะเวลาเป็นวินาทีโดยมีเลขเศษส่วนไม่เกิน 9 หลัก ลงท้ายด้วย "s" ตัวอย่างเช่น "3.5s"

รัฐ

สถานะสำหรับวงจรของไฟล์

Enum
STATE_UNSPECIFIED ค่าเริ่มต้น ระบบจะใช้ค่านี้หากเว้นสถานะไว้
PROCESSING ระบบกำลังประมวลผลไฟล์และยังใช้สำหรับการอนุมานไม่ได้
ACTIVE ไฟล์ได้รับการประมวลผลและพร้อมสำหรับการอนุมาน
FAILED ประมวลผลไฟล์ไม่สำเร็จ

สถานะ

ประเภท Status กำหนดโมเดลข้อผิดพลาดเชิงตรรกะที่เหมาะกับสภาพแวดล้อมในการเขียนโปรแกรมแบบต่างๆ ซึ่งรวมถึง REST API และ RPC API gRPC ใช้ ข้อความ Status แต่ละข้อความจะมีข้อมูล 3 อย่าง ได้แก่ รหัสข้อผิดพลาด ข้อความแสดงข้อผิดพลาด และรายละเอียดข้อผิดพลาด

คุณสามารถดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบข้อผิดพลาดนี้และวิธีใช้โมเดลดังกล่าวได้ในคู่มือการออกแบบ API

การแสดง JSON
{
  "code": integer,
  "message": string,
  "details": [
    {
      "@type": string,
      field1: ...,
      ...
    }
  ]
}
ช่อง
code integer

รหัสสถานะ ซึ่งควรเป็นค่า enum ของ google.rpc.Code

message string

ข้อความแสดงข้อผิดพลาดที่นักพัฒนาแอปเห็น ซึ่งควรเป็นภาษาอังกฤษ ข้อความแสดงข้อผิดพลาดที่แสดงต่อผู้ใช้ควรแปลและส่งในช่อง google.rpc.Status.details หรือแปลโดยไคลเอ็นต์

details[] object

รายการข้อความที่มีรายละเอียดข้อผิดพลาด API จะใช้ชุดประเภทข้อความที่พบได้ทั่วไป

ออบเจ็กต์ที่มีช่องประเภทที่กำหนดเอง ช่องเพิ่มเติม "@type" จะมี URI ที่ระบุประเภท ตัวอย่างเช่น { "id": 1234, "@type": "types.example.com/standard/id" }