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 用户来说会更加有利。这也将显着降低上传数据的成本。
我认为在上传的文件中包含自定义元数据的能力对于管理大量文件非常有用。
当我测试控制输出格式的函数调用时,有时会出现状态码500的错误。但是,当我测试response_mime_type
时,这样的错误很少发生。我不确定这是否是当前的规范。
顶部的抽象图像是由 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 通过此操作,该属性被清除并运行上传。顶部