星期四, 9月 17, 2026

[GAS] Gemini API

在 GAS 內呼叫 Gemini 來進行應用,該筆記分兩部分
  • Google AI Studio 申請 API Key
  • 在 GAS 內透過 UrlFetchApp.fetch 呼叫 Gemini

申請 API Key

進入 Google AI Studio 建立 API Key,步驟依序為

Google AI Studio => MANAGE => Dashboard
PROJECT => API Keys
API Keys 內右上角 [Create API Key]
Create a new Key 頁面,專案選項可以在該畫面新增、選擇現有或是匯入
API Key Detail

呼叫 Gemini

重點
  • 官方文件-互動 API 內有使用模型可以參考,該範例是使用 gemini-3.8-flash
  • Gemini API 內有 response json 範例可以參考,看完後才能比較理解 getGeminiText() 內是在拆解什麼

官方 response json 範例
{
  "id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROBIXT1NBeGFhbTZBcEtpMWU4UGdOZW13UTg",
  "model": "gemini-3-flash-preview",
  "status": "completed",
  "object": "interaction",
  "created": "2025-11-26T12:25:15Z",
  "updated": "2025-11-26T12:25:15Z",
  "steps": [
    {
      "type": "model_output",
      "content": [
        {
          "type": "text",
          "text": "I'm doing great, thank you for asking! How can I help you today?"
        }
      ]
    }
  ]
}
code.gs
const GEMINI_MODEL = "gemini-3.8-flash";

/**
 * 呼叫 Gemini API
 *
 * @param {string} prompt 使用者輸入的問題
 * @return {string} Gemini 回覆
 */
function askGemini(prompt) {

  // 1. 取得 API Key
  const apiKey = PropertiesService
    .getScriptProperties()
    .getProperty("GEMINI_API_KEY");

  if (!apiKey) {
    throw new Error("找不到 GEMINI_API_KEY,請先設定 Script Properties。");
  }

  // 2. Gemini API URL
  const url = "https://generativelanguage.googleapis.com/v1beta/interactions";

  // 3. 要傳給 Gemini 的資料
  const payload = {
    model: GEMINI_MODEL,
    input: prompt
  };

  // 4. HTTP Request 設定
  const options = {
    method: "post",
    contentType: "application/json",

    headers: {
      "x-goog-api-key": apiKey
    },

    payload: JSON.stringify(payload),

    muteHttpExceptions: true
  };

  // 5. 呼叫 Gemini
  const response = UrlFetchApp.fetch(url, options);

  // 6. 取得 HTTP Status Code
  const statusCode = response.getResponseCode();

  // 7. 取得 JSON 字串
  const responseText = response.getContentText();

  // 8. API 發生錯誤
  if (statusCode < 200 || statusCode >= 300) {

    throw new Error(
      "Gemini API 呼叫失敗\n" +
      "HTTP Status: " + statusCode + "\n" +
      responseText
    );
  }

  // 9. JSON → JavaScript Object
  const data = JSON.parse(responseText);

  // 10. 取得 Gemini 回覆文字
  const result = getGeminiText(data);

  return result;
}


/**
 * 從 Gemini Interaction Response 取得文字
 */
function getGeminiText(data) {

  if (!data.steps) {
    throw new Error("Gemini Response 沒有 steps 資料。");
  }

  let result = [];

  data.steps.forEach(step => {

    if (step.type !== "model_output") {
      return;
    }

    if (!step.content) {
      return;
    }

    step.content.forEach(content => {
      if (content.type === "text" && content.text) {
        result.push(content.text);
      }
    });

  });

  if (result.length === 0) {
    throw new Error("Gemini 沒有回傳文字內容。");
  }

  return result.join("\n");
}
測試
/**
 * 測試 Gemini API
 */
function testGemini() {

  const prompt = "請用 100 個字介紹高雄。";

  const result = askGemini(prompt);

  console.log(result);
}

沒有留言:

張貼留言