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 はドキュメント、スプレッドシート、スライドなどの Google ドライブ形式を直接操作することはできませんが、回避策はあります。現段階では、PDF データを Gemini API で直接処理できます。これを使用すると、これらの Google ドキュメント ファイルは PDF に変換され、Gemini API で使用されます。参照
このレポートでは、このプロセスを簡素化する「GeminiWithFiles」と呼ばれる新しい Google Apps Script ライブラリを紹介します。 GeminiWithFiles を使用すると、ユーザーは Gemini の強力な機能を使用してファイルを簡単にアップロードし、コンテンツを生成できます。また、単一の API 呼び出しで複数の画像から効率的に説明を作成できるため、以前のレポートで示したように各画像を個別に処理する場合と比べて作業負荷が大幅に軽減されます。参照
プロセスを合理化し、機能を拡張することで、GeminiWithFiles はさまざまなドメインにわたるさまざまなユースケースを約束します。このレポートは、以前のレポートを拡張したアプローチとして機能し、Gemini および非構造化データを扱う際のプロセス コストをさらに削減し、効率を向上させることを目的としています。
このライブラリは以下のレポートをもとに作成しました。
このライブラリ GeminiWithFiles を使用すると、使いやすい API を通じて、強力なドキュメント処理および管理プラットフォームである Gemini と対話できるようになります。このライブラリを使用して達成できることは次のとおりです。
ファイル管理:
コンテンツのアップロード:
チャット履歴管理:
コンテンツの生成:
出力仕様:
Gemini API によって生成された結果に必要な出力形式を指定します。
response_mime_type
と JSON スキーマを使用して、出力形式を制御します。参照
このスクリプトをテストするには、次の手順を実行してください。
https://makersuite.google.com/app/apikey にアクセスして API キーを作成してください。その際、APIコンソールでGenerative Language APIを有効にしてください。この API キーは、このサンプル スクリプトで使用されます。
こちらの公式ドキュメントもご覧いただけます。参照。
スタンドアロンの Google Apps Script プロジェクトを作成してください。もちろん、このスクリプトはコンテナーバインドされたスクリプトでも使用できます。
そして、Google Apps Scriptプロジェクトのスクリプトエディタを開いてください。
GeminiWithFiles の利用方法は 2 パターンあります。
このライブラリを 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
また、Gemini API の公式ドキュメントは https://ai.google.dev/api/rest でご覧いただけます。
メソッド | 説明 |
---|---|
setFileIds(fileIds, asImage = false) | ファイルIDを設定します。 |
setBlobs(ブロブ) | BLOB を設定します。 |
withUploadedFilesByGenerateContent(fileList = []) | generateContentメソッドを使用するためのオブジェクトを作成します。 |
アップロードファイル(n = 50) | ファイルを Gemini にアップロードします。 |
getFileList() | Gemini でファイルリストを取得します。 |
deleteFiles(名前、n = 50) | Gemini からファイルを削除します。 |
生成コンテンツ(オブジェクト) | メインメソッド。 Gemini API でコンテンツを生成します。 |
setFileIdsOrUrlsWithResumableUpload(オブジェクト) | 50 MB を超えるファイルは Gemini にアップロードできます。 |
GeminiWithFiles をライブラリとして Google Apps Script プロジェクトにインストールする場合は、次のスクリプトを使用してください。
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
または
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
の 1 番目と 2 番目の引数は、それぞれ String[] (Google ドライブ上のファイル ID) とブール値です。第2引数がfalseの場合、入力されたファイルIDのファイルを生データとしてアップロードします。第2引数がtrueの場合、入力されたファイルIDのファイルを画像データに変換してアップロードします。第 2 引数のデフォルトは false です。setFileIds(fileIds, false)
のようにこのメソッドでfalse
使用できます。 BLOB を設定します。 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
の第 1 引数は 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
引数が 1 つだけあります。これは 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 " }
]
この方法では、50 MB を超えるファイルをアップロードできます。
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」に変わるまで十分な時間を待った後に使用できます。アップロードしたファイルは以下のように利用できます。