iT邦幫忙

2024 iThome 鐵人賽

0
生成式 AI

運用生成式 AI 服務 所提供的API 實做應用開發(以Gemini及ChatGPT為例)系列 第 35

5-4 作為網站 web 呼叫 Gemini API 以 Google Apps Script 做為網站後端

  • 分享至 

  • xImage
  •  

5-4 作為網站 web 呼叫 Gemini API 以 Google Apps Script 做為網站後端

https://ithelp.ithome.com.tw/upload/images/20240811/20046160TbcyovjU05.png

為了避免跨網域呼叫問題,可以請 LLMs 將呼叫 Gemini API 的程式碼寫在後端。

由於發現直接輸入 REST 呼叫 Gemini API 及其 JSON 回應的內容會導致 LLMs 混亂,因此我們將任務拆解為兩個步驟:

  1. 先寫出檔案及內容
  2. 在套用去呼叫 Gemini API

Prompt

以下改寫成用 GAS 寫 html 呼叫
- 程式碼保持簡單
index.html 
- input : text
- button : call api
- response div
code.gs
- call api return "from code.gs"

回應

當然可以,這裡是一個簡單的範例,使用 Google Apps Script (GAS) 來創建一個 HTML 文件,包含一個文字輸入框、一個按鈕,並在按鈕點擊後調用 GAS 中的 API,然後在頁面上顯示返回結果。

index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <input type="text" id="inputText" placeholder="Enter text">
      <button onclick="callApi()">Call API</button>
    </div>
    <div id="responseDiv"></div>

    <script>
      function callApi() {
        const inputText = document.getElementById('inputText').value;

        google.script.run.withSuccessHandler(displayResponse).callApiFromHtml(inputText);
      }

      function displayResponse(response) {
        document.getElementById('responseDiv').innerText = response;
      }
    </script>
  </body>
</html>

code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}

function callApiFromHtml(inputText) {
  return "from code.gs: " + inputText;
}

步驟說明

  1. index.html:
    • 包含一個文本輸入框和一個按鈕。
    • 當按鈕被點擊時,JavaScript 函數 callApi 被調用,這個函數會抓取輸入框中的文本並調用 GAS 中的 callApiFromHtml 函數。
    • 使用 google.script.run.withSuccessHandler 方法來調用 GAS 函數,並在成功時執行 displayResponse 函數來顯示返回的結果。
  2. code.gs:
    • 包含 doGet 函數來提供 HTML 文件。
    • 包含 callApiFromHtml 函數,這個函數接收從 HTML 傳來的輸入文本並返回一個帶有 "from code.gs" 前綴的字符串。

這樣,當用戶在輸入框中輸入文本並點擊按鈕後,該文本會被傳遞到 GAS 函數並返回結果顯示在頁面上。

Prompt

callApiFromHtml 改成呼叫 下面的 callAI
function callAI() {
  var url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY';

  var payload = {
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works"
          }
        ]
      }
    ]
  };

  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(payload)
  };

  var response = UrlFetchApp.fetch(url, options);
  var json = JSON.parse(response.getContentText());

  // 提取text內容
  var text = json.candidates[0].content.parts[0].text;
  Logger.log(text);
  return text;
}

回應

好的,這裡是一個更新後的範例,將 callApiFromHtml 改為調用 callAI 函數,並在網頁上顯示 API 的返回結果。

index.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <input type="text" id="inputText" placeholder="Enter text">
      <button onclick="callApi()">Call API</button>
    </div>
    <div id="responseDiv"></div>

    <script>
      function callApi() {
        const inputText = document.getElementById('inputText').value;

        google.script.run.withSuccessHandler(displayResponse).callApiFromHtml(inputText);
      }

      function displayResponse(response) {
        document.getElementById('responseDiv').innerText = response;
      }
    </script>
  </body>
</html>

code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('index');
}

function callApiFromHtml(inputText) {
  return callAI(inputText);
}

function callAI(inputText) {
  var url = '<https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY>';

  var payload = {
    "contents": [
      {
        "parts": [
          {
            "text": inputText
          }
        ]
      }
    ]
  };

  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(payload)
  };

  var response = UrlFetchApp.fetch(url, options);
  var json = JSON.parse(response.getContentText());

  // 提取text內容
  var text = json.candidates[0].content.parts[0].text;
  Logger.log(text);
  return text;
}

說明

  1. index.html:
    • 當按下按鈕時,會將輸入框中的文本傳遞給 callApiFromHtml 函數。
    • callApiFromHtml 函數完成後,會調用 displayResponse 函數顯示結果。
  2. code.gs:
    • callApiFromHtml 函數接收從 HTML 傳來的文本並將其傳遞給 callAI 函數。
    • callAI 函數會構建 API 請求,將文本作為輸入並向指定的 API 發送請求。
    • 接收到的 API 響應解析後,提取出所需的文本並返回。

記得將 YOUR_API_KEY 替換為你實際的 API 金鑰。這樣,當用戶輸入文本並點擊按鈕後,會調用 callAI 函數,向 API 發送請求並顯示返回的結果。

關於我

我是 Wolke。我是一名專業程式開發者,專長是開發 AI 和程式解決方案。

我投入了不少時間在專業發展上。我是多本書的作者,其中包括《LINE聊天機器人+AI+雲端+開源+程式:輕鬆入門到完整學習》《ChatGPT來襲,未來人人都需具備的運算思維!應用詠唱工程來釋放程式生產力—程式學習/開發篇》。也有出版線上課程,我熱衷於分享我的經驗和技術,幫助其他開發者更好地利用 AI 工具。

也在許多知名大學、論壇、社團擔任講者,如果貴方有需要也歡迎與我聯繫。
2023年 講座 紀錄

最後這篇文章若有切合你的需求,敬請訂閱按讚分享


上一篇
5-3 Chrome Extension 呼叫 Gemini API
下一篇
9-1 深入了解 Assistants API
系列文
運用生成式 AI 服務 所提供的API 實做應用開發(以Gemini及ChatGPT為例)36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言