iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0

5-2-1 GAS call Gemini API

https://ithelp.ithome.com.tw/upload/images/20240811/20046160AAtwPSAXPS.png
Google App Script 不是主要語言,所以不會在 Google AI Studio 看到以 Google Apps Script 的範例 code

但是因為 GAS 可以作為後端,而且大部分的情況之下都是免費的, 在我們要撰寫 LINE 聊天機器人需要一個後端解決方案, 又沒有預算的情況之下呢, 使用 GAS 是一個很好的解決方案。

Rest API

因為 Gemini API 非常新,而且不斷地在改進, 所以 LLMs 平台不會有他們的 code , 你直接叫LLMs寫, 通常只是胡謅。

一個好的方式就是我們先去找用 rest 呼叫的範例程式, 再請 LLMs 改寫成 GAS 。

直接改 https://aistudio.google.com/app/apikey 的範例

curl \
  -H 'Content-Type: application/json' \
  -d '{"contents":[{"parts":[{"text":"Explain how AI works"}]}]}' \
  -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY'

會回傳這個json

{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "## AI: From Simple to Complex\n\nArtificial Intelligence (AI) is a vast field encompassing various techniques and methods for creating intelligent machines. Understanding it requires breaking it down into different levels of complexity:\n\n**1.  Basic AI - Mimicking Human Actions:**\n\n* **Machine Learning (ML):**  This is the most common type of AI. It involves training computers to learn from data without explicit programming. \n    * **Supervised Learning:**  The computer learns from labeled data, like classifying images of cats and dogs.\n    * **Unsupervised Learning:**  The computer learns from unlabeled data, like clustering similar items together.\n    * **Reinforcement Learning:** The computer learns through trial and error, receiving rewards for desired actions.\n\n* **Expert Systems:**  These systems contain knowledge from experts in a specific domain, allowing them to solve problems and answer questions.\n\n**2.  Advanced AI - Towards Human-Level Intelligence:**\n\n* **Deep Learning (DL):** A subfield of ML using complex artificial neural networks with multiple layers. These networks can learn intricate patterns and relationships from large datasets, achieving high accuracy in tasks like image recognition, natural language processing, and speech recognition. \n\n* **Natural Language Processing (NLP):**  Enables computers to understand and process human language, allowing them to interact with us more naturally.  Examples include chatbots, text summarization, and language translation.\n\n* **Computer Vision:**  Allows computers to \"see\" and interpret images and videos, enabling applications like self-driving cars, facial recognition, and medical image analysis.\n\n**3.  The Future of AI - Approaching General Intelligence:**\n\n* **General AI (AGI):**  The hypothetical ability of a machine to understand and reason like a human, capable of performing any intellectual task that a human can. \n* **Superintelligence (ASI):** A hypothetical AI surpassing human intelligence in all aspects, posing potential risks and opportunities.\n\n**How AI Works in Practice:**\n\n1. **Data Collection:** Gather relevant data for training.\n2. **Data Preprocessing:** Clean, transform, and prepare the data for machine learning algorithms.\n3. **Model Selection:** Choose the appropriate algorithm for the task.\n4. **Model Training:**  Train the model on the prepared data.\n5. **Model Evaluation:** Test the model's performance and accuracy.\n6. **Deployment:**  Put the trained model into use for real-world applications.\n\n**Overall, AI works by:**\n\n* **Learning from data:**  AI systems learn from vast amounts of data, enabling them to improve their performance over time.\n* **Finding patterns:**  AI algorithms are designed to identify complex patterns and relationships in data.\n* **Making predictions:**  Based on learned patterns, AI systems can make predictions or decisions.\n\nWhile AI is still under development, it has already achieved significant progress in various fields, revolutionizing industries and impacting our lives. As AI continues to evolve, it will likely play an even larger role in our future.\n"
          }
        ],
        "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": 4,
    "candidatesTokenCount": 629,
    "totalTokenCount": 633
  }
}
以下改寫成 用GAS 呼叫
回傳 response 裡的 text

curl
-H 'Content-Type: application/json'
-d '{"contents":[{"parts":[{"text":"Explain how AI works"}]}]}'
-X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=YOUR_API_KEY'

response: '{"contents":[{"parts":[{"text":"Explain how AI works"}]}]}' -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=AIzaSyBeSmRdF2a1xvGNZHnC4ijSADeUqi20IVg'
{
"candidates": [
{
"content": {
"parts": [
{
"text": "## AI: From Simple to Complex\n\nArtificial Intelligence (AI) is a vast field encompassing various techniques and methods for creating intelligent machines. Understanding it requires breaking it down into different levels of complexity:\n\n1. Basic AI - Mimicking Human Actions:\n\n* Machine Learning (ML): This is the most common type of AI. It involves training computers to learn from data without explicit programming. \n * Supervised Learning: The computer learns from labeled data, like classifying images of cats and dogs.\n * Unsupervised Learning: The computer learns from unlabeled data, like clustering similar items together.\n * Reinforcement Learning: The computer learns through trial and error, receiving rewards for desired actions.\n\n* Expert Systems: These systems contain knowledge from experts in a specific domain, allowing them to solve problems and answer questions.\n\n2. Advanced AI - Towards Human-Level Intelligence:\n\n* Deep Learning (DL): A subfield of ML using complex artificial neural networks with multiple layers. These networks can learn intricate patterns and relationships from large datasets, achieving high accuracy in tasks like image recognition, natural language processing, and speech recognition. \n\n* Natural Language Processing (NLP): Enables computers to understand and process human language, allowing them to interact with us more naturally. Examples include chatbots, text summarization, and language translation.\n\n* Computer Vision: Allows computers to "see" and interpret images and videos, enabling applications like self-driving cars, facial recognition, and medical image analysis.\n\n3. The Future of AI - Approaching General Intelligence:\n\n* General AI (AGI): The hypothetical ability of a machine to understand and reason like a human, capable of performing any intellectual task that a human can. \n* Superintelligence (ASI): A hypothetical AI surpassing human intelligence in all aspects, posing potential risks and opportunities.\n\nHow AI Works in Practice:\n\n1. Data Collection: Gather relevant data for training.\n2. Data Preprocessing: Clean, transform, and prepare the data for machine learning algorithms.\n3. Model Selection: Choose the appropriate algorithm for the task.\n4. Model Training: Train the model on the prepared data.\n5. Model Evaluation: Test the model's performance and accuracy.\n6. Deployment: Put the trained model into use for real-world applications.\n\nOverall, AI works by:\n\n* Learning from data: AI systems learn from vast amounts of data, enabling them to improve their performance over time.\n* Finding patterns: AI algorithms are designed to identify complex patterns and relationships in data.\n* Making predictions: Based on learned patterns, AI systems can make predictions or decisions.\n\nWhile AI is still under development, it has already achieved significant progress in various fields, revolutionizing industries and impacting our lives. As AI continues to evolve, it will likely play an even larger role in our future.\n"
}
],
"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": 4,
"candidatesTokenCount": 629,
"totalTokenCount": 633
}
}

回應

以下是使用Google Apps Script (GAS) 呼叫API並回傳response中的text的程式碼:

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;
}

將上述程式碼複製到你的Google Apps Script編輯器中,替換YOUR_API_KEY為你的API金鑰,然後運行該函數callAI即可取得並打印response中的text。

測試

試著放上自己的 API key 看能不能正常呼叫


上一篇
5-1 前言
下一篇
5-2-2 GAS to be webhook of LINE bot
系列文
運用生成式 AI 服務 所提供的API 實做應用開發(以Gemini及ChatGPT為例)23
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言