Gemini API는 계속해서 성장하고 있습니다. 2024년 8월 5일 GeminiWithFiles를 v2.xx로 대폭 업데이트했습니다. 이번 대규모 업데이트로 버전이 v1에서 v2로 변경되었습니다.
GeminiWithFiles v1.xx를 사용하려면 여기를 참조하세요.
이것은 파일이 포함된 Gemini API용 Google Apps Script 라이브러리입니다.
GeminiWithFiles라는 새로운 Google Apps Script 라이브러리는 대규모 언어 모델인 Gemini를 사용하여 이미지 및 PDF와 같은 구조화되지 않은 데이터를 처리하는 작업을 단순화합니다. GeminiWithFiles는 파일을 업로드하고, 콘텐츠를 생성하고, 여러 이미지에서 한 번에 설명을 만들 수 있습니다. 이는 작업 부하를 크게 줄이고 Gemini 사용 가능성을 확장합니다.
최근에는 Google AI의 대규모 언어 모델인 Gemini를 통해 비정형 데이터를 정형 데이터로 활용 가능하게 함으로써 다양한 작업에 새로운 가능성을 가져왔습니다. 텍스트 문서, 이미지, 비디오 등 구조화되지 않은 형식으로 방대한 양의 정보가 존재하기 때문에 이는 특히 중요합니다.
최근 출시된 Gemini 1.5 API는 이러한 기능을 크게 확장합니다. 최대 100만 개의 토큰으로 콘텐츠를 생성할 수 있으며, 이는 이전 버전에 비해 상당히 증가한 수치입니다. 또한 Gemini 1.5는 이제 최대 3,000개의 이미지 파일을 처리할 수 있으며 이는 Gemini 1.0의 16개 이미지 제한을 크게 초과합니다. 참조
Gemini는 Docs, Sheets, Slides와 같은 Google 드라이브 형식으로 직접 작업할 수 없지만 해결 방법이 있습니다. 현 단계에서는 PDF 데이터를 Gemini API로 직접 처리할 수 있습니다. 이를 사용하여 Google Docs 파일을 PDF로 변환하고 Gemini API와 함께 사용합니다. 참조
이 보고서에서는 이 프로세스를 단순화하는 "GeminiWithFiles"라는 새로운 Google Apps Script 라이브러리를 소개합니다. GeminiWithFiles를 사용하면 사용자는 Gemini의 강력한 기능을 사용하여 쉽게 파일을 업로드하고 콘텐츠를 생성할 수 있습니다. 또한 단일 API 호출로 여러 이미지에서 효율적인 설명 생성이 가능하므로 이전 보고서에서 설명한 것처럼 각 이미지를 개별적으로 처리하는 것에 비해 작업 부하가 크게 줄어듭니다. 참조
프로세스를 간소화하고 기능을 확장함으로써 GeminiWithFiles는 다양한 도메인에 걸쳐 다양한 사용 사례를 약속합니다. 이 보고서는 Gemini 및 비정형 데이터로 작업할 때 프로세스 비용을 더욱 줄이고 효율성을 향상시키는 것을 목표로 이전 보고서에 대한 확장된 접근 방식을 제공합니다.
다음 보고서를 기반으로 이 라이브러리를 만들었습니다.
이 라이브러리 GeminiWithFiles를 사용하면 사용하기 쉬운 API를 통해 강력한 문서 처리 및 관리 플랫폼인 Gemini와 상호 작용할 수 있습니다. 이 라이브러리를 사용하여 얻을 수 있는 작업은 다음과 같습니다.
파일 관리:
콘텐츠 업로드:
채팅 기록 관리:
콘텐츠 생성:
출력 사양:
Gemini API에서 생성된 결과에 대해 원하는 출력 형식을 지정합니다.
response_mime_type
및 JSON 스키마를 사용하여 출력 형식이 제어됩니다. 참조
이 스크립트를 테스트하려면 다음 단계를 수행하십시오.
https://makerssuite.google.com/app/apikey에 접속하여 API 키를 생성하세요. 이때 API 콘솔에서 Generative Language API를 활성화하세요. 이 API 키는 이 샘플 스크립트에 사용됩니다.
이 공식 문서도 볼 수 있습니다. 참조.
독립형 Google Apps Script 프로젝트를 만드세요. 물론 이 스크립트는 컨테이너 바인딩 스크립트와 함께 사용할 수도 있습니다.
그리고 Google Apps Script 프로젝트의 스크립트 편집기를 열어주세요.
GeminiWithFiles를 사용하는 데는 두 가지 패턴이 있습니다.
이 라이브러리를 Google Apps Script 라이브러리로 사용하는 경우 다음과 같이 Google Apps Script 프로젝트에 라이브러리를 설치하세요.
Google Apps Script 프로젝트를 만듭니다. 또는 Google Apps Script 프로젝트를 엽니다.
이 라이브러리를 설치하세요.
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
자신의 Google Apps Script 프로젝트에서 이 라이브러리를 사용하는 경우 "classGeminiWithFiles.js" 스크립트를 복사하여 Google Apps Script 프로젝트에 붙여넣으세요. 이를 통해 스크립트를 사용할 수 있습니다.
"main.js"는 Google Apps Script 라이브러리에 사용됩니다. 따라서 이 패턴에서는 사용할 필요가 없습니다.
이 라이브러리는 다음 2가지 범위를 사용합니다.
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/drive
액세스 토큰을 사용하려면 Google Cloud Platform 프로젝트를 Google Apps Script 프로젝트에 연결하세요. 그리고, 다음 범위를 추가해주세요.
https://www.googleapis.com/auth/generative-language
또한 https://ai.google.dev/api/rest에서 Gemini API 공식 문서를 보실 수 있습니다.
행동 양식 | 설명 |
---|---|
setFileIds(fileIds, asImage = false) | 파일 ID를 설정합니다. |
setBlob(블롭) | 얼룩을 설정합니다. |
withUploadedFilesByGenerateContent(fileList = []) | generateContent 메소드를 사용하기 위한 객체를 생성합니다. |
업로드파일(n = 50) | Gemini에 파일을 업로드합니다. |
파일목록() | Gemini에서 파일 목록을 가져옵니다. |
deleteFiles(이름, n = 50) | Gemini에서 파일을 삭제합니다. |
생성컨텐트(객체) | 주요 방법. Gemini API로 콘텐츠를 생성합니다. |
setFileIdsOrUrlsWithResumableUpload(객체) | 50MB가 넘는 파일은 Gemini에 업로드할 수 있습니다. |
Google Apps Script 프로젝트에 GeminiWithFiles를 라이브러리로 설치할 때 다음 스크립트를 사용하세요.
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
또는
Class GeminiWithFiles의 스크립트를 Google Apps Script 프로젝트에 직접 복사하여 붙여넣을 때 다음 스크립트를 사용하세요.
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
사용하려면 generateContent 메소드에 jsonSchema
지정하세요. 현재 단계에서는 response_mime_type
에 "application/json"
만 사용할 수 있습니다.
systemInstruction
사용하려면 공식 문서 Ref.를 확인하세요.
Gemini 1.5 Flash 최신( 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"
자동으로 사용됩니다.
파일 ID를 설정합니다. 파일 ID의 파일이 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 드라이브의 파일 ID) 및 부울입니다. 두 번째 인수가 false이면 입력된 파일 ID의 파일이 원시 데이터로 업로드됩니다. 두 번째 인수가 true이면 입력된 파일 ID의 파일을 이미지 데이터로 변환하여 업로드한다. 두 번째 인수의 기본값은 false입니다.setFileIds(fileIds, false)
와 같은 이 메서드에서 false
사용할 수 있습니다. 얼룩을 설정합니다. Blob이 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[]입니다.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
인수가 하나만 있습니다. 이는 getFileList 메소드의 값입니다. 파일을 업로드한 후 실제 값을 볼 수 있습니다.Gemini에 파일을 업로드합니다. 파일은 입력된 파일 ID 또는 Blob을 사용하여 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
사용하고 싶다면 generateContent 메소드에 다음과 같이 jsonSchema
부여해주세요. 이 경우 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 " }
]
이 방법을 사용하면 50MB가 넘는 파일을 업로드할 수 있습니다.
v2.xx부터는 이를 달성할 수 있습니다. 이것은 Ref와 Ref에서 나온 것입니다.
v2.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.
파일이 크고 업로드된 파일의 상태가 아직 "ACTIVE"가 아닌 경우 다음 스크립트를 테스트하십시오.
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".
}
이를 통해 파일을 업로드할 수 있습니다. 그리고 업로드된 파일은 상태가 "ACTIVE"로 변경될 때까지 충분한 시간을 기다린 후 사용할 수 있습니다. 업로드한 파일은 다음과 같이 사용할 수 있습니다.