Gemini API terus berkembang. Pada tanggal 5 Agustus 2024, saya memperbarui sebagian besar GeminiWithFiles ke v2.xx Dengan pembaruan besar ini, versi diubah dari v1 ke v2.
Jika Anda ingin menggunakan GeminiWithFiles v1.xx, silakan lihat di sini.
Ini adalah perpustakaan Google Apps Script untuk Gemini API dengan file.
Pustaka Google Apps Script baru bernama GeminiWithFiles menyederhanakan penggunaan Gemini, model bahasa besar, untuk memproses data tidak terstruktur seperti gambar dan PDF. GeminiWithFiles dapat mengunggah file, menghasilkan konten, dan membuat deskripsi dari banyak gambar sekaligus. Ini secara signifikan mengurangi beban kerja dan memperluas kemungkinan penggunaan Gemini.
Baru-baru ini, Gemini, model bahasa besar dari Google AI, telah menghadirkan kemungkinan baru untuk berbagai tugas dengan memungkinkan penggunaan data tidak terstruktur sebagai data terstruktur. Hal ini sangat penting karena sejumlah besar informasi terdapat dalam format tidak terstruktur seperti dokumen teks, gambar, dan video.
API Gemini 1.5, yang dirilis baru-baru ini, secara signifikan memperluas kemampuan ini. Ini dapat menghasilkan konten hingga 1 juta token, peningkatan substansial dibandingkan versi sebelumnya. Selain itu, Gemini 1.5 kini dapat memproses hingga 3.000 file gambar, jauh melebihi batas 16 gambar pada Gemini 1.0. Ref
Meskipun Gemini tidak dapat langsung bekerja dengan format Google Drive seperti Dokumen, Spreadsheet, dan Slide, ada solusinya. Pada tahap saat ini, data PDF bisa langsung diproses dengan Gemini API. Dengan menggunakan ini, file Google Docs tersebut dikonversi ke PDF dan digunakan dengan Gemini API. Ref
Laporan ini memperkenalkan pustaka Google Apps Script baru yang disebut "GeminiWithFiles" yang menyederhanakan proses ini. GeminiWithFiles memungkinkan pengguna mengunggah file dan menghasilkan konten dengan mudah menggunakan kemampuan kuat Gemini. Hal ini juga memungkinkan pembuatan deskripsi yang efisien dari beberapa gambar dengan satu panggilan API, sehingga mengurangi beban kerja secara signifikan dibandingkan dengan memproses setiap gambar satu per satu seperti yang ditunjukkan dalam laporan saya sebelumnya. Ref
Dengan menyederhanakan proses dan memperluas kemampuan, GeminiWithFiles menjanjikan berbagai kasus penggunaan di berbagai domain. Laporan ini berfungsi sebagai pendekatan yang diperluas dari laporan sebelumnya, yang bertujuan untuk lebih mengurangi biaya proses dan meningkatkan efisiensi saat bekerja dengan Gemini dan data tidak terstruktur.
Saya membuat perpustakaan ini berdasarkan laporan berikut.
Perpustakaan GeminiWithFiles ini memungkinkan Anda berinteraksi dengan Gemini, platform pemrosesan dan manajemen dokumen yang kuat, melalui API yang mudah digunakan. Inilah yang dapat Anda capai dengan perpustakaan ini:
Manajemen File:
Unggah Konten:
Manajemen Riwayat Obrolan:
Pembuatan Konten:
Spesifikasi Keluaran:
Tentukan format output yang diinginkan untuk hasil yang dihasilkan oleh Gemini API.
Menggunakan skema response_mime_type
dan JSON, format output dikontrol. Ref
Untuk menguji skrip ini, silakan lakukan langkah-langkah berikut.
Silakan akses https://makersuite.google.com/app/apikey dan buat kunci API Anda. Pada saat itu, aktifkan API Bahasa Generatif di konsol API. Kunci API ini digunakan untuk contoh skrip ini.
Dokumen resmi ini juga dapat dilihat. Ref.
Harap buat proyek Skrip Google Apps mandiri. Tentu saja, skrip ini juga dapat digunakan dengan skrip yang terikat pada container.
Dan silahkan buka script editor proyek Google Apps Script.
Ada 2 pola untuk menggunakan GeminiWithFiles.
Jika Anda menggunakan perpustakaan ini sebagai perpustakaan Google Apps Script, harap pasang perpustakaan tersebut ke proyek Google Apps Script Anda sebagai berikut.
Buat proyek Skrip Google Apps. Atau, buka proyek Google Apps Script Anda.
Instal perpustakaan ini.
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
Jika Anda menggunakan perpustakaan ini dalam proyek Skrip Google Apps Anda sendiri, salin dan tempelkan skrip "classGeminiWithFiles.js" ke proyek Skrip Google Apps Anda. Dengan ini, skrip dapat digunakan.
"main.js" digunakan untuk perpustakaan Skrip Google Apps. Jadi, pada pola ini, Anda tidak diwajibkan untuk menggunakannya.
Perpustakaan ini menggunakan 2 cakupan berikut.
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/drive
Jika Anda ingin menggunakan token akses, harap tautkan Proyek Google Cloud Platform ke Proyek Google Apps Script. Dan, silakan tambahkan cakupan berikut.
https://www.googleapis.com/auth/generative-language
Anda juga dapat melihat dokumen resmi Gemini API di https://ai.google.dev/api/rest.
Metode | Keterangan |
---|---|
setFileIds(fileIds, asImage = false) | Tetapkan ID file. |
setBlob(gumpalan) | Atur gumpalan. |
denganUploadedFilesByGenerateContent(fileList = []) | Buat objek untuk menggunakan metode generateContent. |
unggahFile(n = 50) | Unggah file ke Gemini. |
dapatkanDaftar File() | Dapatkan daftar file di Gemini. |
deleteFiles(nama, n = 50) | Hapus file dari Gemini. |
menghasilkan Konten (objek) | Metode utama. Hasilkan konten dengan Gemini API. |
setFileIdsOrUrlsWithResumableUpload(objek) | File lebih dari 50 MB dapat diunggah ke Gemini. |
Saat Anda memasang GeminiWithFiles sebagai pustaka untuk proyek Skrip Google Apps Anda, harap gunakan skrip berikut.
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
atau
Saat Anda langsung menyalin dan menempelkan skrip Kelas GeminiWithFiles ke proyek Skrip Google Apps Anda, harap gunakan skrip berikut.
const g = new GeminiWithFiles ( object ) ;
Nilai object
adalah sebagai berikut.
{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.
Jika Anda ingin menggunakan response_mime_type
, berikan jsonSchema
ke metode generateContent. Pada tahap saat ini, hanya "application/json"
yang dapat digunakan untuk response_mime_type
.
Bila Anda ingin menggunakan systemInstruction
, harap konfirmasikan dokumen resmi Ref.
Gemini 1.5 Flash Terbaru ( models/gemini-1.5-flash-latest
) digunakan sebagai model default. Bila ingin menggunakan Gemini 1.5 Pro Terbaru ( models/gemini-1.5-pro-latest
), silakan gunakan seperti const g = GeminiWithFiles.geminiWithFiles({ apiKey, model: "models/gemini-1.5-pro-latest" })
.
Pada tahap saat ini, ketika response_schema
digunakan, response_mime_type: "application/json"
secara otomatis digunakan.
Tetapkan ID file. File ID file diunggah ke Gemini.
Dalam hal ini, async/await digunakan dalam fungsi tersebut.
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
ke-1 dan ke-2 adalah String[] (ID file di Google Drive) dan boolean. Jika argumen ke-2 salah, file ID file yang dimasukkan akan diunggah sebagai data mentah. Jika argumen ke-2 benar, file ID file yang dimasukkan akan dikonversi menjadi data gambar dan diunggah. Default argumen ke-2 adalah salah.false
pada metode ini seperti setFileIds(fileIds, false)
. Atur gumpalan. Gumpalan tersebut diunggah ke 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
adalah Blob[].Buat objek untuk menggunakan metode 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
hanya memiliki satu argumen. Itu adalah nilai dari metode getFileList. Anda dapat melihat nilai sebenarnya setelah Anda mengunggah file.Unggah file ke Gemini. File diunggah ke Gemini menggunakan ID file atau blob yang dimasukkan.
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 ) ;
}
Dalam skrip ini, file fileIds
diunggah ke Gemini dengan data mentah. Jika setFileIds(fileIds, false)
diubah menjadi setFileIds(fileIds, true)
, file akan diunggah ke Gemini sebagai gambar.
Saat Anda langsung menggunakan Blob, Anda dapat menggunakan skrip berikut.
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 ) ;
}
Dapatkan daftar file di 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 ) ;
}
Hapus file dari 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.` ) ;
}
Metode utama. Hasilkan konten dengan Gemini API. Contoh skrip selengkapnya dapat dilihat pada bagian “Contoh skrip” berikut.
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 ) ;
}
Dalam skrip ini, konten dihasilkan dengan pemanggilan fungsi.
Bila ingin menggunakan response_mime_type
, berikan metode jsonSchema
ke generateContent sebagai berikut. Dalam hal ini, dengan hanya memberikan skema JSON, perpustakaan ini dapat mengembalikan objek yang valid. Anda juga dapat melihat informasi detail tentang response_mime_type
di laporan saya.
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 ) ;
}
Ketika skrip ini dijalankan, diperoleh hasil sebagai berikut.
[
{ "recipe_name" : " Chocolate Chip Cookies " },
{ "recipe_name" : " Peanut Butter Cookies " },
{ "recipe_name" : " Oatmeal Cookies " },
{ "recipe_name" : " Sugar Cookies " },
{ "recipe_name" : " Snickerdoodle Cookies " }
]
Cara ini dapat mengupload file berukuran lebih dari 50 MB.
Dari v2.xx, hal ini dapat dicapai. Ini dari Ref dan Ref.
Mulai v2.0.3, saat Anda menggunakan metode ini, harap sertakan propertiesService: PropertiesService.getScriptProperties()
ke dalam objek awal sebagai berikut. Karena, ketika PropertiesService.getScriptProperties()
digunakan di perpustakaan, nilainya dimasukkan ke dalam perpustakaan. Saat saya membuat Ref dan Ref, saya mengira skrip tersebut digunakan dengan cara copy dan paste, bukan perpustakaan. Jadi, saya menyertakan PropertiesService.getScriptProperties()
dalam skrip. Tapi saya perhatikan bahwa ketika ini digunakan dengan GeminiWithFiles, setiap pengguna diharuskan menggunakan PropertiesService.getScriptProperties()
. Jadi, saya memodifikasi ini.
Contoh skripnya adalah sebagai berikut.
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 ) ;
}
Saat skrip ini dijalankan, log berikut dapat dilihat di log.
- 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.
Jika file anda berukuran besar dan keadaan file yang diupload belum masih "AKTIF", silahkan test script berikut ini.
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".
}
Dengan ini, file dapat diunggah. Dan, Anda dapat menggunakan file yang diunggah setelah menunggu cukup waktu untuk mengubah status menjadi "AKTIF". File yang diunggah dapat digunakan sebagai berikut.