Gemini API продолжает расти. 5 августа 2024 г. я значительно обновил GeminiWithFiles до версии v2.xx. В этом большом обновлении версия изменена с v1 на v2.
Если вы хотите использовать GeminiWithFiles v1.xx, см. здесь.
Это библиотека сценариев Google Apps для Gemini API с файлами.
Новая библиотека сценариев Google Apps под названием GeminiWithFiles упрощает использование Gemini, большой языковой модели, для обработки неструктурированных данных, таких как изображения и PDF-файлы. GeminiWithFiles может загружать файлы, генерировать контент и создавать описания из нескольких изображений одновременно. Это значительно снижает рабочую нагрузку и расширяет возможности использования Gemini.
Недавно Gemini, большая языковая модель от Google AI, привнесла новые возможности в решение различных задач, позволив использовать неструктурированные данные в качестве структурированных. Это особенно важно, поскольку огромное количество информации существует в неструктурированных форматах, таких как текстовые документы, изображения и видео.
API Gemini 1.5, выпущенный недавно, существенно расширяет эти возможности. Он может генерировать контент до 1 миллиона токенов, что значительно больше по сравнению с предыдущими версиями. Кроме того, Gemini 1.5 теперь может обрабатывать до 3000 файлов изображений, что значительно превышает лимит Gemini 1.0 на 16 изображений. Ссылка
Хотя Gemini не может напрямую работать с форматами Google Диска, такими как Документы, Таблицы и Презентации, существуют обходные пути. На текущем этапе данные PDF могут обрабатываться напрямую с помощью Gemini API. Благодаря этому файлы Google Docs преобразуются в PDF и используются с Gemini API. Ссылка
В этом отчете представлена новая библиотека сценариев Google Apps под названием GeminiWithFiles, которая упрощает этот процесс. GeminiWithFiles позволяет пользователям легко загружать файлы и создавать контент, используя мощные возможности Gemini. Это также позволяет эффективно создавать описания из нескольких изображений с помощью одного вызова API, что значительно снижает рабочую нагрузку по сравнению с обработкой каждого изображения по отдельности, как показано в моем предыдущем отчете. Ссылка
Оптимизируя процесс и расширяя возможности, GeminiWithFiles обещает множество вариантов использования в разных областях. Этот отчет представляет собой расширенный подход к предыдущему, направленный на дальнейшее снижение затрат на процессы и повышение эффективности при работе с Gemini и неструктурированными данными.
Я создал эту библиотеку на основе следующих отчетов.
Эта библиотека GeminiWithFiles позволяет вам взаимодействовать с Gemini, мощной платформой обработки и управления документами, через простой в использовании API. Вот чего вы можете достичь с помощью этой библиотеки:
Управление файлами:
Загрузка контента:
Управление историей чата:
Генерация контента:
Выходная спецификация:
Укажите желаемый формат вывода результатов, генерируемых API Gemini.
Формат вывода контролируется с помощью response_mime_type
и схемы JSON. Ссылка
Чтобы протестировать этот скрипт, выполните следующие действия.
Откройте https://makersuite.google.com/app/apikey и создайте свой ключ API. В это время включите API генеративного языка на консоли API. Этот ключ API используется для этого примера сценария.
Этот официальный документ также можно увидеть. Ссылка.
Создайте отдельный проект скрипта Google Apps. Конечно, этот сценарий также можно использовать со сценарием, привязанным к контейнеру.
И откройте редактор сценариев проекта Google Apps Script.
Существует два шаблона использования GeminiWithFiles.
Если вы используете эту библиотеку в качестве библиотеки сценариев Google Apps, установите ее в свой проект сценариев Google Apps следующим образом.
Создайте проект скрипта Google Apps. Или откройте проект Google Apps Script.
Установите эту библиотеку.
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
Если вы используете эту библиотеку в своем собственном проекте скрипта Google Apps, скопируйте и вставьте скрипт «classGeminiWithFiles.js» в свой проект скрипта Google Apps. При этом скрипт можно использовать.
«main.js» используется для библиотеки сценариев Google Apps. Итак, в этом шаблоне вам не обязательно его использовать.
Эта библиотека использует следующие две области видимости.
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/drive
Если вы хотите использовать токен доступа, свяжите проект Google Cloud Platform с проектом скрипта Google Apps. И, пожалуйста, добавьте следующую область действия.
https://www.googleapis.com/auth/generative-language
Также вы можете просмотреть официальный документ Gemini API по адресу https://ai.google.dev/api/rest.
Методы | Описание |
---|---|
setFileIds (fileIds, asImage = false) | Установите идентификаторы файлов. |
setBlobs(капли) | Установите капли. |
withUploadedFilesByGenerateContent (fileList = []) | Создайте объект для использования методаgenerContent. |
загрузить файлы (n = 50) | Загрузите файлы в Gemini. |
getFileList() | Получить список файлов в Gemini. |
deleteFiles(имена, n = 50) | Удалить файлы из Gemini. |
генерироватьСодержимое (объект) | Основной метод. Генерируйте контент с помощью Gemini API. |
setFileIdsOrUrlsWithResumableUpload (объект) | Файл размером более 50 МБ можно загрузить в Gemini. |
При установке GeminiWithFiles в качестве библиотеки в проект скрипта Google Apps используйте следующий скрипт.
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
или
При непосредственном копировании и вставке сценария класса GeminiWithFiles в проект сценария Google Apps используйте следующий сценарий.
const g = new GeminiWithFiles ( object ) ;
Стоимость object
следующая.
{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.
Если вы хотите использовать response_mime_type
, укажите jsonSchema
для методаgenerateContent. На текущем этапе для response_mime_type
можно использовать только "application/json"
.
Если вы хотите использовать systemInstruction
, подтвердите официальный документ Ref.
В качестве модели по умолчанию используется Gemini 1.5 Flash Latest ( models/gemini-1.5-flash-latest
). Если вы хотите использовать последнюю версию Gemini 1.5 Pro ( models/gemini-1.5-pro-latest
), используйте ее следующим образом: const g = GeminiWithFiles.geminiWithFiles({ apiKey, model: "models/gemini-1.5-pro-latest" })
.
На текущем этапе, когда используется response_schema
, автоматически используется response_mime_type: "application/json"
.
Установите идентификаторы файлов. Файлы с идентификаторами файлов загружаются в Gemini.
В этом случае в функции используется async/await.
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
являются String[] (идентификаторы файлов на Google Диске) и логическое значение соответственно. Если второй аргумент имеет значение false, введенные файлы с идентификаторами файлов загружаются как необработанные данные. Если второй аргумент имеет значение true, введенные файлы с идентификаторами файлов преобразуются в данные изображения и загружаются. По умолчанию второй аргумент имеет значение false.false
в этом методе, например setFileIds(fileIds, false)
. Установите капли. Капли загружаются в 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
— Blob[].Создайте объект для использования методаgenerContent.
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
имеет только один аргумент. Это значение метода getFileList. Вы можете увидеть фактические значения после загрузки файлов.Загрузите файлы в Gemini. Файлы загружаются в Gemini с использованием введенных идентификаторов файлов или больших двоичных объектов.
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 ) ;
}
В этом скрипте файлы fileIds
загружаются в Gemini с необработанными данными. Если setFileIds(fileIds, false)
изменен на setFileIds(fileIds, true)
, файлы загружаются в Gemini в виде изображений.
Когда вы напрямую используете Blob, вы можете использовать следующий скрипт.
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 ) ;
}
Получить список файлов в 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 ) ;
}
Удалить файлы из 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.` ) ;
}
Основной метод. Генерируйте контент с помощью Gemini API. Дополнительные примеры сценариев можно увидеть в следующем разделе «Примеры сценариев».
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 ) ;
}
В этом скрипте контент генерируется с помощью вызова функции.
Если вы хотите использовать response_mime_type
, укажите jsonSchema
для методаgenerateContent следующим образом. В этом случае, предоставляя только схему JSON, эта библиотека может вернуть действительный объект. Вы также можете увидеть подробную информацию об response_mime_type
в моем отчете.
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 ) ;
}
При запуске этого сценария получается следующий результат.
[
{ "recipe_name" : " Chocolate Chip Cookies " },
{ "recipe_name" : " Peanut Butter Cookies " },
{ "recipe_name" : " Oatmeal Cookies " },
{ "recipe_name" : " Sugar Cookies " },
{ "recipe_name" : " Snickerdoodle Cookies " }
]
Этот метод позволяет загружать файлы размером более 50 МБ.
Этого можно достичь начиная с версии 2.xx. Это из Ref и Ref.
Начиная с версии 2.0.3, когда вы используете этот метод, включите propertiesService: PropertiesService.getScriptProperties()
в исходный объект следующим образом. Потому что, когда PropertiesService.getScriptProperties()
используется в библиотеке, значения помещаются в библиотеку. Когда я создавал Ref и Ref, я предполагал, что вместо библиотеки используется скрипт копирования и вставки. Итак, я включил в скрипт PropertiesService.getScriptProperties()
. Но я заметил, что когда это используется с GeminiWithFiles, каждый пользователь должен использовать PropertiesService.getScriptProperties()
. Итак, я изменил это.
Пример сценария выглядит следующим образом.
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 ) ;
}
Когда этот сценарий запускается, в журнале можно увидеть следующий журнал.
- 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.
Если ваш файл большой и состояние загруженного файла еще не «АКТИВНО», протестируйте следующий скрипт.
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".
}
Благодаря этому файл можно загрузить. И вы можете использовать загруженный файл после того, как он подождет достаточно времени, чтобы изменить состояние на «АКТИВНО». Загруженный файл можно использовать следующим образом.