1. 事前準備
在本程式碼研究室中,您將瞭解如何運用 Gemini API 的函式呼叫和多模態功能,自動執行 Google Workspace 工作。
必要條件
- 對 Apps Script、JavaScript 或類似的程式設計語言有基本的瞭解
課程內容
- 如何運用 Gemini API 的函式呼叫和多模態功能。
- 如何將多個 Gemini API 呼叫串連在一起。
- 瞭解如何使用 Gemini API 自動執行 Google Workspace 工作。
需求條件
- 網路瀏覽器。
- Gmail 帳戶。或者,已實作 Gemini API 特定設定的 Google Workspace 帳戶。
- 從 支援的區域連線至 Gemini API。
- 選用:具有
curl程式的指令列介面,可測試直接 API 要求。
您可以在 GitHub 上的 Gemini API Cookbook 中找到本程式碼研究室的完整程式碼。如需完整程式碼,請查看這個頁面。
2. 設定 Gemini API
關於 Gemini
Gemini 模型是 Google 規模最大、功能最強大的 AI 模型系列。如要在應用程式中使用這些模型,請使用 Gemini API。您也可以在 Google AI Studio 中試用 Gemini API。這個 API 網頁介面可讓您試用提示、調整模型設定,以及微調自訂模型,完全不必編寫程式碼。
取得金鑰
- 如要使用 Gemini API,請在 Google AI Studio 建立 API 金鑰。
選用:測試金鑰
如果您可以使用 curl 存取指令列,請將金鑰加入下列程式碼區塊的第一行,然後在終端機中執行,測試 API 金鑰。
export GOOGLE_API_KEY=Paste_your_API_key_here
curl "https://generativelanguage.googleapis.com/v1beta/models?key=${GOOGLE_API_KEY}"
您應該會看到 JSON 格式的模型清單,例如 models/gemini-1.0-pro。這表示運作正常。
3. 選用:向 Gemini API 提出要求
在這個選用步驟中,您會向 Gemini API 提出要求,進一步瞭解內容生成方式,然後再將內容新增至 Apps Script 應用程式。
關於模型
Gemini API 提供多種模型,功能和限制各不相同。Gemini 模型頁面會列出所有模型及其功能。
發出第一項要求
如要讓 Gemini API 完成文字提示,請建構 JSON 要求並傳送至 REST API 端點。
步驟如下:
- 在新檔案中輸入下列 JSON 要求:
{
contents: [
{
parts: [
{ text: 'The most important aspects of a persuasive presentation are:' }
]
}
]
}
JSON 要求包含下列提示:The most important aspects of a persuasive presentation are:。模型會完成這項指令,並直接提供結果。
JSON 要求有三個頂層欄位需要填入:contents、generationConfig 和 safetySettings。只需要 contents。其他則提供控制輸出內容的機制。
- 將這個 JSON 儲存在
presentation.txt檔案中,然後直接傳遞至curl,如下所示:
curl -H 'Content-Type: application/json' -X POST -d @presentation.txt \
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-latest:generateContent?key='${GOOGLE_API_KEY}
在本範例中,您在網址中設定下列值:
v1beta會指定 API 版本。gemini-1.0-pro-latest將 Gemini 1.0 Pro 指定為模型,並使用最新快照。generateContent:指定您呼叫的 API 方法。
您應該會看到類似下方的結果:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "* **Credibility:** The audience must trust that you are an expert on the subject matter and that you have their best interests at heart.\n* **Clearness:** Your message must be easy to understand and follow. Avoid using jargon or technical terms that your audience may not be familiar with.\n* **Concreteness:** Use specific examples and data to support your arguments. Avoid making vague or general claims.\n* **Emotional appeal:** In addition to appealing to the audience's logical side, you should also try to connect with them on an emotional level. Use storytelling, humor, and personal anecdotes to make your points more memorable and engaging.\n* **Strong closing:** End your presentation with a strong call to action. Tell the audience what you want them to do and why it is important for them to do it."
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": [...]
}
],
"promptFeedback": {
"safetyRatings": [...]
}
}
為了方便閱讀,以下是經過一般格式化的終端機輸出內容:
- 可信度:觀眾必須相信你是該主題的專家,且會為他們著想。
- 清楚明瞭:訊息必須簡單易懂,且易於遵循。避免使用目標對象可能不熟悉的專業術語或技術用語。
- 具體性:使用具體範例和資料來支持論點。避免做出含糊不清或籠統的聲明。
- 訴諸情感:除了訴諸觀眾的邏輯思維,您也應嘗試與他們建立情感連結。運用說故事、幽默和個人軼事,讓重點更令人印象深刻且引人入勝。
- 強而有力的結尾:在簡報結尾加入強而有力的行動號召。告訴觀眾你希望他們採取什麼行動,以及這麼做的重要性。
如要進一步瞭解其他設定,包括 generationConfig 和 safetySettings,請參閱提示和安全指南。
4. 從 Apps Script 呼叫 Gemini API
- 前往 script.new,系統就會自動為您建立
code.gsApps Script 檔案。 - 將游標懸停在
code.gs檔案上,然後依序點選
>「重新命名」。 - 將檔案名稱變更為
utils.gs。 - 在檔案中移除
myFunction函式,讓檔案保持空白。
將 API 金鑰加進專案
- 在導覽選單中選取「專案設定」。
- 在「指令碼屬性」下方,按一下「新增指令碼屬性」。
- 在「Property」(屬性) 下方輸入
GOOGLE_API_KEY。 - 在「Value」(值) 下方,輸入從 Google AI Studio 取得的 API 金鑰。

- 按一下「儲存指令碼屬性」。
- 返回編輯器。
新增 Gemini API 程式碼
在 utils.gs 檔案中,請按照下列步驟操作:
設定 API 金鑰和端點:
const properties = PropertiesService.getScriptProperties().getProperties();
const geminiApiKey = properties['GOOGLE_API_KEY'];
const geminiEndpoint = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-latest:generateContent?key=${geminiApiKey}`;
- 新增下列函式,使用特定提示呼叫 Gemini API:
function callGemini(prompt, temperature=0) {
const payload = {
"contents": [
{
"parts": [
{
"text": prompt
},
]
}
],
"generationConfig": {
"temperature": temperature,
},
};
const options = {
'method' : 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(geminiEndpoint, options);
const data = JSON.parse(response);
const content = data["candidates"][0]["content"]["parts"][0]["text"];
return content;
}
- 新增下列函式來設定提示:
function testGemini() {
const prompt = "The best thing since sliced bread is";
const output = callGemini(prompt);
console.log(prompt, output);
}
測試
- 按一下
「儲存」。 - 在函式下拉式清單中選擇
testGemini,然後按一下
。 - 接受必要權限。程式碼應會執行,且執行記錄中會顯示一些控制台輸出內容和結果。

成功了!
5. 使用圖片呼叫 Gemini API
Gemini 系列模型最強大的功能之一,就是支援多模態輸入,也就是說,您不僅能提供文字,在本節中,您會新增函式,透過圖片呼叫 Gemini API。
- 在現有的
const geminiEndpoint宣告後方,於utils.gs檔案頂端新增下列程式碼:
const geminiProVisionEndpoint = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-vision-latest:generateContent?key=${geminiApiKey}`;
新增 Gemini Vision 程式碼
- 在
utils.gs檔案中新增函式,呼叫這個新加入的端點:
function callGeminiProVision(prompt, image, temperature=0) {
const imageData = Utilities.base64Encode(image.getAs('image/png').getBytes());
const payload = {
"contents": [
{
"parts": [
{
"text": prompt
},
{
"inlineData": {
"mimeType": "image/png",
"data": imageData
}
}
]
}
],
"generationConfig": {
"temperature": temperature,
},
};
const options = {
'method' : 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(geminiProVisionEndpoint, options);
const data = JSON.parse(response);
const content = data["candidates"][0]["content"]["parts"][0]["text"];
return content;
}
- 新增下列測試函式:
function testGeminiVision() {
const prompt = "Provide a fun fact about this object.";
const image = UrlFetchApp.fetch('https://storage.googleapis.com/generativeai-downloads/images/instrument.jpg').getBlob();
const output = callGeminiProVision(prompt, image);
console.log(prompt, output);
}
這個函式會從網際網路載入測試圖片,並傳遞至您定義的函式。稍後,您會將其連線至試算表中的圖表,因此這只是測試。
測試
- 儲存並執行
testGeminiVision函式,然後檢查輸出內容。

6. 使用工具呼叫 Gemini API
除了文字和圖片,您也可以在提示中提供工具的存取權。
新增工具處理程式碼
- 在
utils.gs檔案中新增函式,接受工具規格:
function callGeminiWithTools(prompt, tools, temperature=0) {
const payload = {
"contents": [
{
"parts": [
{
"text": prompt
},
]
}
],
"tools" : tools,
"generationConfig": {
"temperature": temperature,
},
};
const options = {
'method' : 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(geminiEndpoint, options);
const data = JSON.parse(response);
const content = data["candidates"][0]["content"]["parts"][0]["functionCall"];
return content;
}
如要進一步瞭解這個結構定義和可用欄位,請參閱 FunctionDeclaration API 參考資料。
測試
- 定義模型可用來尋找目前日期和時間的工具:
function testGeminiTools() {
const prompt = "Tell me how many days there are left in this month.";
const tools = {
"function_declarations": [
{
"name": "datetime",
"description": "Returns the current date and time as a formatted string.",
"parameters": {
"type": "string"
}
}
]
};
const output = callGeminiWithTools(prompt, tools);
console.log(prompt, output);
}
這裡使用的格式為 FunctionDeclaration 結構定義。您實際上不會呼叫日期時間函式。您只會收到模型要求函式呼叫的指標。您會在後續步驟中處理函式呼叫。
- 儲存並執行
testGeminiTools函式,查看輸出內容。

7. Google Workspace 整合服務的試用版總覽
瞭解函式呼叫的運作方式後,您就能輕鬆將 Gemini 模型的強大功能擴展至其他服務。在接下來幾個章節中,您將針對 Google 雲端硬碟、Google 簡報和 Google 試算表等 Google Workspace 產品建構整合功能。簡化圖表如下:

從高層次來看,當使用者提出查詢時,您可以使用 Gemini API 的函式呼叫功能,判斷要使用的工具。您會建構三項工具,分別可執行下列作業:
- 設定會議。圖表中的
setupMeeting()函式會呼叫 Gemini 1.0 Pro API,摘要 Google 雲端硬碟中的網誌內容,並將摘要新增至 Google 日曆中新建立的會議。 - 根據圖表洞察資料草擬電子郵件。圖表中的
draftEmail()函式會叫用 Gemini 1.0 Pro Vision,分析 Google 試算表中的圖表,並根據分析結果在 Gmail 中撰寫電子郵件。 - 建立簡報架構。圖表中的
createDeck()函式會叫用 Gemini 1.0 Pro,為 Google 簡報中的投影片集發想重點。
您需要為每項工具執行下列三件事:
- 判斷 Gemini API 的函式呼叫回應是否要求在
if...else區塊中叫用該特定工具。 - 新增實際函式,實作工具功能。
- 使用 Gemini API 宣告工具,讓 Gemini 模型知道工具的存在,並傳回正確的函式呼叫回覆。
8. 使用 Apps Script 安排會議
首先,您在 Google 日曆中自動設定會議,但也會新增說明,也就是 Google 雲端硬碟中檔案的摘要。
步驟如下:
- 下載這份文字檔,這是 Gemini 1.5 Pro 發布網誌的文字副本。
- 將檔案上傳至 Google 雲端硬碟的根資料夾。
- 在編輯器中建立
main.gs檔案,然後新增下列程式碼:
function main() {
const userQuery = "Set up a meeting at 10AM tomorrow with Helen to discuss the news in the Gemini-blog.txt file.";
var tool_use = callGeminiWithTools(userQuery, WORKSPACE_TOOLS);
Logger.log(tool_use);
if(tool_use['name'] == "setupMeeting") {
setupMeeting(tool_use['args']['time'], tool_use['args']['recipient'], tool_use['args']['filename']);
Logger.log("Your meeting has been set up.");
}
else
Logger.log("no proper tool found");
}
您可以在這裡叫用 Gemini API 的函式呼叫功能。接著,您需要定義工具函式。
- 在編輯器左側,按一下「服務」旁的「+ 新增服務」>「Google Calendar API」>「新增」。這會啟用進階 Google 日曆服務,您稍後需要使用這項服務才能存取部分進階 API。

- 在
utils.gs檔案中,新增下列程式碼:
function attachFileToMeeting(event, file, fileName) {
// Get the iCal ID for the event.
const iCalEventId = event.getId();
// Log the ID and title for debugging.
console.log(`iCal event ID: ${iCalEventId}`);
console.log(`event Title: ${event.getTitle()}`);
// Set up the options for listing the event with the advanced Google Calendar service.
const options = {
iCalUID: iCalEventId,
};
// Use the primary calendar as the calendar ID to list events.
const calendarId = 'primary';
// Use the advanced Google Calendar service to list the event.
const calEvents = Calendar.Events.list(calendarId, options);
// Get the Calendar ID used by the advanced Google Calendar service.
const eventId = calEvents.items[0].id;
// Get the file URL for the attachment.
const fileUrl = file.getUrl();
// Set up the patch options to add the file.
var patch = {
attachments: [{
'fileUrl': fileUrl,
'title': fileName
}]
};
// Patch the event to add the file as an attachment.
Calendar.Events.patch(patch, 'primary', eventId, {"supportsAttachments": true});
}
function setupMeeting(time, recipient, filename) {
const files = DriveApp.getFilesByName(filename);
const file = files.next();
const blogContent = file.getAs("text/*").getDataAsString();
var geminiOutput = callGemini("Give me a really short title of this blog and a summary with less than three sentences. Please return the result as a JSON with two fields: title and summary. \n" + blogContent);
// The Gemini model likes to enclose the JSON with ```json and ```
geminiOutput = JSON.parse(geminiOutput.replace(/```(?:json|)/g, ""));
const title = geminiOutput['title'];
const fileSummary = geminiOutput['summary'];
const event = CalendarApp.getDefaultCalendar().createEventFromDescription(`meet ${recipient} at ${time} to discuss "${title}"`);
event.setDescription(fileSummary);
attachFileToMeeting(event, file, filename);
}
這段程式碼會執行下列動作:
setupMeeting()函式會瀏覽 Google 雲端硬碟,找出Gemini-blog.txt檔案。這個檔案名稱會在步驟 3 中,由 Gemini API 的函式呼叫功能自動傳回。setupMeeting()函式會呼叫 Gemini API 來統整檔案內容,並使用任意形式的說明,透過 CalendarApp 設定會議,然後將摘要新增至會議。setupMeeting()函式會呼叫attachFileToMeeting()函式,使用進階 Google 日曆服務將網誌檔案附加至會議。
- 在
utils.gs檔案頂端新增下列程式碼:
const WORKSPACE_TOOLS = {
"function_declarations": [
{
"name": "setupMeeting",
"description": "Sets up a meeting in Google Calendar.",
"parameters": {
"type": "object",
"properties": {
"time": {
"type": "string",
"description": "The time of the meeting."
},
"recipient": {
"type": "string",
"description": "The name of the recipient."
},
"filename": {
"type": "string",
"description": "The name of the file."
},
},
"required": [
"time",
"recipient",
"filename"
]
}
},
// You add tools here.
]
};
- 在編輯器中返回
main.gs檔案,然後按一下
。 - 如果 Google Workspace 要求您授權執行指令碼,請按一下「確定」。
執行記錄會在幾秒內顯示訊息,通知您會議已設定完成。
- 在 Google 日曆中,找出含有摘要和附件的會議。

9. 使用 Apps Script 草擬電子郵件
接著,自動在 Gmail 中草擬電子郵件。假設您在 Google 試算表中進行資料分析,您將所有數字放在適當位置,然後建立圖表。您想使用 Gemini Pro Vision API,根據圖表草擬電子郵件。
步驟如下:
- 開啟這份試算表,然後依序點選「檔案」->「建立副本」。
- 在「複製文件」對話方塊的「名稱」文字方塊中,將預設名稱
Copy of CollegeExpenses替換為CollegeExpenses。 - 在
main.gs檔案中,將先前的使用者查詢替換為新的查詢,然後將下列程式碼新增至if...else陳述式:
function main() {
// const userQuery = "Set up a meeting at 5PM with Helen to discuss the news in the Gemini-1.5-blog.txt file.";
const userQuery = "Draft an email for Mary with insights from the chart in the CollegeExpenses sheet.";
if(...) {...}
// Add this code
else if(tool_use['name'] == "draftEmail") {
draftEmail(tool_use['args']['sheet_name'], tool_use['args']['recipient']);
Logger.log("Check your Gmail to review the draft");
}
else {...}
}
- 在
utils.gs檔案中,新增下列程式碼:
function draftEmail(sheet_name, recipient) {
const prompt = `Compose the email body for ${recipient} with your insights for this chart. Use information in this chart only and do not do historical comparisons. Be concise.`;
var files = DriveApp.getFilesByName(sheet_name);
var sheet = SpreadsheetApp.openById(files.next().getId()).getSheetByName("Sheet1");
var expenseChart = sheet.getCharts()[0];
var chartFile = DriveApp.createFile(expenseChart.getBlob().setName("ExpenseChart.png"));
var emailBody = callGeminiProVision(prompt, expenseChart);
GmailApp.createDraft(recipient+"@demo-email-provider.com", "College expenses", emailBody, {
attachments: [chartFile.getAs(MimeType.PNG)],
name: 'myname'
});
}
這個函式會從工作表擷取大學費用圖表,並傳送至 Gemini Pro Vision 來草擬電子郵件。Gemini Pro Vision 會從圖表擷取資訊,並代您草擬電子郵件內文。
- 在
utils.gs檔案中,將下列程式碼新增至You add tools here註解後的WORKSPACE_TOOLS物件:
WORKSPACE_TOOLS = {
"function_declarations": [
// You add tools here.
{
"name": "draftEmail",
"description": "Write an email by analyzing data or charts in a Google Sheets file.",
"parameters": {
"type": "object",
"properties": {
"sheet_name": {
"type": "string",
"description": "The name of the sheet to analyze."
},
"recipient": {
"type": "string",
"description": "The name of the recipient."
},
},
"required": [
"sheet_name",
"recipient"
]
}
},
]
};
- 在編輯器中返回
main.gs檔案,然後點選
。 - 10 到 20 秒後,開啟 Gmail。您應該會看到類似下方的電子郵件草稿:
你可以先修訂電子郵件草稿,然後再傳送。你提供簡短提示和圖表後,這封電子郵件就會完全由 Gemini Pro Vision 撰寫。
10. 使用 Apps Script 建立簡報架構
接著,您可以使用 Apps Script,自動在 Google 簡報中建立簡報架構。
步驟如下:
- 在
main.gs檔案中,將先前的使用者查詢換成新的查詢,並在if...else陳述式中新增下列程式碼:
function main() {
// const userQuery = "Draft an email for Mary with insights from the chart in the CollegeExpenses sheet.";
const userQuery = "Help me put together a deck about water conservation.";
if(...) {...}
// Add this code
else if(tool_use['name'] == 'createDeck') {
deckURL = createDeck(tool_use['args']['topic']);
Logger.log("Deck URL: " + deckURL);
}
else {...}
}
- 在
utils.gs檔案中,新增下列程式碼:
function createDeck(topic) {
const prompt = `I'm preparing a ${NUM_SLIDES}-slide deck to discuss ${topic}. Please help me brainstorm and generate main bullet points for each slide. Keep the title of each slide short. Please produce the result as a valid JSON so that I can pass it to other APIs.`;
var geminiOutput = callGemini(prompt, 0.4);
// The Gemini model likes to enclose the JSON with ```json and ```
geminiOutput = geminiOutput.replace(/```(?:json|)/g, "");
const bulletPoints = JSON.parse(geminiOutput);
// Create a Google Slides presentation.
const presentation = SlidesApp.create("My New Presentation");
// Set up the opening slide.
var slide = presentation.getSlides()[0];
var shapes = slide.getShapes();
shapes[0].getText().setText(topic);
var body;
for (var i = 0; i < NUM_SLIDES; i++) {
slide = presentation.appendSlide(SlidesApp.PredefinedLayout.TITLE_AND_BODY);
shapes = slide.getShapes();
// Set title.
shapes[0].getText().setText(bulletPoints['slides'][i]['title']);
// Set body.
body = "";
for (var j = 0; j < bulletPoints['slides'][i]['bullets'].length; j++) {
body += '* ' + bulletPoints['slides'][i]['bullets'][j] + '\n';
}
shapes[1].getText().setText(body);
}
return presentation.getUrl();
}
這個函式會呼叫 Gemini API,針對特定主題進行腦力激盪,並以格式傳回重點
的 JSON,然後使用 Apps Script 填入簡報範本。
- 在
utils.gs檔案中,將下列程式碼新增至You add tools here註解後的WORKSPACE_TOOLS物件:
WORKSPACE_TOOLS = {
"function_declarations": [
// You add tools here.
{
"name": "createDeck",
"description": "Build a simple presentation deck with Google Slides and return the URL.",
"parameters": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "The topic that the presentation is about."
},
},
"required": [
"topic"
]
}
},
]
};
- 在
utils.gs檔案頂端定義下列常數:
const NUM_SLIDES = 3;
這是 Gemini 模型除了開場投影片外,還會建立的投影片數量。
- 在編輯器中,返回
main.gs檔案,然後按一下
。幾秒後,執行記錄中就會顯示簡報網址。 - 使用瀏覽器開啟網址。畫面上應該會顯示填入項目符號的簡報架構。

11. 探索想法
除了上述三項整合功能,您還可以參考下列構想:
- 在 Google Chat 中建構聊天機器人。建構聊天機器人是大型語言模型 (LLM) 最常見的用途之一。透過 Gemini API,您可以輕鬆建構 Google Chat 專用的聊天機器人。詳情請參閱「Google Chat API」和程式碼實驗室「使用 Gemini 建構 Google Chat 應用程式」。
- 使用 Google 雲端硬碟或 Keep 中的資料進行檢索增強生成 (RAG)。在本程式碼研究室中,您只會使用單一文字檔進行摘要。不過,您也可以搭配使用 Gemini API、向量資料庫,以及 (選用) 協調工具 (例如 LangChain),從個人 Google 雲端硬碟和 Keep 取得內容 (例如記事、PDF 和圖片),進行 RAG 並根據您的資料調整模型回覆。
- 使用 Gemini API 的多輪函式呼叫功能。Gemini API 的函式呼叫不限於單一回合,您也可以多回合呼叫函式,處理更複雜的工作。
- 超越 Google Workspace。您現在已瞭解如何將 Gemini API 與 Google Workspace 整合,接下來可以超越 Google Workspace,運用其他 API。
12. 恭喜
您瞭解了 Gemini API 的多模態功能和函式呼叫。您曾使用這些函式,透過 Apps Script 自動執行部分 Google Workspace 工作!