Gemini API (Node.js) 開發環境安裝教學:在 VPS 上打造 AI 應用程式

GeminiGoogle AIGemini SDKNode.jsVPS安裝教學JavaScriptAI 應用開發Google Cloud

本文將引導你在 VPS 上的 Node.js 專案中安裝並設定 Google Gemini SDK,讓你可以輕鬆在應用程式中呼叫最強大的生成式 AI 模型。

為什麼選擇 Gemini API?

Gemini 是 Google 開發的高效能多模態模型,提供大容量的免費配額與極高的性能。在 侃瑞科技 VPS 上部署 Gemini 應用,能結合伺服器的穩定性與 AI 的強大智慧,實現自動客服、內容分析與代碼產生等功能。

步驟一:取得 Gemini API Key

  1. 登入 Google AI Studio
  2. 在左側選單點選「Get API Key」。
  3. 點選「Create API Key in new project」。
  4. 複製產生的金鑰,稍後會用到。

步驟二:在專案中安裝 SDK

進入你的專案目錄(如果還沒有專案,請先執行 npm init -y),然後安裝 @google/generative-ai 套件:

npm install @google/generative-ai

步驟三:撰寫測試程式碼

建立一個名為 index.js 的檔案,並填入以下內容來測試連線:

const { GoogleGenerativeAI } = require("@google/generative-ai");

const genAI = new GoogleGenerativeAI("YOUR_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

async function run() {
  const prompt = "請用一句話介紹侃瑞科技 VPS 的優點。";
  const result = await model.generateContent(prompt);
  console.log(result.response.text());
}

run();

步驟四:執行與驗證

在終端機執行:node index.js。如果看到對應的回應,代表你的 Gemini 開發環境已在 VPS 上成功運行!

常見問題

Q:為什麼回應顯示 Request Error?
這通常是因為 API Key 無效、配額已滿或是你的 VPS IP 被封鎖。請確認 API Key 是否正確,並到 Google AI Studio 檢查配額狀態。如果你在開發過程中需要高頻率呼叫,建議使用我們的 IP Transit 服務 以確保最穩定的網路路徑。

Q:如何保護我的 API Key?
切勿直接將 API Key 寫在程式碼中。建議安裝 dotenv 套件,將金鑰存放在 .env 檔案裡,並在執行時讀取環境變數。

需要主機來實作?

侃瑞科技提供 cPanel 虛擬主機與 VPS,教學裡的操作開箱即用。

查看方案 →
LINE 諮詢