Die Gemini-API wächst weiter. Am 5. August 2024 habe ich GeminiWithFiles weitgehend auf v2.xx aktualisiert. Mit diesem großen Update wird die Version von v1 auf v2 geändert.
Wenn Sie GeminiWithFiles v1.xx verwenden möchten, lesen Sie bitte hier.
Dies ist eine Google Apps Script-Bibliothek für die Gemini API mit Dateien.
Eine neue Google Apps Script-Bibliothek namens GeminiWithFiles vereinfacht die Verwendung von Gemini, einem großen Sprachmodell, um unstrukturierte Daten wie Bilder und PDFs zu verarbeiten. GeminiWithFiles kann Dateien hochladen, Inhalte generieren und Beschreibungen aus mehreren Bildern gleichzeitig erstellen. Dies reduziert den Arbeitsaufwand erheblich und erweitert die Einsatzmöglichkeiten von Gemini.
Kürzlich hat Gemini, ein großes Sprachmodell von Google AI, neue Möglichkeiten für verschiedene Aufgaben eröffnet, indem es die Verwendung unstrukturierter Daten als strukturierte Daten ermöglicht. Dies ist besonders wichtig, da eine große Menge an Informationen in unstrukturierten Formaten wie Textdokumenten, Bildern und Videos vorliegt.
Die kürzlich veröffentlichte Gemini 1.5 API erweitert diese Funktionen erheblich. Es kann Inhalte mit bis zu 1 Million Token generieren, eine erhebliche Steigerung im Vergleich zu früheren Versionen. Darüber hinaus kann Gemini 1.5 jetzt bis zu 3.000 Bilddateien verarbeiten und übertrifft damit die 16-Bilder-Grenze von Gemini 1.0 bei weitem. Ref
Obwohl Gemini nicht direkt mit Google Drive-Formaten wie Docs, Sheets und Slides arbeiten kann, gibt es Workarounds. Im aktuellen Stadium können PDF-Daten direkt mit der Gemini API verarbeitet werden. Auf diese Weise werden diese Google Docs-Dateien in PDF konvertiert und mit der Gemini-API verwendet. Ref
In diesem Bericht wird eine neue Google Apps Script-Bibliothek namens „GeminiWithFiles“ vorgestellt, die diesen Prozess vereinfacht. GeminiWithFiles ermöglicht Benutzern das einfache Hochladen von Dateien und das Generieren von Inhalten mithilfe der leistungsstarken Funktionen von Gemini. Es ermöglicht außerdem die effiziente Erstellung von Beschreibungen aus mehreren Bildern mit einem einzigen API-Aufruf, wodurch der Arbeitsaufwand im Vergleich zur Verarbeitung jedes Bildes einzeln, wie in meinem vorherigen Bericht gezeigt, erheblich reduziert wird. Ref
Durch die Rationalisierung des Prozesses und die Erweiterung der Funktionen verspricht GeminiWithFiles verschiedene Anwendungsfälle in verschiedenen Domänen. Dieser Bericht dient als erweiterter Ansatz zum vorherigen und zielt darauf ab, die Prozesskosten weiter zu senken und die Effizienz bei der Arbeit mit Gemini und unstrukturierten Daten zu verbessern.
Ich habe diese Bibliothek basierend auf den folgenden Berichten erstellt.
Mit dieser Bibliothek GeminiWithFiles können Sie über eine benutzerfreundliche API mit Gemini, einer leistungsstarken Dokumentenverarbeitungs- und Verwaltungsplattform, interagieren. Folgendes können Sie mit dieser Bibliothek erreichen:
Dateiverwaltung:
Inhalt hochladen:
Chat-Verlaufsverwaltung:
Inhaltsgenerierung:
Ausgabespezifikation:
Geben Sie das gewünschte Ausgabeformat für die von der Gemini-API generierten Ergebnisse an.
Mit Hilfe von response_mime_type
und dem JSON-Schema wird das Ausgabeformat gesteuert. Ref
Um dieses Skript zu testen, führen Sie bitte die folgenden Schritte aus.
Bitte greifen Sie auf https://makersuite.google.com/app/apikey zu und erstellen Sie Ihren API-Schlüssel. Bitte aktivieren Sie zu diesem Zeitpunkt die Generative Language API in der API-Konsole. Dieser API-Schlüssel wird für dieses Beispielskript verwendet.
Dieses offizielle Dokument ist ebenfalls einsehbar. Ref.
Bitte erstellen Sie ein eigenständiges Google Apps Script-Projekt. Natürlich kann dieses Skript auch mit dem Container-gebundenen Skript verwendet werden.
Und öffnen Sie bitte den Skripteditor des Google Apps Script-Projekts.
Es gibt zwei Muster für die Verwendung von GeminiWithFiles.
Wenn Sie diese Bibliothek als Google Apps Script-Bibliothek verwenden, installieren Sie die Bibliothek bitte wie folgt in Ihrem Google Apps Script-Projekt.
Erstellen Sie ein Google Apps Script-Projekt. Oder öffnen Sie Ihr Google Apps Script-Projekt.
Installieren Sie diese Bibliothek.
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
Wenn Sie diese Bibliothek in Ihrem eigenen Google Apps Script-Projekt verwenden, kopieren Sie bitte das Skript „classGeminiWithFiles.js“ und fügen Sie es in Ihr Google Apps Script-Projekt ein. Dadurch kann das Skript verwendet werden.
„main.js“ wird für die Google Apps Script-Bibliothek verwendet. In diesem Muster ist es also nicht erforderlich, es zu verwenden.
Diese Bibliothek verwendet die folgenden zwei Bereiche.
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/drive
Wenn Sie das Zugriffstoken verwenden möchten, verknüpfen Sie bitte das Google Cloud Platform Project mit dem Google Apps Script Project. Und fügen Sie bitte den folgenden Bereich hinzu.
https://www.googleapis.com/auth/generative-language
Außerdem können Sie das offizielle Dokument der Gemini API unter https://ai.google.dev/api/rest einsehen.
Methoden | Beschreibung |
---|---|
setFileIds(fileIds, asImage = false) | Datei-IDs festlegen. |
setBlobs(Blobs) | Blobs setzen. |
withUploadedFilesByGenerateContent(fileList = []) | Erstellen Sie ein Objekt zur Verwendung der Methode „generateContent“. |
uploadFiles(n = 50) | Laden Sie Dateien auf Gemini hoch. |
getFileList() | Dateiliste in Gemini abrufen. |
deleteFiles(names, n = 50) | Löschen Sie Dateien von Gemini. |
generierenContent(Objekt) | Hauptmethode. Generieren Sie Inhalte mit der Gemini-API. |
setFileIdsOrUrlsWithResumableUpload(object) | Dateien über 50 MB können auf Gemini hochgeladen werden. |
Wenn Sie GeminiWithFiles als Bibliothek in Ihrem Google Apps Script-Projekt installieren, verwenden Sie bitte das folgende Skript.
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
oder
Wenn Sie das Skript der Klasse GeminiWithFiles direkt kopieren und in Ihr Google Apps-Skriptprojekt einfügen, verwenden Sie bitte das folgende Skript.
const g = new GeminiWithFiles ( object ) ;
Der Wert des object
ist wie folgt.
{Object} object API key or access token for using Gemini API.
{String} object.apiKey API key.
{String} object.accessToken Access token.
{String} object.model Model. Default is "models/gemini-1.5-pro-latest".
{String} object.version Version of API. Default is "v1beta".
{Boolean} object.doCountToken Default is false. If this is true, when Gemini API is requested, the token of request is shown in the log.
{Array} object.history History for continuing chat.
{Array} object.functions If you want to give the custom functions, please use this.
{String} object.response_mime_type In the current stage, only "application/json" can be used.
{String} object.responseMimeType In the current stage, only "application/json" can be used.
{Object} object.response_schema JSON schema for controlling the output format.
{Object} object.responseSchema JSON schema for controlling the output format.
{Number} object.temperature Control the randomness of the output.
{Object} object.systemInstruction Ref: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini.
{Boolean} object.exportTotalTokens When this is true, the total tokens are exported as the result value. At that time, the generated content and the total tokens are returned as an object.
{Boolean} object.exportRawData The default value is false. When this is true, the raw data returned from Gemini API is returned.
{Object} object.toolConfig The default is null. If you want to directly give the object of "toolConfig", please use this.
{Array} object.tools The default value is null. For example, when you want to use "codeExecution", please set `tools: [{ codeExecution: {}}]`.
{PropertiesService.Properties} object.propertiesService PropertiesService.getScriptProperties()
{Boolean} object.resumableUploadAsNewUpload When you want to upload the data with the resumable upload as new upload, please set this as true. The default is false.
Wenn Sie response_mime_type
verwenden möchten, geben Sie bitte jsonSchema
an die Methode „generateContent“ an. In der aktuellen Phase kann nur "application/json"
für response_mime_type
“ verwendet werden.
Wenn Sie systemInstruction
verwenden möchten, bestätigen Sie bitte das offizielle Dokument Ref.
Gemini 1.5 Flash Latest ( models/gemini-1.5-flash-latest
) wird als Standardmodell verwendet. Wenn Sie Gemini 1.5 Pro Latest ( models/gemini-1.5-pro-latest
) verwenden möchten, verwenden Sie es bitte wie const g = GeminiWithFiles.geminiWithFiles({ apiKey, model: "models/gemini-1.5-pro-latest" })
.
In der aktuellen Phase wird bei Verwendung von response_schema
automatisch response_mime_type: "application/json"
verwendet.
Datei-IDs festlegen. Die Dateien der Datei-IDs werden auf Gemini hochgeladen.
In diesem Fall wird async/await in der Funktion verwendet.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const folderId = "###" ; // Please set your folder ID including images.
let fileIds = [ ] ;
const files = DriveApp . getFolderById ( folderId ) . getFiles ( ) ;
while ( files . hasNext ( ) ) {
const file = files . next ( ) ;
fileIds . push ( file . getId ( ) ) ;
}
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . setFileIds ( fileIds , false ) . uploadFiles ( ) ;
console . log ( res ) ;
}
setFileIds
sind String[] (die Datei-IDs auf Google Drive) bzw. der boolesche Wert. Wenn das 2. Argument falsch ist, werden die eingegebenen Dateien mit Datei-IDs als Rohdaten hochgeladen. Wenn das 2. Argument wahr ist, werden die eingegebenen Dateien mit Datei-IDs in Bilddaten umgewandelt und hochgeladen. Der Standardwert des 2. Arguments ist falsch.false
wie setFileIds(fileIds, false)
verwenden. Blobs setzen. Die Blobs werden auf Gemini hochgeladen.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const folderId = "###" ; // Please set your folder ID including images.
const blobs = [ ] ;
const files = DriveApp . getFolderById ( folderId ) . getFiles ( ) ;
while ( files . hasNext ( ) ) {
blobs . push ( files . next ( ) . getBlob ( ) ) ;
}
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . setBlobs ( blobs ) . uploadFiles ( ) ;
console . log ( res ) ;
}
setBlobs
ist Blob[].Erstellen Sie ein Objekt zur Verwendung der Methode „generateContent“.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const q = "###" ; // Please set your question.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const fileList = g . getFileList ( ) ;
const res = g
. withUploadedFilesByGenerateContent ( fileList )
. generateContent ( { q } ) ;
console . log ( res ) ;
}
withUploadedFilesByGenerateContent
hat nur ein Argument. Das ist der Wert der getFileList-Methode. Sie können die tatsächlichen Werte sehen, nachdem Sie Dateien hochgeladen haben.Laden Sie Dateien auf Gemini hoch. Die Dateien werden mithilfe der eingegebenen Datei-IDs oder Blobs auf Gemini hochgeladen.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const fileIds = [ "###fileId1###" , "###fileId2###" , , , ] ; // Please set your file IDs in this array.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . setFileIds ( fileIds , false ) . uploadFiles ( ) ;
console . log ( res ) ;
}
In diesem Skript werden die Dateien von fileIds
mit den Rohdaten nach Gemini hochgeladen. Wenn setFileIds(fileIds, false)
in setFileIds(fileIds, true)
geändert wird, werden die Dateien als Bilder auf Gemini hochgeladen.
Wenn Sie Blob direkt verwenden, können Sie das folgende Skript verwenden.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const fileIds = [ "###fileId1###" , "###fileId2###" , , , ] ; // Please set your file IDs in this array.
const blobs = fileIds . map ( id => DriveApp . getFileById ( id ) . getBlob ( ) ) ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . setBlobs ( blobs ) . uploadFiles ( ) ;
console . log ( res ) ;
}
Dateiliste in Gemini abrufen.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . getFileList ( ) ;
console . log ( res ) ;
}
Löschen Sie Dateien von Gemini.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const names = g . getFileList ( ) . map ( ( { name } ) => name ) ;
if ( names . length == 0 ) return ;
g . deleteFiles ( names ) ;
console . log ( ` ${ names . length } files were deleted.` ) ;
}
Hauptmethode. Generieren Sie Inhalte mit der Gemini-API. Weitere Beispielskripte finden Sie im folgenden Abschnitt „Beispielskripte“.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . generateContent ( { q : "What is Google Apps Script?" } ) ;
console . log ( res ) ;
}
In diesem Skript wird der Inhalt mit dem Funktionsaufruf generiert.
Wenn Sie response_mime_type
verwenden möchten, geben Sie jsonSchema
wie folgt an die Methode „generateContent“ weiter. In diesem Fall kann diese Bibliothek ein gültiges Objekt zurückgeben, indem sie nur das JSON-Schema angibt. Die detaillierten Informationen zu response_mime_type
finden Sie auch in meinem Bericht.
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( {
apiKey ,
response_mime_type : "application/json" ,
} ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, response_mime_type: "application/json" }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const jsonSchema = {
title : "5 popular cookie recipes" ,
description : "List 5 popular cookie recipes." ,
type : "array" ,
items : {
type : "object" ,
properties : {
recipe_name : {
description : "Names of recipe." ,
type : "string" ,
} ,
} ,
} ,
} ;
const res = g . generateContent ( { jsonSchema } ) ;
console . log ( res ) ;
}
Wenn dieses Skript ausgeführt wird, wird das folgende Ergebnis erhalten.
[
{ "recipe_name" : " Chocolate Chip Cookies " },
{ "recipe_name" : " Peanut Butter Cookies " },
{ "recipe_name" : " Oatmeal Cookies " },
{ "recipe_name" : " Sugar Cookies " },
{ "recipe_name" : " Snickerdoodle Cookies " }
]
Mit dieser Methode können Dateien über 50 MB hochgeladen werden.
Ab v2.xx ist dies möglich. Dies ist aus Ref und Ref.
Wenn Sie diese Methode ab Version 2.0.3 verwenden, fügen Sie bitte propertiesService: PropertiesService.getScriptProperties()
wie folgt in das ursprüngliche Objekt ein. Denn wenn PropertiesService.getScriptProperties()
in der Bibliothek verwendet wird, werden die Werte in die Bibliothek gestellt. Als ich Ref und Ref erstellt habe, ging ich davon aus, dass das Skript durch Kopieren und Einfügen anstelle der Bibliothek verwendet wird. Also habe ich PropertiesService.getScriptProperties()
in das Skript eingefügt. Mir ist jedoch aufgefallen, dass bei Verwendung mit GeminiWithFiles jeder Benutzer PropertiesService.getScriptProperties()
verwenden muss. Also habe ich das geändert.
Das Beispielskript sieht wie folgt aus.
function myFunction ( ) {
// This URL is from https://github.com/google/generative-ai-docs/blob/main/site/en/gemini-api/docs/prompting_with_media.ipynb
const url = "https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" ; // 64,657,027 bytes
const apiKey = "###" ; // Please set your API key.
const q = "Description this video." ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , propertiesService : PropertiesService . getScriptProperties ( ) } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, propertiesService: PropertiesService.getScriptProperties() }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const fileList = g . setFileIdsOrUrlsWithResumableUpload ( [ { url } ] ) . uploadFiles ( ) ;
Utilities . sleep ( 10000 ) ; // This might be required to be used because the state of the uploaded file might not be active.
const res = g . withUploadedFilesByGenerateContent ( fileList ) . generateContent ( { q } ) ;
console . log ( res ) ;
}
Wenn dieses Skript ausgeführt wird, wird im Protokoll das folgende Protokoll angezeigt.
- Get metadata
- Calculate chunks
- Get location
- Download and upload data.
- Now... 1/4
- Start downloading data with 0-16777215
- Finished downloading data with 0-16777215
- Start uploading data with 0-16777215
- Finished uploading data with 0-16777215
- Upload the next chunk.
- Now... 2/4
- Start downloading data with 16777216-33554431
- Finished downloading data with 16777216-33554431
- Start uploading data with 16777216-33554431
- Finished uploading data with 16777216-33554431
- Upload the next chunk.
- Now... 3/4
- Start downloading data with 33554432-50331647
- Finished downloading data with 33554432-50331647
- Start uploading data with 33554432-50331647
- Finished uploading data with 33554432-50331647
- Upload the next chunk.
- Now... 4/4
- Start downloading data with 50331648-64657026
- Finished downloading data with 50331648-64657026
- Start uploading data with 50331648-64657026
- Finished uploading data with 50331648-64657026
- Done.
- Now, the state of the uploaded files "url@https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4$page@1$maxPage@1" is not active. So, it will wait until it is active. Please wait for 10 seconds. Retry (1/3)
- 1 uploaded files are used with generateCotent.
- The video is a cartoon that shows a large, white rabbit in a field. The rabbit is shown waking up from a nap and then is seen eating an apple. After eating the apple, the rabbit is approached by a bird. The rabbit is scared of the bird and tries to hide from it. The bird flies away. The rabbit is seen smiling and then a squirrel flies toward the rabbit. The squirrel is startled by the rabbit and flies away. The rabbit is then seen catching another squirrel with its vine and the scene ends with a close-up of the rabbit's face.
Wenn Ihre Datei groß ist und der Status der hochgeladenen Datei immer noch nicht „AKTIV“ ist, testen Sie bitte das folgende Skript.
function myFunction ( ) {
// This URL is from https://github.com/google/generative-ai-docs/blob/main/site/en/gemini-api/docs/prompting_with_media.ipynb
const url = "https://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_320x180.mp4" ; // 64,657,027 bytes
const apiKey = "###" ; // Please set your API key.
const q = "Description this video." ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , propertiesService : PropertiesService . getScriptProperties ( ) } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, propertiesService: PropertiesService.getScriptProperties() }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const fileList = g . setFileIdsOrUrlsWithResumableUpload ( [ { url } ] ) . uploadFiles ( ) ;
console . log ( JSON . stringify ( fileList ) ) ;
// Please copy the value of "fileList".
}
Dadurch kann die Datei hochgeladen werden. Und Sie können die hochgeladene Datei verwenden, nachdem sie genügend Zeit gewartet hat, um den Status in „AKTIV“ zu ändern. Die hochgeladene Datei kann wie folgt verwendet werden.