Using files

שיטה: media.upload

ייווצר File.

נקודת קצה

URI להעלאה, לבקשות להעלאת מדיה:
`post
https://generativelanguage.googleapis.com/upload/v1beta/files

  • URI של מטא-נתונים, לבקשות למטא-נתונים בלבד:
    POST https://generativelanguage.googleapis.com/v1beta/filesכתובת ה-URL משתמשת בתחביר המרת קידוד של 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}`);

גוף התשובה

אם הביצוע יהיה תקין, גוף התגובה יהיה ריק.

Resource 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' בפורמט של רזולוציה של ננו-שנייה ועד תשע ספרות עשרוניות. דוגמאות: "2014-10-02T15:01:23Z" ו-"2014-10-02T15:01:23.045123456Z".

updateTime string (Timestamp format)

פלט בלבד. חותמת הזמן של מועד העדכון האחרון של File.

חותמת זמן ב-RFC3339 UTC 'Zulu' בפורמט של רזולוציה של ננו-שנייה ועד תשע ספרות עשרוניות. דוגמאות: "2014-10-02T15:01:23Z" ו-"2014-10-02T15:01:23.045123456Z".

expirationTime string (Timestamp format)

פלט בלבד. חותמת הזמן של המועד שבו File יימחק. מוגדר רק אם התוקף של File עומד לפוג.

חותמת זמן ב-RFC3339 UTC 'Zulu' בפורמט של רזולוציה של ננו-שנייה ועד תשע ספרות עשרוניות. דוגמאות: "2014-10-02T15:01:23Z" ו-"2014-10-02T15:01:23.045123456Z".

sha256Hash string (bytes format)

פלט בלבד. גיבוב SHA-256 של הבייטים שהועלו.

מחרוזת בקידוד base64.

uri string

פלט בלבד. ה-URI של File.

state enum (State)

פלט בלבד. מצב הקובץ בתהליך עיבוד.

error object (Status)

פלט בלבד. סטטוס השגיאה אם עיבוד הקובץ נכשל.

שדה איחוד metadata. מטא-נתונים של הקובץ. metadata יכול להיות רק אחת מהאפשרויות הבאות:
videoMetadata object (VideoMetadata)

פלט בלבד. מטא-נתונים של סרטון.

VideoMetadata

מטא-נתונים של סרטון File.

ייצוג JSON
{
  "videoDuration": string
}
שדות
videoDuration string (Duration format)

משך הסרטון.

משך זמן בשניות עם עד תשע ספרות עשרוניות, שמסתיים ב-'s'. לדוגמה: "3.5s".

מדינה

מצבים במחזור החיים של קובץ.

טיפוסים בני מנייה (enum)
STATE_UNSPECIFIED ערך ברירת המחדל. הערך הזה משמש אם לא מציינים את המצב.
PROCESSING הקובץ בתהליך עיבוד ואי אפשר עדיין להשתמש בו לצורך הסקת מסקנות.
ACTIVE הקובץ מעובד וזמין להסקת מסקנות.
FAILED עיבוד הקובץ נכשל.

סטטוס

הסוג Status מגדיר מודל שגיאות לוגי שמתאים לסביבות תכנות שונות, כולל ממשקי API ל-REST וממשקי API ל-RPC. הוא נמצא בשימוש של gRPC. כל הודעת Status מכילה שלושה נתונים: קוד שגיאה, הודעת שגיאה ופרטי שגיאה.

במדריך לעיצוב 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" }.