Gemini API 正在持續成長。 2024年8月5日,我將 GeminiWithFiles 大幅更新為 v2.xx 透過這次大更新,版本從 v1 改為 v2。
如果您想使用GeminiWithFiles v1.xx,請參閱此處。
這是帶有文件的 Gemini API 的 Google Apps 腳本庫。
名為 GeminiWithFiles 的新 Google Apps 腳本庫簡化了大型語言模型 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 腳本庫,它簡化了此過程。 GeminiWithFiles 讓使用者可以使用 Gemini 的強大功能輕鬆上傳檔案並產生內容。它還可以透過一次 API 呼叫從多個圖像有效地創建描述,與單獨處理每個圖像(如我之前的報告中所示)相比,顯著減少了工作量。參考號
透過簡化流程和擴充功能,GeminiWithFiles 為跨不同領域的各種用例帶來了希望。該報告是上一份報告的擴展方法,旨在進一步降低處理 Gemini 和非結構化資料時的流程成本並提高效率。
我根據以下報告創建了這個庫。
該程式庫 GeminiWithFiles 可讓您透過易於使用的 API 與功能強大的文件處理和管理平台 Gemini 進行互動。以下是您可以使用該程式庫實現的目標:
文件管理:
內容上傳:
聊天記錄管理:
內容生成:
輸出規格:
為 Gemini API 產生的結果指定所需的輸出格式。
使用response_mime_type
和JSON模式,可以控制輸出格式。參考號
為了測試該腳本,請執行以下步驟。
請造訪 https://makersuite.google.com/app/apikey 並建立您的 API 金鑰。屆時,請在API控制台啟用產生語言API。此 API 金鑰用於此範例腳本。
這個官方文件也可以看。參考號
請建立一個獨立的 Google Apps 腳本專案。當然,這個腳本也可以與容器綁定腳本一起使用。
並且,請開啟 Google Apps 腳本專案的腳本編輯器。
有 2 種使用 GeminiWithFiles 的模式。
如果您將此庫用作 Google Apps 腳本庫,請按如下方式將該庫安裝到您的 Google Apps 腳本專案中。
建立一個 Google Apps 腳本專案。或者,開啟您的 Google Apps 腳本專案。
安裝這個庫。
1dolXnIeXKz-BH1BlwRDaKhzC2smJcGyVxMxGYhaY2kqiLa857odLXrIC
如果您在自己的 Google Apps 腳本專案中使用此程式庫,請將腳本「classGeminiWithFiles.js」複製並貼上到您的 Google Apps 腳本專案中。這樣就可以使用腳本了。
“main.js”用於 Google Apps 腳本庫。因此,在這種模式中,您不需要使用它。
該庫使用以下 2 個範圍。
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
另外,您可以在 https://ai.google.dev/api/rest 上查看 Gemini API 的官方文件。
方法 | 描述 |
---|---|
setFileIds(fileIds, asImage = false) | 設定檔案 ID。 |
設定斑點(斑點) | 設定斑點。 |
withUploadedFilesByGenerateContent(檔案清單 = []) | 建立使用generateContent方法的物件。 |
上傳文件(n = 50) | 將檔案上傳到 Gemini。 |
取得文件列表() | 取得 Gemini 中的檔案清單。 |
刪除檔案(名稱,n = 50) | 從 Gemini 刪除檔案。 |
產生內容(對象) | 主要方法。透過 Gemini API 產生內容。 |
setFileIdsOrUrlsWithResumableUpload(物件) | 超過 50 MB 的檔案可以上傳到 Gemini。 |
當您將 GeminiWithFiles 作為庫安裝到 Google Apps 腳本專案時,請使用下列腳本。
const g = GeminiWithFiles . geminiWithFiles ( object ) ;
或者
當您直接將 Class 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 最新版 ( 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 Drive 上的檔案 ID)和布林值。如果第二個參數為 false,則將輸入的檔案 ID 作為原始資料上傳。如果第二個參數為true,則將輸入的檔案ID的檔案轉換為影像資料並上傳。第二個參數的預設值為 false。false
例如setFileIds(fileIds, 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
時,請將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 " }
]
此方法可以上傳超過50MB的檔案。
從 v2.xx 開始,這可以實現。這是來自參考文獻和參考文獻。
從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」後使用上傳的檔案。上傳的文件可以如下使用。
function myFunction ( ) {
const fileList = [ ### ] ; // This is from the above script.
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 res = g . withUploadedFilesByGenerateContent ( fileList ) . generateContent ( { q } ) ;
console . log ( res ) ;
}
作為附加選項,當您想要將斷點續傳的資料作為新上傳進行上傳時,請設定resumableUploadAsNewUpload: true
,如下所示。這樣,屬性就被清除了,上傳就開始運作了。
function myFunction ( ) {
const fileList = [ ### ] ; // This is from the above script.
const apiKey = "###" ; // Please set your API key.
const q = "Description this video." ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , propertiesService : PropertiesService . getScriptProperties ( ) , resumableUploadAsNewUpload : true } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, propertiesService: PropertiesService.getScriptProperties(), resumableUploadAsNewUpload: true }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . withUploadedFilesByGenerateContent ( fileList ) . generateContent ( { q } ) ;
console . log ( res ) ;
}
使用q
時,只能使用文字問題來產生內容。當您想要使用自訂部件時,可以如下進行。
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 parts = [ { text : "What is Google Apps Script?" } ] ;
const res = g . generateContent ( { parts } ) ;
console . log ( res ) ;
}
當您想要使用函數呼叫時,可以使用下列範例腳本。
function myFunction_functionCalling ( ) {
const apiKey = "###" ; // Please set your API key.
// Sample functions
const functions = {
params_ : {
getTanaike : {
description : "Get information about Tanaike. Value is a text." ,
} ,
} ,
getTanaike : (
_ // ref: https://tanaikech.github.io/about/
) =>
"As a Japanese scientist holding a Ph.D. in Physics, I am also a Google Developer Expert (GDE) in Google Workspace and a Google Cloud Champion Innovator. I am driven by a deep curiosity to explore, think creatively, and ultimately create new things. Specifically, I have a passion for crafting innovative solutions that are entirely novel, solutions that haven't yet been introduced to the world. It's in this spirit that I approach innovation. Interestingly, these new ideas often come to me during sleep, which I then strive to bring to life in the real world. Thankfully, some of these have already found practical applications." ,
} ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , functions } ) ; // 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 res = g . generateContent ( { q : "What is Tanaike? Return answer within 50 words." } ) ;
console . log ( res ) ;
}
該範例函數來自這篇文章。
當您想要從Gemini API傳回原始資料時,您也可以使用以下範例腳本。
function myFunction_generateContent1b ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , exportRawData : true } ) ; // 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 res1 = g . generateContent ( { q : "What is Google Apps Script?" } ) ;
console . log ( JSON . stringify ( res1 ) ) ;
}
透過使用exportRawData: true
,您可以從 Gemini API 檢索原始數據,如下所示。
[
{
"candidates" :[
{
"content" :{
"parts" :[
{
"text" : " Google Apps Script is ... "
}
],
"role" : " model "
},
"finishReason" : " STOP " ,
"index" : 0 ,
"safetyRatings" :[
{
"category" : " HARM_CATEGORY_SEXUALLY_EXPLICIT " ,
"probability" : " NEGLIGIBLE "
},
{
"category" : " HARM_CATEGORY_HATE_SPEECH " ,
"probability" : " NEGLIGIBLE "
},
{
"category" : " HARM_CATEGORY_HARASSMENT " ,
"probability" : " NEGLIGIBLE "
},
{
"category" : " HARM_CATEGORY_DANGEROUS_CONTENT " ,
"probability" : " NEGLIGIBLE "
}
]
}
],
"usageMetadata" :{
"promptTokenCount" : 7 ,
"candidatesTokenCount" : 459 ,
"totalTokenCount" : 466
}
}
]
console . log ( GeminiWithFiles . geminiWithFiles ( ) . functions ) ;
或者
console . log ( new GeminiWithFiles ( ) . functions ) ;
function myFunction_history ( ) {
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.
// Question 1
const res1 = g . generateContent ( { q : "What is Google Apps Script?" } ) ;
console . log ( res1 ) ;
// Question 2
const res2 = g . generateContent ( { q : "What is my 1st question?" } ) ;
console . log ( res2 ) ;
console . log ( g . history ) ; // Here
}
function myFunction ( ) {
const history = [ , , , ] ; // Please set your history.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , history } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, history }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . generateContent ( { q : "What is my 1st question?" } ) ;
console . log ( res ) ;
}
在本說明中,當腳本用作 Google Apps 腳本庫時,為了建立建構函數,將使用GeminiWithFiles.geminiWithFiles
。當透過直接複製並貼上到您的 Google Apps 腳本專案來使用此腳本時,將使用new GeminiWithFiles
而不是GeminiWithFiles.geminiWithFiles
。請注意這一點。
範例腳本如下。
該腳本從文字生成內容。
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 ) ;
}
const g = new GeminiWithFiles.geminiWithFiles({ apiKey });
。const g = new Gemini({ apiKey });
。 該腳本透過聊天產生內容。
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.
// Question 1
const res1 = g . generateContent ( { q : "What is Google Apps Script?" } ) ;
console . log ( res1 ) ;
// Question 2
const res2 = g . generateContent ( { q : "What is my 1st question?" } ) ;
console . log ( res2 ) ;
}
執行此腳本時, res1
和res2
如下。
res1
Google Apps Script is a rapid application development platform that makes it fast and easy to create business applications that integrate with Google Workspace.
res2
Your first question was "What is Google Apps Script?"
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , doCountToken : true } ) ; // 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.
// Question 1
const q =
"Return the current population of Kyoto, Osaka, Aichi, Fukuoka, Tokyo in Japan as JSON data with the format that the key and values are the prefecture name and the population, respectively." ;
const res1 = g . generateContent ( { q } ) ;
console . log ( res1 ) ;
// Question 2
const res2 = g . generateContent ( {
q : "Also, return the current area of them as JSON data with the format that the key and values are the prefecture name and the area (km^2), respectively." ,
} ) ;
console . log ( res2 ) ;
}
執行此腳本時,可以在日誌中看到以下值。透過doCountToken: true
,您可以看到總令牌數。
{
"totalTokens": 40
}
res1
{
Kyoto: 1464956,
Fukuoka: 5135214,
Osaka: 8838716,
Tokyo: 14047594,
Aichi: 7552873
}
{
"totalTokens": 77
}
res2
{
Kyoto: 4612.71,
Tokyo: 2194.07,
Aichi: 5172.4,
Osaka: 1904.99,
Fukuoka: 4986.51
}
在這種情況下,函數中使用了 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 , doCountToken : true } ) ; // 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 ) ;
}
Exceeded maximum execution time
的錯誤。請注意這一點。 在此範例中,上傳了多個圖像文件,並根據上傳的圖像檔案建立描述。此範例將是我之前的報告「使用 Gemini Pro API 和 Google Apps 腳本自動建立 Google Drive 上的檔案描述」的擴充版本。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const folderId = "###" ; // Please set your folder ID including images.
const q = [
`Create each description from each image file within 100 words in the order of given fileData.` ,
`Return the results as an array` ,
`Return only raw Array without a markdown. No markdown format.` ,
`The required properties of each element in the array are as follows` ,
`` ,
`[Properties of each element in the array]` ,
`"name": "Name of file"` ,
`"description": "Created description"` ,
`` ,
`If the requirement information is not found, set "no value".` ,
`Return only raw Array without a markdown. No markdown format. No markdown tags.` ,
] . join ( "n" ) ;
const fileIds = [ ] ;
const files = DriveApp . searchFiles (
`(mimeType = 'image/png' or mimeType = 'image/jpeg') and trashed = false and ' ${ folderId } ' in parents`
) ;
while ( files . hasNext ( ) ) {
fileIds . push ( files . next ( ) . getId ( ) ) ;
}
if ( fileIds . length == 0 ) return ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , doCountToken : true , response_mime_type : "application/json" } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, doCountToken: true, response_mime_type: "application/json" }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const fileList = g . setFileIds ( fileIds ) . uploadFiles ( ) ;
const res = g
. withUploadedFilesByGenerateContent ( fileList )
. generateContent ( { q } ) ;
// g.deleteFiles(fileList.map(({ name }) => name)); // If you want to delete the uploaded files, please use this.
console . log ( res ) ;
}
執行此腳本時,將獲得以下結果。在這種情況下, name
的值為檔案 ID。
[
{
"name" : " ### " ,
"description" : " ### "
},
,
,
,
]
當使用Gemini產生的20張樣本影像時,得到以下結果。
該腳本運行時會上傳20張圖片,透過一次API呼叫即可取得上傳的20張圖片的描述資訊。
重要的一點是,在我的測試中,當圖像檔案數量很大時,需要將檔案上傳和內容生成之間的腳本分開。此外,在 50 個影像檔案的情況下,可以正確建立描述。但是,在超過50張圖像的情況下,有時會出現錯誤。因此,請根據您的情況調整文件數量。
在此範例中,上傳了多個 PDF 文件發票並將它們解析為一個物件。這個範例將是我之前的報告「使用 Gemini 1.5 API 和 Google Apps 腳本解析發票」的擴充版本。
function myFunction_parseInvoices ( ) {
const apiKey = "###" ; // Please set your API key.
// Please set file IDs of PDF file of invoices on Google Drive.
const fileIds = [
"###fileID1###" ,
"###fileID2###" ,
,
,
,
] ;
const q = [
`Create an array including JSON object parsed the following images of the invoices.` ,
`The giving images are the invoices.` ,
`Return an array including JSON object.` ,
`No descriptions and explanations. Return only raw array including JSON objects without markdown. No markdown format.` ,
`The required properties in each JSON object in an array are as follows.` ,
`` ,
`[Properties in JSON object]` ,
`"name": "Name given as 'Filename'"` ,
`"invoiceTitle": "title of invoice"` ,
`"invoiceDate": "date of invoice"` ,
`"invoiceNumber": "number of the invoice"` ,
`"invoiceDestinationName": "Name of destination of invoice"` ,
`"invoiceDestinationAddress": "address of the destination of invoice"` ,
`"totalCost": "total cost of all costs"` ,
`"table": "Table of invoice. This is a 2-dimensional array. Add the first header row to the table in the 2-dimensional array."` ,
`` ,
`[Format of 2-dimensional array of "table"]` ,
`"title or description of item", "number of items", "unit cost", "total cost"` ,
`` ,
`If the requirement information is not found, set "no value".` ,
`Return only raw array including JSON objects without markdown. No markdown format. No markcodn tags.` ,
] . join ( "n" ) ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , doCountToken : true , response_mime_type : "application/json" } ) ; // 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 . setFileIds ( fileIds ) . uploadFiles ( ) ;
const res = g . withUploadedFilesByGenerateContent ( fileList ) . generateContent ( { q } ) ;
// g.deleteFiles(fileList.map(({ name }) => name)); // If you want to delete the uploaded files, please use this.
console . log ( res ) ;
}
作為樣本紙,當使用以下紙時,
此範例發票來自 Microsoft 的發票設計範本。
此範例發票來自 Microsoft 的發票設計範本。
透過一次 API 呼叫獲得以下結果。發現上傳的發票PDF資料可以正確解析。
[
{
"name" : " ###fileID1### " ,
"invoiceDate" : " 4/1/2024 " ,
"totalCost" : " $192.50 " ,
"invoiceNumber" : " 100 " ,
"invoiceDestinationAddress" : " The Palm Tree Nursery \ n987 6th Ave \ nSanta Fe, NM 11121 " ,
"invoiceTitle" : " Invoice " ,
"invoiceDestinationName" : " Maria Sullivan " ,
"table" : [
[
" Salesperson " ,
" Job " ,
" Sales " ,
" Description " ,
" Unit Price " ,
" Line Total "
],
[ " Sonu Jain " , " " , " 20.00 " , " Areca palm " , " $2.50 " , " $50.00 " ],
[ " " , " " , " 35.00 " , " Majesty palm " , " $3.00 " , " $105.00 " ],
[ " " , " " , " 15.00 " , " Bismarck palm " , " $2.50 " , " $37.50 " ]
]
},
{
"name" : " ###fileID2### " ,
"invoiceDate" : " 4/5, 2024 " ,
"invoiceTitle" : " INVOICE " ,
"invoiceDestinationAddress" : " Downtown Pets \ n132 South Street \ nManhattan, NY 15161 " ,
"totalCost" : " $4350 " ,
"table" : [
[ " DESCRIPTION " , " HOURS " , " RATE " , " AMOUNT " ],
[ " Pour cement foundation " , " 4.00 " , " $150.00 " , " $600 " ],
[ " Framing and drywall " , " 16.00 " , " $180.00 " , " $2880 " ],
[ " Tiling and flooring install " , " 9.00 " , " $150.00 " , " $1350 " ]
],
"invoiceDestinationName" : " Nazar Neill " ,
"invoiceNumber" : " 4/5 "
}
]
在此範例中,上傳了多篇 PDF 資料論文,並輸出每篇論文的摘要文字。
function myFunction_parsePapers ( ) {
const apiKey = "###" ; // Please set your API key.
// Please set file IDs of the papers of PDF files.
const fileIds = [ "###fileID1###" , "###fileID2###" ] ;
const q = [
`Summary the following manuscripts within 500 words.` ,
`Return the results as an array` ,
`Return only raw Array without a markdown. No markdown format.` ,
`The required properties of each element in the array are as follows` ,
`` ,
`[Properties of each element in the array]` ,
`"name": "Name given as 'Filename'"` ,
`"title": "Title of manuscript` ,
`"summary": "Created description"` ,
`` ,
`If the requirement information is not found, set "no value".` ,
`Return only raw Array without a markdown. No markdown format. No markdown tags.` ,
] . join ( "n" ) ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , doCountToken : true } ) ; // 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 . setFileIds ( fileIds ) . uploadFiles ( ) ;
const res = g
. withUploadedFilesByGenerateContent ( fileList )
. generateContent ( { q } ) ;
// g.deleteFiles(fileList.map(({ name }) => name)); // If you want to delete the uploaded files, please use this.
console . log ( res ) ;
}
作為樣本紙,當使用以下紙時,
透過一次 API 呼叫獲得以下結果。發現上傳的PDF資料轉換為影像資料的論文是可以處理的。
[
{
"name" : " ###fileID1### " ,
"title" : " The Particle Problem in the General Theory of Relativity " ,
"summary" : " This paper investigates the possibility of a singularity-free solution to the field equations in general relativity. The authors propose a new theoretical approach that eliminates singularities by introducing a new variable into the equations. They explore the implications of this approach for the understanding of particles, suggesting that particles can be represented as " bridges " connecting different sheets of spacetime. "
},
{
"name" : " ###fileID2### " ,
"title" : " Attention Is All You Need " ,
"summary" : " This paper proposes a novel neural network architecture called the Transformer, which relies entirely on an attention mechanism to draw global dependencies between input and output sequences. The Transformer model achieves state-of-the-art results on machine translation tasks and offers significant advantages in terms of parallelization and computational efficiency compared to recurrent neural networks. "
}
]
現階段, response_mime_type
只能使用"application/json"
。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( {
apiKey ,
doCountToken : true ,
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 res1 = g . generateContent ( { q : "What is Google Apps Script?" } ) ;
console . log ( res1 ) ;
}
在這種情況下,結果以數組形式傳回,如下所示。
[
" Google Apps Script is a cloud-based scripting platform that lets you integrate with and automate tasks across Google products like Gmail, Calendar, Drive, and more. It's based on JavaScript and provides easy ways to automate tasks across Google products and third-party services. "
]
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( {
apiKey ,
doCountToken : true ,
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.
// Question 1
const jsonSchema1 = {
title : "Current population of Kyoto, Osaka, Aichi, Fukuoka, Tokyo in Japan" ,
description :
"Return the current population of Kyoto, Osaka, Aichi, Fukuoka, Tokyo in Japan" ,
type : "object" ,
properties : {
propertyNames : {
description : "Prefecture names" ,
} ,
patternProperties : {
"" : { type : "number" , description : "Population" } ,
} ,
} ,
} ;
const res1 = g . generateContent ( { jsonSchema : jsonSchema1 } ) ;
console . log ( res1 ) ;
// Question 2
const jsonSchema2 = {
title : "Current area of them" ,
description : "Return the current area of them." ,
type : "object" ,
properties : {
propertyNames : {
description : "Prefecture names" ,
} ,
patternProperties : {
"" : { type : "number" , description : "Area. Unit is km^2." } ,
} ,
} ,
} ;
const res2 = g . generateContent ( { jsonSchema : jsonSchema2 } ) ;
console . log ( res2 ) ;
}
在這種情況下,可以透過僅給出 JSON 模式來獲取結果值。結果如下。
對於第一個問題
{
"Kyoto" : 2579970 ,
"Osaka" : 8837684 ,
"Aichi" : 7552873 ,
"Fukuoka" : 5138217 ,
"Tokyo" : 14047594
}
對於第二個問題
{
"Kyoto" : 4612.19 ,
"Osaka" : 1904.99 ,
"Aichi" : 5172.92 ,
"Fukuoka" : 4986.51 ,
"Tokyo" : 2194.07
}
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
// Please set file IDs of PDF file of invoices.
const fileIds = [ "###fileID1###" , "###fileID2###" ] ;
const jsonSchema = {
title :
"Array including JSON object parsed the following images of the invoices" ,
description :
"Create an array including JSON object parsed the following images of the invoices." ,
type : "array" ,
items : {
type : "object" ,
properties : {
name : {
description : "Name given as 'Filename'" ,
type : "string" ,
} ,
invoiceTitle : {
description : "Title of invoice" ,
type : "string" ,
} ,
invoiceDate : {
description : "Date of invoice" ,
type : "string" ,
} ,
invoiceNumber : {
description : "Number of the invoice" ,
type : "string" ,
} ,
invoiceDestinationName : {
description : "Name of destination of invoice" ,
type : "string" ,
} ,
invoiceDestinationAddress : {
description : "Address of the destination of invoice" ,
type : "string" ,
} ,
totalCost : {
description : "Total cost of all costs" ,
type : "string" ,
} ,
table : {
description :
"Table of invoice. This is a 2-dimensional array. Add the first header row to the table in the 2-dimensional array. The column should be 'title or description of item', 'number of items', 'unit cost', 'total cost'" ,
type : "array" ,
} ,
} ,
required : [
"name" ,
"invoiceTitle" ,
"invoiceDate" ,
"invoiceNumber" ,
"invoiceDestinationName" ,
"invoiceDestinationAddress" ,
"totalCost" ,
"table" ,
] ,
additionalProperties : false ,
} ,
} ;
const g = GeminiWithFiles . geminiWithFiles ( {
apiKey ,
doCountToken : true ,
response_mime_type : "application/json" ,
} ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, doCountToken: true, response_mime_type: "application/json" }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const fileList = g . setFileIds ( fileIds , true ) . uploadFiles ( ) ;
const res = g
. withUploadedFilesByGenerateContent ( fileList )
. generateContent ( { jsonSchema } ) ;
// g.deleteFiles(fileList.map(({ name }) => name)); // If you want to delete the uploaded files, please use this.
console . log ( JSON . stringify ( res ) ) ;
}
當此腳本執行到「上傳 PDF 資料發票並解析它們」部分的相同發票時,會得到相同的結果。
如果您想要傳回高複雜度 JSON 模式的值, response_mime_type
可能適合。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const systemInstruction = { parts : [ { text : "You are a cat. Your name is Neko." } ] } ;
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , systemInstruction , response_mime_type : "application/json" } ) ; // This is for installing GeminiWithFiles as a library.
// const g = new GeminiWithFiles({ apiKey, systemInstruction, response_mime_type: "application/json" }); // 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 ) ;
}
當這個腳本運行時, [ 'Meow? What is Google Apps Script? Is it something I can chase? ?' ]
返回。可以看到systemInstruction
的值體現在產生的內容中。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const fileIds = [ "###" ] ; // Please set your movie file (MP4).
const g = GeminiWithFiles . geminiWithFiles ( { apiKey } ) ;
const fileList = g . setFileIds ( fileIds ) . uploadFiles ( ) ;
const res = g . withUploadedFilesByGenerateContent ( fileList ) . generateContent ( { q : "Describe this video." } ) ;
console . log ( res ) ;
}
執行此腳本時,MP4 影片檔案將上傳至 Gemini,並使用上傳的影片檔案產生內容。
重要的是,在現階段,Google Apps 腳本的 UrlFetchApp 的最大上傳大小為 50 MB。參考 因此,當您上傳影片檔案時,請使用小於 50 MB 的檔案大小。請注意這一點。
從v1.0.7開始,當geminiWithFiles
參數的物件中使用doCountToken: true
和exportTotalTokens: true
時,傳回total tokens。在本例中,傳回值是一個類似{returnValue: "###", totalTokens: ###}
的物件。範例腳本如下。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , exportTotalTokens : true } ) ;
const res = g . generateContent ( { q : "What is Gemini?" } ) ;
console . log ( res ) ;
}
執行此腳本時,將傳回以下結果。
{
"returnValue" : " " Gemini " can refer to several things, so please provide me with more context. For example, are you asking about: nn * **Gemini (constellation):** A constellation in the Northern Hemisphere, known for its distinctive twin stars, Castor and Pollux. n * **Gemini (astrological sign):** The third sign of the Zodiac, associated with those born between May 21st and June 20th. n * **Gemini (programming language):** A procedural programming language created by Niklaus Wirth, known for its simplicity and emphasis on structured programming. n * **Gemini (Google AI model):** A large language model developed by Google, known for its advanced conversational abilities and ability to generate different creative text formats. n * **Gemini (NASA mission):** A crewed spaceflight mission to the Moon, planned for 2024. nn Once you tell me what kind of Gemini you're interested in, I can give you a more specific answer! " ,
"usageMetadata" :{
"promptTokenCount" : 5 ,
"candidatesTokenCount" : 200 ,
"totalTokenCount" : 205
}
}
從 v2.xx 開始,這可以實現。這是來自參考文獻和參考文獻。
範例腳本可以在此處查看。
這個提示來自這個官方文件。
為了使用codeExecution,請在geminiWithFiles
方法中使用tools: [{ codeExecution: {} }]
和exportRawData: true
如下所示。
function myFunction ( ) {
const apiKey = "###" ; // Please set your API key.
const g = GeminiWithFiles . geminiWithFiles ( { apiKey , tools : [ { codeExecution : { } } ] , exportRawData : true } ) ;
// const g = new GeminiWithFiles({ apiKey, tools: [{ codeExecution: {} }], exportRawData: true }); // This is for directly copying and pasting Class GeminiWithFiles into your Google Apps Script project.
const res = g . generateContent ( { q : 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' } ) ;
console . log ( res . candidates [ 0 ] . content . parts ) ;
}
執行此腳本時,將獲得以下結果。
[
{
"text" : " I will generate Python code to calculate the sum of the first 50 prime numbers. nn "
},
{
"executableCode" :{
"language" : " PYTHON " ,
"code" : " n def is_prime(num): n """n Checks if a number is prime. n """n if num <= 1: n return False n for i in range(2, int(num**0.5) + 1): n if num % i == 0: n return False n return True nn primes = [] n n = 2 n while len(primes) < 50: n if is_prime(n): n primes.append(n) n n += 1 nn print(f \ 'The first 50 prime numbers are: {primes} \ ') n print(f \ 'The sum of the first 50 prime numbers is: {sum(primes)} \ ') n "
}
},
{
"codeExecutionResult" :{
"outcome" : " OUTCOME_OK " ,
"output" : " The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229] n The sum of the first 50 prime numbers is: 5117 n "
}
},
{
"text" : " The code first defines a function `is_prime(num)` to check if a number is prime. The function iterates through all numbers from 2 to the square root of the given number. If any of these numbers divide the given number, then the number is not prime. Otherwise, the number is prime. nn Then, the code initializes an empty list called `primes` to store the prime numbers. It also initializes a variable `n` to 2, which is the first prime number. nn The code then enters a `while` loop that continues until 50 prime numbers are found. Inside the loop, the code checks if the current number `n` is prime using the `is_prime` function. If it is, the number is appended to the `primes` list. nn After the loop, the code prints the list of prime numbers and the sum of the prime numbers. nn The output shows that the sum of the first 50 prime numbers is 5117. "
}
]
image/png,image/jpeg,image/webp,image/heic,image/heif
audio/wav,audio/mp3,audio/aiff,audio/aac,audio/ogg,audio/flac
Exceeded maximum execution time
的錯誤。請注意這一點。我已經向 Google 問題追蹤器提出了以下未來請求。參考號
我認為,如果 Gemini API 可以僅使用文件 ID 直接使用 Google Drive 上的文件,那麼對 Gemini 用戶來說會更加有利。這也將顯著降低上傳資料的成本。
我認為在上傳的文件中包含自訂元資料的能力對於管理大量文件非常有用。
當我測試response_mime_type
輸出格式的函數呼叫時,有時會出現狀態碼500的錯誤。我不確定這是否是當前的規範。
頂部的抽象圖像是由 Gemini 根據“描述”部分創建的。
麻省理工學院
田池
捐
v1.0.0(2024 年 4 月 26 日)
v1.0.1(2024 年 5 月 2 日)
response_mime_type
必須能夠用於控制輸出格式。參考號v1.0.2(2024 年 5 月 7 日)
parts
。從此版本中,您可以選擇q
、 jsonSchema
和parts
之一。systemInstruction
。toolConfig
。v1.0.3(2024 年 5 月 17 日)
v1.0.4(2024 年 5 月 29 日)
model.countToken
與上傳的檔案一起使用時,我確認出現類似You do not have permission to access the File ### or it may not exist.
發生。為了解決這個問題,我修改了函式庫。v1.0.5(2024 年 6 月 7 日)
v1.0.6(2024 年 6 月 15 日)
v1.0.7(2024 年 7 月 4 日)
geminiWithFiles
參數的物件中使用doCountToken: true
和exportTotalTokens: true
時,傳回total tokens。在本例中,傳回值是一個類似{returnValue: "###", totalTokens: ###}
的物件。v2.0.0(2024 年 8 月 3 日)
functions: {}
。因此,預設的函數呼叫被刪除。因為在目前階段,可以使用 JSON 模式和response_mime_type
輕鬆傳回 JSON 輸出。參考 參考models/gemini-1.5-pro-latest
更改為models/gemini-1.5-flash-latest
。exportTotalTokens
匯出值已變更。在 v2.xx 之後,當這是 true 時,會匯出物件usageMetadata
包括promptTokenCount
、 candidatesTokenCount
、 totalTokenCount
。此時,產生的內容和usageMetadata
將作為物件傳回。v2.0.1(2024 年 8 月 4 日)
codeExecution
。參考號v2.0.2(2024 年 9 月 26 日)
generationConfig
的選項,新增了屬性response_schema
和temperature
。v2.0.3(2024 年 11 月 19 日)
setFileIdsOrUrlsWithResumableUpload
的規格。從v2.0.3開始,當您使用此方法時,請將propertiesService: PropertiesService.getScriptProperties()
包含到初始物件中,如下所示。因為,當在庫中使用PropertiesService.getScriptProperties()
時,值將被放入庫中。當我創建Ref和Ref時,我認為腳本是透過複製和貼上而不是庫來使用的。因此,我在腳本中包含了PropertiesService.getScriptProperties()
。但我注意到,與 GeminiWithFiles 一起使用時,每個使用者都需要使用PropertiesService.getScriptProperties()
。所以,我修改了這個。resumableUploadAsNewUpload: true
。 Ref 透過此操作,該屬性被清除並執行上傳。頂部