La API Gemini sigue creciendo. El 5 de agosto de 2024, actualicé en gran medida GeminiWithFiles a v2.xx. Con esta gran actualización, la versión cambia de v1 a v2.
Si desea utilizar GeminiWithFiles v1.xx, consulte aquí.
Esta es una biblioteca de Google Apps Script para la API de Gemini con archivos.
Una nueva biblioteca de Google Apps Script llamada GeminiWithFiles simplifica el uso de Gemini, un modelo de lenguaje grande, para procesar datos no estructurados como imágenes y archivos PDF. GeminiWithFiles puede cargar archivos, generar contenido y crear descripciones a partir de varias imágenes a la vez. Esto reduce significativamente la carga de trabajo y amplía las posibilidades de utilizar Gemini.
Recientemente, Gemini, un gran modelo de lenguaje de Google AI, ha brindado nuevas posibilidades a diversas tareas al permitir el uso de datos no estructurados como datos estructurados. Esto es particularmente significativo porque existe una gran cantidad de información en formatos no estructurados como documentos de texto, imágenes y videos.
La API Gemini 1.5, lanzada recientemente, amplía significativamente estas capacidades. Puede generar contenido de hasta 1 millón de tokens, un aumento sustancial en comparación con versiones anteriores. Además, Gemini 1.5 ahora puede procesar hasta 3000 archivos de imágenes, superando ampliamente el límite de 16 imágenes de Gemini 1.0. Árbitro
Si bien Gemini no puede trabajar directamente con formatos de Google Drive como Docs, Sheets y Slides, existen soluciones. En la etapa actual, los datos PDF se pueden procesar directamente con la API de Gemini. Con esto, esos archivos de Google Docs se convierten a PDF y se usan con la API de Gemini. Árbitro
Este informe presenta una nueva biblioteca de Google Apps Script llamada "GeminiWithFiles" que simplifica este proceso. GeminiWithFiles permite a los usuarios cargar archivos y generar contenido fácilmente utilizando las poderosas capacidades de Gemini. También permite la creación eficiente de descripciones a partir de múltiples imágenes con una sola llamada API, lo que reduce significativamente la carga de trabajo en comparación con el procesamiento de cada imagen individualmente, como se demostró en mi informe anterior. Árbitro
Al optimizar el proceso y ampliar las capacidades, GeminiWithFiles es prometedor para varios casos de uso en diferentes dominios. Este informe sirve como un enfoque ampliado del anterior, con el objetivo de reducir aún más los costos de proceso y mejorar la eficiencia al trabajar con Gemini y datos no estructurados.
Creé esta biblioteca en base a los siguientes informes.
Esta biblioteca GeminiWithFiles le permite interactuar con Gemini, una potente plataforma de gestión y procesamiento de documentos, a través de una API fácil de usar. Esto es lo que puede lograr con esta biblioteca:
Gestión de archivos:
Carga de contenido:
Gestión del historial de chat:
Generación de contenido:
Especificación de salida:
Especifique el formato de salida deseado para los resultados generados por la API de Gemini.
Utilizando response_mime_type
y el esquema JSON, se controla el formato de salida. Árbitro
Para probar este script, siga los siguientes pasos.
Acceda a https://makersuite.google.com/app/apikey y cree su clave API. En ese momento, habilite la API de lenguaje generativo en la consola API. Esta clave API se utiliza para este script de muestra.
Este documento oficial también se puede ver. Árbitro.
Cree un proyecto independiente de Google Apps Script. Por supuesto, este script también se puede utilizar con el script vinculado al contenedor.
Y abra el editor de secuencias de comandos del proyecto Google Apps Script.
Hay 2 patrones para usar GeminiWithFiles.
Si utiliza esta biblioteca como biblioteca de Google Apps Script, instálela en su proyecto de Google Apps Script de la siguiente manera.
Cree un proyecto de Google Apps Script. O abra su proyecto de Google Apps Script.
Instale esta biblioteca.
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
Si utiliza esta biblioteca en su propio proyecto de Google Apps Script, copie y pegue el script "classGeminiWithFiles.js" en su proyecto de Google Apps Script. De esta manera, se puede utilizar el script.
"main.js" se utiliza para la biblioteca de Google Apps Script. Entonces, en este patrón, no es necesario que lo utilices.
Esta biblioteca utiliza los siguientes 2 ámbitos.
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/drive
Si desea utilizar el token de acceso, vincule el proyecto Google Cloud Platform al proyecto Google Apps Script. Y agregue el siguiente alcance.
https://www.googleapis.com/auth/generative-language
Además, puede ver el documento oficial de la API de Gemini en https://ai.google.dev/api/rest.
Métodos | Descripción |
---|---|
setFileIds(fileIds, asImage = false) | Establecer ID de archivos. |
establecerBlobs(blobs) | Establecer manchas. |
withUploadedFilesByGenerateContent(listadearchivos = []) | Cree un objeto para usar el método generateContent. |
cargar archivos (n = 50) | Sube archivos a Gemini. |
obtener lista de archivos() | Obtener lista de archivos en Gemini. |
eliminar archivos (nombres, n = 50) | Eliminar archivos de Gemini. |
generar contenido (objeto) | Método principal. Generar contenido mediante API Gemini. |
setFileIdsOrUrlsWithResumableUpload(objeto) | Se pueden cargar archivos de más de 50 MB en Gemini. |
Cuando instale GeminiWithFiles como biblioteca para su proyecto de Google Apps Script, utilice el siguiente script.
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
o
Cuando copie y pegue directamente el script de Class GeminiWithFiles en su proyecto de Google Apps Script, utilice el siguiente script.
const g = new GeminiWithFiles ( object ) ;
El valor del object
es el siguiente.
{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.
Cuando desee utilizar response_mime_type
, proporcione jsonSchema
para generar el método Content. En la etapa actual, solo se puede usar "application/json"
para response_mime_type
.
Cuando desee utilizar systemInstruction
, confirme el documento oficial Ref.
Gemini 1.5 Flash Latest ( models/gemini-1.5-flash-latest
) se utiliza como modelo predeterminado. Cuando desee utilizar Gemini 1.5 Pro Latest ( models/gemini-1.5-pro-latest
), utilícelo como const g = GeminiWithFiles.geminiWithFiles({ apiKey, model: "models/gemini-1.5-pro-latest" })
.
En la etapa actual, cuando se usa response_schema
, se usa automáticamente response_mime_type: "application/json"
.
Establecer ID de archivos. Los archivos de ID de archivo se cargan en Gemini.
En este caso, se utiliza async/await en la función.
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
son String[] (los ID de archivo en Google Drive) y el booleano, respectivamente. Si el segundo argumento es falso, los archivos ingresados con ID de archivo se cargan como datos sin procesar. Si el segundo argumento es verdadero, los archivos ingresados con ID de archivo se convierten en datos de imagen y se cargan. El valor predeterminado del segundo argumento es falso.false
en este método como setFileIds(fileIds, false)
. Establecer manchas. Los blobs se cargan en Gemini.
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
es Blob[].Cree un objeto para usar el método 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
tiene un solo argumento. Ese es el valor del método getFileList. Puede ver los valores reales después de cargar los archivos.Sube archivos a Gemini. Los archivos se cargan en Gemini utilizando los ID de archivo o blobs ingresados.
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 ) ;
}
En este script, los archivos de fileIds
se cargan en Gemini con los datos sin procesar. Si setFileIds(fileIds, false)
se modifica a setFileIds(fileIds, true)
, los archivos se cargan en Gemini como imágenes.
Cuando usa Blob directamente, puede usar el siguiente script.
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 ) ;
}
Obtener lista de archivos en 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 res = g . getFileList ( ) ;
console . log ( res ) ;
}
Eliminar archivos de 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.` ) ;
}
Método principal. Generar contenido mediante API Gemini. Se pueden ver más scripts de muestra en la siguiente sección "Scripts de muestra".
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 ) ;
}
En este script, el contenido se genera con la llamada a la función.
Cuando desee utilizar response_mime_type
, proporcione jsonSchema
para generar el método Content de la siguiente manera. En este caso, al proporcionar solo el esquema JSON, esta biblioteca puede devolver un objeto válido. También puedes ver la información detallada sobre response_mime_type
en mi informe.
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 ) ;
}
Cuando se ejecuta este script, se obtiene el siguiente resultado.
[
{ "recipe_name" : " Chocolate Chip Cookies " },
{ "recipe_name" : " Peanut Butter Cookies " },
{ "recipe_name" : " Oatmeal Cookies " },
{ "recipe_name" : " Sugar Cookies " },
{ "recipe_name" : " Snickerdoodle Cookies " }
]
Este método puede cargar archivos de más de 50 MB.
A partir de v2.xx, esto se puede lograr. Esto es de Ref y Ref.
A partir de v2.0.3, cuando utilice este método, incluya propertiesService: PropertiesService.getScriptProperties()
en el objeto inicial de la siguiente manera. Porque, cuando se usa PropertiesService.getScriptProperties()
en la biblioteca, los valores se colocan en la biblioteca. Cuando creé Ref y Ref, supuse que el script se usa copiando y pegando en lugar de la biblioteca. Entonces, incluí PropertiesService.getScriptProperties()
en el script. Pero noté que cuando esto se usa con GeminiWithFiles, cada usuario debe usar PropertiesService.getScriptProperties()
. Entonces, modifiqué esto.
El script de muestra es el siguiente.
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 ) ;
}
Cuando se ejecuta este script, se puede ver el siguiente registro en el registro.
- 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.
Si su archivo es grande y el estado del archivo cargado aún no es "ACTIVO", pruebe el siguiente script.
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".
}
Con esto, se puede cargar el archivo. Y puede usar el archivo cargado después de que espere el tiempo suficiente para cambiar el estado a "ACTIVO". El archivo cargado se puede utilizar de la siguiente manera.