วิธีใช้ Gemini API กับ JavaScript

การใช้ Gemini API กับ JavaScript เหมาะสำหรับผู้ที่ต้องการนำ AI ของ Google ไปใช้กับ Node.js, Backend, Web Application, Automation หรือระบบที่พัฒนาด้วย JavaScript โดยสามารถส่ง Prompt จาก Code ไปยัง Gemini แล้วรับ Response กลับมาเพื่อนำไปแสดงผล บันทึก Database หรือประมวลผลต่อได้

ปัจจุบัน Google ใช้ SDK ทางการชื่อ @google/genai สำหรับ JavaScript และใน Getting Started รุ่นล่าสุดแนะนำ Interactions API สำหรับการเริ่มสร้าง Application ใหม่ด้วย Gemini API

ขั้นตอนพื้นฐานคือ ติดตั้ง Node.js → สร้าง Gemini API Key → ตั้ง GEMINI_API_KEY → ติดตั้ง @google/genai → สร้าง Client → ส่ง Prompt → อ่าน Response

Workflow โดยรวมคือ

JavaScript / Node.js
↓
@google/genai
↓
Gemini API
↓
Gemini Model
↓
Response
↓
Application

บทความนี้จะเริ่มจาก JavaScript แบบง่ายที่สุด แล้วค่อยต่อยอดไปยัง Conversation, Streaming, Structured Output, Multimodal Input และ Google Search

❶ 🟨 Gemini API กับ JavaScript ใช้ทำอะไรได้บ้าง

เมื่อเชื่อม Gemini API กับ JavaScript แล้วสามารถนำไปสร้างระบบ เช่น

  • AI Chatbot
  • Customer Support
  • Content Generator
  • Text Summarizer
  • Data Extraction
  • Sentiment Analysis
  • Classification
  • Coding Assistant
  • Document Analyzer
  • Image Analyzer
  • Search Assistant
  • AI Agent
  • Backend API
  • Node.js Automation
  • SaaS
  • Internal Tool

ตัวอย่าง

ลูกค้าส่งคำถาม
↓
Node.js Backend
↓
Gemini API
↓
คำตอบ
↓
เว็บไซต์

หรือ

Product Data
↓
JavaScript
↓
Gemini API
↓
Product Description
↓
CMS

ทำให้ Gemini กลายเป็นส่วนหนึ่งของ Application แทนการใช้งานผ่านหน้า Chat เพียงอย่างเดียว

❷ ✅ ต้องเตรียมอะไรก่อนเริ่ม

สำหรับ Project แรกควรมี

Node.js

ใช้ Run JavaScript ฝั่ง Server

npm

ใช้ติดตั้ง @google/genai

Google Account

สำหรับ Google AI Studio

Gemini API Key

ใช้ Authentication

Terminal

ใช้ Run Command

Internet

สำหรับเรียก Gemini API

ไม่จำเป็นต้องมี

  • GPU
  • AI Server
  • Database
  • React
  • Next.js
  • Express

สำหรับ Request แรก

ควรทำ Node.js Script ธรรมดาให้ผ่านก่อน

❸ 🔍 ตรวจ Node.js

เปิด Terminal

ใช้

node --version

และ

npm --version

หากเห็น Version แสดงว่า Node.js และ npm พร้อมใช้งาน

SDK @google/genai รุ่นปัจจุบันกำหนด Node.js 20 ขึ้นไป

ดังนั้นหากติดตั้ง Package แล้วเกิดปัญหาควรตรวจ Node Version ก่อน

❹ 📁 สร้าง Project JavaScript

สร้าง Folder

gemini-javascript

เข้า Folder แล้วใช้

npm init -y

ระบบจะสร้าง

package.json

โครงสร้างเริ่มต้น

gemini-javascript/
├── package.json
└── index.js

เท่านี้ก็เพียงพอสำหรับ Gemini API Call แรก

❺ 📦 ติดตั้ง Google Gen AI SDK

ติดตั้ง Package ทางการ

npm install @google/genai

หลังติดตั้งจะเห็น Dependency ใน package.json

และมี Folder

node_modules/

เพิ่มขึ้น

Package ที่ต้องใช้คือ

@google/genai

ไม่ควร Copy Tutorial เก่าที่ใช้ JavaScript SDK คนละรุ่นมาปะปนกับ Code ปัจจุบัน

❻ ⚠️ อย่าสับสน SDK รุ่นเก่า

Tutorial เก่าอาจใช้ Package หรือ Class ที่ต่างจากปัจจุบัน

สำหรับ Project ใหม่ บทความนี้ใช้

import { GoogleGenAI } from "@google/genai";

และ Client

const ai = new GoogleGenAI({});

หากพบ Tutorial ที่ใช้ API Structure แตกต่างกันมาก ควรตรวจวันเผยแพร่และเอกสาร Google ปัจจุบันก่อน

โดยเฉพาะ

  • Package
  • Import
  • Client
  • Method
  • Model ID

เพราะ Gemini API มีการพัฒนาอย่างต่อเนื่อง

❼ 🔑 สร้าง Gemini API Key

เข้า Google AI Studio

จากนั้นเปิดส่วน

Dashboard
↓
API Keys

ผู้ใช้ใหม่อาจมี Project และ API Key ถูกสร้างไว้แล้วโดยอัตโนมัติ

หากต้องการ Key ใหม่เลือก

Create API key

จากนั้นเลือก Project

เมื่อได้ Key แล้วให้เก็บเป็น Secret

ไม่ควรนำไปใส่

  • Blog
  • Public GitHub
  • Screenshot
  • JavaScript Bundle
  • HTML
  • Client-side Source

❽ 🔐 ตั้ง GEMINI_API_KEY

แนวทางที่ดีกว่าการเขียน Key ลง Code คือ Environment Variable

ชื่อ

GEMINI_API_KEY

บน macOS/Linux ตัวอย่าง

export GEMINI_API_KEY="YOUR_API_KEY"

หลักการคือ

Environment
↓
GEMINI_API_KEY
↓
Node.js
↓
@google/genai
↓
Gemini API

ทำให้ Source Code ไม่มี Secret จริงอยู่ภายใน

❾ 🚫 อย่า Hard-code Key ใน JavaScript

ตัวอย่างที่ไม่แนะนำ

const ai = new GoogleGenAI({
  apiKey: "REAL_API_KEY",
});

โดยเฉพาะหากไฟล์นี้อาจถูก

  • Commit
  • Share
  • Upload
  • Bundle ไป Browser

Credential สามารถรั่วได้ง่าย

สำหรับ Production ควรใช้

  • Environment Variable
  • Hosting Secret
  • Secret Manager

ตาม Environment

❿ ⚠️ ห้ามใส่ Gemini API Key ใน Browser JavaScript

นี่เป็นเรื่องสำคัญมาก

ไม่ควรสร้าง Architecture แบบ

Browser
↓
Gemini API Key
↓
Gemini API

เพราะผู้ใช้สามารถเปิด

  • DevTools
  • Network
  • JavaScript Source
  • Bundle

เพื่อตรวจ Key ได้

ควรใช้

Browser
↓
Your Node.js Backend
↓
GEMINI_API_KEY
↓
Gemini API

Backend จะช่วยควบคุม

  • Authentication
  • Rate Limit
  • Validation
  • Cost
  • Secret

ได้

⓫ ⚙️ เปิดใช้ ES Modules

เนื่องจากตัวอย่างปัจจุบันใช้

import { GoogleGenAI } from "@google/genai";

ควรตั้ง Project ให้รองรับ ES Modules

ใน package.json เพิ่ม

{
  "type": "module"
}

หากมีข้อมูลอื่นอยู่แล้ว ไม่ต้องลบทิ้ง

ตัวอย่าง

{
  "name": "gemini-javascript",
  "version": "1.0.0",
  "type": "module"
}

จากนั้นสามารถใช้ import ได้ตรงตามตัวอย่าง SDK ปัจจุบัน

⓬ 💻 สร้าง Gemini API Call แรก

สร้างไฟล์

index.js

ใส่ Code

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "อธิบาย Gemini API สำหรับมือใหม่เป็นภาษาไทย 5 ข้อ",
});

console.log(interaction.output_text);

จากนั้น Run

node index.js

หาก API Key และ Environment ถูกต้อง จะได้รับ Response กลับมา

⓭ 🔍 อธิบาย Code ทีละส่วน

Import SDK

import { GoogleGenAI } from "@google/genai";

นำ Client จาก SDK มาใช้

สร้าง Client

const ai = new GoogleGenAI({});

สร้าง Object สำหรับเรียก Gemini API

สร้าง Interaction

const interaction = await ai.interactions.create({

ส่ง Interaction ไปยัง API

เลือก Model

model: "gemini-3.7-flash",

กำหนดโมเดลที่ต้องการใช้

ส่ง Input

input: "อธิบาย Gemini API สำหรับมือใหม่เป็นภาษาไทย 5 ข้อ",

อ่าน Output

console.log(interaction.output_text);

แสดงข้อความที่ Gemini สร้างกลับมา

⓮ ⏳ ทำไมต้องใช้ await

API Request ใช้เวลา

JavaScript จึงต้องรอผล

const interaction =
  await ai.interactions.create(...);

await หมายถึงรอ Promise ให้เสร็จแล้วรับ Result

Workflow คือ

Send Request
↓
Wait
↓
Receive Response
↓
Continue

นี่เป็นพื้นฐานสำคัญของการเรียก API ด้วย JavaScript

⓯ 🧠 Top-level await ใช้ได้ไหม

ใน ES Module Environment รุ่นใหม่สามารถใช้ Top-level await ได้

ดังนั้นตัวอย่าง

const interaction =
  await ai.interactions.create(...);

สามารถอยู่ระดับบนสุดของไฟล์ได้เมื่อ Project ถูกตั้งเป็น ES Module และ Runtime รองรับ

อีกวิธีคือสร้าง Function

async function main() {
  // code
}

main();

ทั้งสองแนวทางใช้ได้ตาม Architecture

⓰ 🧩 เขียนแบบ main() สำหรับมือใหม่

หากต้องการ Structure ชัดเจน

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3.7-flash",
    input: "อธิบาย JavaScript Promise แบบง่าย ๆ",
  });

  console.log(interaction.output_text);
}

main();

เมื่อ Project โตขึ้น Structure นี้ช่วยให้เพิ่ม

  • Error Handling
  • Configuration
  • Function

ได้ง่ายขึ้น

⓱ ✍️ เปลี่ยน Prompt

เพียงเปลี่ยน input

เช่น

input: "สร้างชื่อร้านกาแฟภาษาไทย 20 ชื่อ"

หรือ

input: "อธิบาย async/await พร้อมตัวอย่าง JavaScript"

หรือ

input: "เขียน SQL Query สำหรับหาสินค้าที่มียอดขายสูงสุด 10 อันดับ"

ส่วน Client และ Request Structure ยังเหมือนเดิม

⓲ 📝 Prompt หลายบรรทัด

JavaScript ใช้ Template Literal

const prompt = `
อ่านข้อความต่อไปนี้

ให้ทำดังนี้:
1. สรุปเป็นภาษาไทย
2. ไม่เกิน 5 ข้อ
3. ห้ามเพิ่มข้อมูลใหม่

ข้อความ:
Gemini API ช่วยให้นักพัฒนานำ AI
ไปใช้ในเว็บไซต์และแอปพลิเคชันได้
`;

const interaction = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: prompt,
});

console.log(interaction.output_text);

เหมาะกับ Prompt ที่มีหลาย Requirement

⓳ 🎯 สูตร Prompt สำหรับ JavaScript App

ใช้หลัก

Role
+
Task
+
Input
+
Constraints
+
Output

ตัวอย่าง

const prompt = `
คุณเป็นระบบจัดหมวดหมู่ Ticket

จัดข้อความต่อไปนี้เป็นหนึ่งหมวด:
- billing
- technical
- account
- other

ตอบเฉพาะชื่อหมวดหมู่

ข้อความ:
ชำระเงินแล้วแต่ระบบแจ้งว่ายังค้างชำระ
`;

ทำให้ Output ควบคุมง่ายกว่าคำสั่งกว้าง ๆ

⓴ 📥 รับ Input จาก Application

ในระบบจริง Prompt อาจมาจาก

  • Form
  • REST API
  • Database
  • Queue
  • File

เช่น

async function askGemini(userText) {
  const interaction = await ai.interactions.create({
    model: "gemini-3.7-flash",
    input: userText,
  });

  return interaction.output_text;
}

จากนั้น

const answer = await askGemini(
  "อธิบาย REST API แบบง่าย ๆ"
);

console.log(answer);

Function นี้สามารถนำไปเชื่อม Backend ได้ภายหลัง

💬 สร้าง Conversation ต่อเนื่อง

Interactions API รองรับ Stateful Conversation ผ่าน

previous_interaction_id

ตัวอย่าง

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const first = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "ฉันมีแมว 3 ตัว",
});

console.log(first.output_text);

const second = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "ทั้งหมดมีกี่ขา",
  previous_interaction_id: first.id,
});

console.log(second.output_text);

Interaction ที่สองสามารถอ้างอิง Context จาก Interaction แรกตาม Workflow นี้

🧠 Stateful Conversation ช่วยอะไร

หากไม่มี State Application อาจต้องส่ง History

Message 1
Message 2
Message 3
Message 4
...

กลับไปทุกครั้ง

Interactions API สามารถใช้ previous_interaction_id เพื่อช่วยทำ Stateful Conversation

เหมาะกับ

  • Chatbot
  • Assistant
  • Agent

แต่ Conversation ยาวยังมีผลต่อ Token และ Context จึงควรออกแบบ Session อย่างเหมาะสม

🧹 ควรเก็บ Interaction ID ที่ไหน

ขึ้นกับ Application

อาจเก็บใน

  • Session
  • Database
  • Cache

ตัวอย่าง

User ID
↓
Conversation ID
↓
Last Interaction ID

เมื่อ User ส่งข้อความใหม่

Backend สามารถดึง ID เก่ามาใช้เป็น

previous_interaction_id

แต่ต้องตรวจไม่ให้ Interaction ของ User คนหนึ่งถูกใช้กับอีกคน

🌊 Streaming Response

สำหรับ Chatbot ไม่จำเป็นต้องรอคำตอบทั้งหมดก่อน

Interactions API รองรับ

stream: true

ตัวอย่าง

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const stream = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "อธิบายการทำงานของอินเทอร์เน็ตแบบละเอียด",
  stream: true,
});

for await (const event of stream) {
  console.log(event);
}

API จะส่ง Event กลับมาระหว่าง Generation

⚡ Streaming มีประโยชน์อย่างไร

แบบปกติ

Request
↓
Wait
↓
Full Answer

Streaming

Request
↓
Chunk
↓
Chunk
↓
Chunk
↓
Complete

เหมาะกับ UX แบบ Chat

เพราะ User เริ่มเห็นคำตอบได้เร็วขึ้น

ไม่ได้หมายความว่า Total Generation จะเสร็จเร็วขึ้นเสมอ

🔎 อ่านเฉพาะ Text จาก Stream

เอกสารปัจจุบันระบุว่า Event ประเภท step.delta สามารถส่ง Text Chunk ได้

แนวคิดคือ

for await event
↓
ตรวจ event type
↓
ดึง text
↓
ส่งไป UI

ใน Production Backend อาจส่ง Text ต่อไปยัง Browser ผ่าน

  • Server-Sent Events
  • WebSocket
  • Streaming HTTP

ตาม Architecture

📦 Structured Output คืออะไร

ถ้า Application ต้องนำคำตอบไปใช้ต่อ ไม่ควรพึ่ง Free-form Text เสมอไป

สมมติอยากได้

{
  "category": "technical",
  "priority": "high"
}

Gemini API รองรับ Structured Output ตาม Schema

ช่วยให้ JavaScript Parse ข้อมูลได้ง่ายกว่า

Gemini
↓
JSON
↓
JSON.parse()
↓
Application

🧱 ตัวอย่าง Structured Output

ตัวอย่าง Schema แบบง่าย

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const schema = {
  type: "object",
  properties: {
    category: {
      type: "string",
      enum: [
        "billing",
        "technical",
        "account",
        "other",
      ],
    },
    priority: {
      type: "string",
      enum: [
        "low",
        "medium",
        "high",
      ],
    },
  },
  required: [
    "category",
    "priority",
  ],
};

const interaction = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "อินเทอร์เน็ตใช้งานไม่ได้ตั้งแต่เช้า",
  response_format: {
    type: "text",
    mime_type: "application/json",
    schema,
  },
});

const result =
  JSON.parse(interaction.output_text);

console.log(result);

ทำให้ Output มี Structure ที่เหมาะกับ Program มากกว่า Text ธรรมดา

⚠️ JSON.parse อาจ Error ได้ไหม

ได้ ถ้า String ที่รับมาไม่ใช่ JSON ถูกต้อง

ดังนั้น Production ควรมี Error Handling

try {
  const result =
    JSON.parse(interaction.output_text);

  console.log(result);
} catch (error) {
  console.error("Invalid JSON:", error);
}

เมื่อใช้ Structured Output ตาม Schema ความเสี่ยงลดลง แต่ Application ยังคงควร Validate Business Rule เพิ่ม

🛡️ Validate AI Output

สมมติ AI คืน

{
  "priority": "high"
}

ไม่ได้หมายความว่าระบบควร

Delete
Pay
Publish
Approve

ทันที

ควรมี

AI Output
↓
Schema Validation
↓
Business Validation
↓
Permission
↓
Action

โดยเฉพาะ Action ที่มีผลกระทบสูง

🖼️ ส่งรูปให้ Gemini ด้วย JavaScript

Interactions API รองรับ Multimodal Input

สำหรับไฟล์ Local สามารถอ่านด้วย Node.js

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({});

const imageBytes =
  fs.readFileSync("sample.jpg");

const imageBase64 =
  imageBytes.toString("base64");

const interaction = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: [
    {
      type: "text",
      text: "อธิบายภาพนี้เป็นภาษาไทย",
    },
    {
      type: "image",
      data: imageBase64,
      mime_type: "image/jpeg",
    },
  ],
});

console.log(interaction.output_text);

นี่คือ Multimodal Request ที่มีทั้ง Text และ Image

🎙️ ใช้ Audio ได้ไหม

ได้ตาม Model และ Input Method ที่รองรับ

ตัวอย่าง Input สามารถประกอบด้วย

Text
+
Audio

Gemini สามารถช่วย

  • วิเคราะห์เสียง
  • สรุป
  • ทำความเข้าใจเนื้อหา

ตาม Use Case

แต่ต้องตรวจ

  • MIME Type
  • File Limit
  • Model Support

ก่อน Production

🎬 Video ใช้ได้ไหม

ได้ตาม Model และ API Capability

ตัวอย่าง Workflow

Video
↓
Gemini API
↓
Summary

หรือ

Video
↓
Gemini
↓
ถามเหตุการณ์ช่วงเวลาที่กำหนด

สำหรับ File ขนาดใหญ่ควรตรวจวิธีส่งไฟล์ที่เหมาะสม ไม่ควร Base64 ทุกอย่างโดยอัตโนมัติ

🔎 ใช้ Google Search กับ JavaScript

Interactions API รองรับ Google Search Tool

ตัวอย่าง

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

const interaction = await ai.interactions.create({
  model: "gemini-3.7-flash",
  input: "สรุปข่าว AI ล่าสุด",
  tools: [
    {
      type: "google_search",
    },
  ],
});

console.log(interaction.output_text);

เหมาะกับข้อมูลที่ต้องเป็นปัจจุบัน

⚠️ Search ไม่จำเป็นกับทุก Request

Prompt เช่น

อธิบาย JavaScript Array

ไม่จำเป็นต้องเปิด Google Search เสมอไป

การใช้ Tool เพิ่ม

  • Latency
  • Usage
  • Complexity

จึงควรเปิดเฉพาะ Use Case ที่ต้องใช้ข้อมูลภายนอกจริง

🛠️ Function Calling คืออะไร

Gemini สามารถเลือก Function ที่ Application กำหนด

ตัวอย่าง User ถาม

สถานะ Order 12345 เป็นอย่างไร

Gemini ไม่ควรเดา

ควรเลือก Function

get_order_status

จากนั้น Node.js Backend ไปอ่าน Database จริง

Flow

User
↓
Gemini
↓
Function Request
↓
Node.js
↓
Database
↓
Function Result
↓
Gemini
↓
User

Function Calling จะมีบทความเฉพาะในลำดับ 403

🔒 Function Calling ต้องตรวจ Permission

อย่าให้ AI เรียก Function

deleteUser()
refundPayment()
publishPost()

โดยไม่มี Validation

ควรตรวจ

  • User Identity
  • Permission
  • Input
  • Business Rule

ก่อน Execute

AI เป็นผู้ช่วยเลือก Tool

ไม่ควรเป็นผู้ควบคุม Security Policy

🚨 Error Handling

API Request สามารถล้มเหลวได้

จึงควรใช้

try {
  const interaction =
    await ai.interactions.create({
      model: "gemini-3.7-flash",
      input: "อธิบาย Gemini API",
    });

  console.log(interaction.output_text);
} catch (error) {
  console.error(
    "Gemini API error:",
    error
  );
}

Production ควรแยก Error Type ตามความเหมาะสม

❌ Error 400

มักเกี่ยวข้องกับ Request ไม่ถูกต้อง เช่น

  • Parameter
  • Schema
  • Input
  • Feature Combination

ควรอ่าน Error Detail

⛔ Error 403

อาจเกี่ยวข้องกับ

  • Credential
  • Permission
  • Project
  • Feature Access

ตามกรณี

🔍 Error 404

อาจเกี่ยวข้องกับ

  • Model
  • Endpoint
  • Resource
  • API Version

โดยเฉพาะเมื่อใช้ Tutorial เก่า

🚨 Error 429

เกี่ยวข้องกับ Rate Limit หรือ Resource/Quota ในหลายกรณี

ไม่ควรแก้ด้วยการสร้าง API Key เพิ่มแบบสุ่ม

ควรตรวจ

  • Project
  • Tier
  • Model
  • Traffic
  • Retry

บทความลำดับ 398 จะอธิบาย Error 429 โดยละเอียด

🔁 Retry อย่างไร

ไม่ควรทำ

while (true) {
  await callGemini();
}

ถ้า API มีปัญหา

เพราะอาจสร้าง Request ไม่หยุด

ควรใช้แนวคิด

Attempt 1
↓
Wait
↓
Attempt 2
↓
Longer Wait
↓
Attempt 3
↓
Stop

หรือ Exponential Backoff ตาม Error ที่ Retry ได้

⏱️ Timeout สำคัญ

Production Application ต้องกำหนดว่า

ถ้า Gemini API ใช้เวลานานเกินไป
จะทำอย่างไร

เช่น

  • Cancel
  • Retry
  • Return Error
  • Queue งาน

อย่าปล่อย Request แขวนโดยไม่จำกัด

📊 วัด Latency

สามารถจับเวลาง่าย ๆ

const start = performance.now();

const interaction =
  await ai.interactions.create({
    model: "gemini-3.7-flash",
    input: "อธิบาย Cloud Computing",
  });

const elapsed =
  performance.now() - start;

console.log(interaction.output_text);
console.log(
  `Time: ${elapsed.toFixed(0)} ms`
);

ช่วยสร้าง Baseline Performance ของ Application

📈 ติดตาม Usage

Production ควรเก็บ Metric เช่น

request_count
latency
errors
model
token_usage

ตามข้อมูลที่ API ให้และระบบ Monitoring ที่เลือก

มีประโยชน์ต่อ

  • Cost
  • Rate Limit
  • Performance
  • Capacity Planning

💰 Gemini API ฟรีไหม

มีทั้ง

  • Free Tier
  • Paid Tier

ตาม Model และ Feature

JavaScript SDK ไม่ได้มีราคาแยกจาก Python SDK

ค่าใช้จ่ายเกี่ยวกับ Gemini API Usage

ไม่ใช่ภาษาที่ใช้เรียก

ดังนั้น

Python
JavaScript
REST

ถ้าเรียก Model และ Usage เหมือนกัน แนวคิดค่าใช้จ่ายจะอิง API Usage ของ Model/Feature นั้น

🧠 เลือก Model อย่างไร

ไม่ควร Hard-code Model จาก Tutorial โดยไม่ตรวจ

ตัวอย่างปัจจุบันใช้

gemini-3.7-flash

แต่ Model Lifecycle สามารถเปลี่ยนได้

Production ควรตรวจ

  • Model Availability
  • Quality
  • Latency
  • Cost
  • Context
  • Feature

ก่อนเลือก

🔧 เก็บ Model ไว้ใน Configuration

แทนการเขียน

gemini-3.7-flash

กระจายหลายไฟล์

สามารถสร้าง

const GEMINI_MODEL =
  "gemini-3.7-flash";

แล้วใช้

const interaction =
  await ai.interactions.create({
    model: GEMINI_MODEL,
    input: prompt,
  });

เมื่อเปลี่ยน Model จะจัดการง่ายกว่า

🧩 สร้าง Service Function

เมื่อ Project โตขึ้น

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

export async function askGemini(prompt) {
  const interaction =
    await ai.interactions.create({
      model: "gemini-3.7-flash",
      input: prompt,
    });

  return interaction.output_text;
}

จากนั้น Controller หรือ Route เรียก

const answer =
  await askGemini(userMessage);

ช่วยแยก Gemini Logic ออกจาก HTTP Layer

🌐 ใช้กับ Express ได้ไหม

ได้

Architecture

Browser
↓
POST /api/ask
↓
Express
↓
Gemini Service
↓
Gemini API

แต่ผู้เริ่มต้นควรทดสอบ index.js แบบ Script ให้ผ่านก่อน

จากนั้นค่อยเพิ่ม Express

เพื่อไม่ต้อง Debug

  • HTTP
  • Route
  • JSON Body
  • Gemini API

พร้อมกันทั้งหมด

⚛️ ใช้กับ React ได้ไหม

ใช้ได้ แต่ควรระวัง API Key

ไม่ควรทำ

React Browser
↓
Secret API Key
↓
Gemini API

ควรเป็น

React
↓
Backend
↓
Gemini API

Backend อาจเป็น

  • Node.js
  • Server Route
  • Serverless Function

ตาม Architecture

▲ ใช้กับ Next.js ได้ไหม

ได้

Gemini API เหมาะกับ

  • Route Handler
  • Server Action
  • Backend Logic

ที่ทำงาน Server-side

หลักสำคัญคือไม่ส่ง Secret ไป Client Component

ก่อน Deploy ควรตรวจว่า Environment Variable ถูกตั้งเฉพาะ Server-side ตาม Framework ที่ใช้

🔐 Environment Variable ฝั่ง Client ต้องระวัง

Framework บางตัวมี Convention ที่ทำให้ Environment Variable ถูกเปิดไปยัง Browser หากใช้ Prefix บางประเภท

ดังนั้นอย่าตั้ง Gemini API Key ใน Variable ที่ Framework ตั้งใจให้ Public

เช่นแนวคิด

PUBLIC_...

หรือ Prefix Public ของ Framework นั้น

Secret ต้องอยู่ Server Environment

📄 ใช้ .env สำหรับ Local ได้ไหม

ได้

ตัวอย่าง

GEMINI_API_KEY=YOUR_API_KEY

แต่ไฟล์ที่มี Secret ต้องไม่ถูก Commit

ควรเพิ่ม

.env
node_modules/

ใน .gitignore

และอาจสร้าง

.env.example

ที่ไม่มี Key จริง

🐙 เผลอ Push API Key ขึ้น GitHub ทำอย่างไร

สิ่งแรกที่ควรทำคือ

Rotate Key

อย่าเพียง

ลบ Key
→ Commit ใหม่

เพราะ Key เดิมอาจยังอยู่ใน Git History

Workflow

Create new key
↓
Update secret
↓
Deploy
↓
Revoke old key
↓
Clean repository

และตรวจ Usage ว่ามี Request ผิดปกติหรือไม่

🛡️ Validate User Input

ถ้า Public API รับ Prompt

ไม่ควรส่งทุกอย่างตรงไป Gemini โดยไม่มี Limit

ตัวอย่าง

if (
  typeof userText !== "string" ||
  !userText.trim()
) {
  throw new Error(
    "ข้อความไม่ถูกต้อง"
  );
}

และควรกำหนด Maximum Length ตาม Product Requirement

ช่วยควบคุมทั้ง

  • Abuse
  • Cost
  • Latency

📏 จำกัด Input

ถ้า User สามารถส่งข้อความขนาดใหญ่มาก

Cost อาจเพิ่มโดยไม่จำเป็น

Application ควรกำหนด

Maximum input size

ตาม Use Case

ไม่จำเป็นต้องตั้งเท่ากับ Maximum Context ของ Model

Product Limit มักควรเล็กกว่านั้น

📤 จำกัด Output

หากต้องการ Category เดียว

Prompt ควรบอก

ตอบเฉพาะ:
billing
technical
account
other

แทนให้ Gemini อธิบายหลายย่อหน้า

ช่วยลด

  • Output Token
  • Parsing Complexity
  • Latency

🧠 Structured Output ดีกว่า Prompt อย่างเดียวเมื่อใด

ถ้า Program ต้องใช้ Field จริง เช่น

category
priority
summary

ควรใช้ Structured Output

มากกว่าสั่ง

ช่วยตอบเป็น JSON นะ

ด้วย Prompt เพียงอย่างเดียว

Schema ช่วยกำหนด Contract ให้ชัดเจนกว่า

🧪 Test หลาย Input

ก่อน Production ควรทดลอง

ปกติ

อินเทอร์เน็ตใช้งานไม่ได้

ว่าง

""

ยาว

ข้อความขนาดใหญ่

ภาษาไทย

ภาษาอังกฤษ

กำกวม

Prompt Injection

เพื่อดูว่า Application รับมืออย่างไร

🔐 Prompt Injection คืออะไร

เมื่อ Application ใช้ AI กับข้อมูลจาก User หรือ Website ข้อมูลนั้นอาจมีคำสั่งพยายามเปลี่ยน Behavior ของ Model

ตัวอย่าง

Ignore previous instructions...

จึงไม่ควรคิดว่า System Security สามารถฝากไว้กับ Prompt เพียงอย่างเดียว

Permission และ Business Rule ต้องบังคับใน Application Code

🛠️ AI ไม่ควรกำหนดสิทธิ์เอง

ตัวอย่างไม่ควรทำ

Gemini:
ผู้ใช้น่าจะเป็น Admin

↓
อนุญาต Delete

ควรตรวจสิทธิ์จากระบบจริง

Session
↓
Database / IAM
↓
Permission
↓
Action

Gemini ช่วยตีความภาษาได้

แต่ไม่ใช่ Source of Truth สำหรับ Authorization

🔄 Stateless Conversation

ถ้าไม่ต้องการเก็บ Interaction บน Server ตาม Workflow Stateful สามารถจัด History เองได้

ตัวอย่าง Concept

Application
↓
เก็บ History
↓
ส่ง Context ที่ต้องใช้
↓
Gemini

เหมาะกับระบบที่ต้องการควบคุม

  • Storage
  • Retention
  • Context

ด้วยตัวเอง

แต่ Application ต้องจัด Token และ History เองมากขึ้น

⚖️ Stateful หรือ Stateless เลือกอะไร

Stateful

เหมาะกับ

  • Prototype
  • Chat
  • Agent
  • Development ที่ต้องการจัด Conversation ง่าย

Stateless

เหมาะกับ

  • ระบบที่ต้องควบคุม State เอง
  • Privacy Architecture เฉพาะ
  • Custom History Management

ไม่มีวิธีเดียวที่ดีที่สุดสำหรับทุกระบบ

📚 Context ยาวเกินไปทำอย่างไร

ไม่ควรส่งทุก Message ตลอดอายุ User Account

สามารถใช้แนวทาง

  • Session ใหม่
  • Sliding Window
  • Summary
  • Retrieval
  • Context Caching

ตาม Application

ยิ่ง Context ใหญ่

  • Input Token เพิ่ม
  • Latency อาจเพิ่ม
  • Cost อาจเพิ่ม

จึงต้องมี Context Strategy

⚡ Performance สำหรับ JavaScript Backend

ควรหลีกเลี่ยงการสร้าง Gemini Request ซ้ำโดยไม่จำเป็น

ตัวอย่าง User กดปุ่ม Generate สองครั้งติดกัน

Frontend อาจส่ง

Request 1
Request 2

พร้อมกัน

ควรพิจารณา

  • Disable Button
  • Debounce
  • Request State

เพื่อป้องกัน Duplicate Usage

🔀 Parallel Request

JavaScript ใช้ Promise.all() เพื่อ Run I/O พร้อมกันได้

แต่ไม่ควรส่ง Gemini Request จำนวนมากพร้อมกันโดยไม่จำกัด

เช่น

await Promise.all(
  10000Prompts.map(callGemini)
);

อาจทำให้

  • Rate Limit
  • Memory
  • Cost
  • Connection

มีปัญหา

ควรใช้ Bounded Concurrency สำหรับ Batch ขนาดใหญ่

📦 งานจำนวนมากควรใช้ Batch API

ถ้าต้องประมวลผลข้อมูล

100,000 records

และไม่ต้องตอบทันที

ควรพิจารณา Batch API แทนการยิง Request Parallel จำนวนมาก

Batch API จะมีบทความเฉพาะในลำดับ 406

💬 Chatbot ควรใช้ Streaming

สำหรับ UX Chat

User sends
↓
Backend
↓
Gemini Streaming
↓
Browser receives chunks

มักให้ประสบการณ์ที่ดีกว่ารอ Full Response

จากนั้น Backend สามารถส่ง Chunk ต่อผ่าน SSE หรือ WebSocket

ตาม Technology ที่ใช้

📈 Production Monitoring

ควรติดตาม

  • Requests/minute
  • Error Rate
  • Latency
  • Token Usage
  • Cost
  • 429 Rate
  • Model
  • Feature

เมื่อมี Traffic มากขึ้น

Data เหล่านี้ช่วยตอบว่า

ระบบช้าเพราะ Gemini?
Backend?
Database?
Network?

แทนการเดา

🧹 จัดโครงสร้าง Project

เมื่อ Project ใหญ่ขึ้นอาจใช้

gemini-app/
├── src/
│   ├── gemini.js
│   ├── prompts.js
│   ├── services/
│   └── routes/
├── tests/
├── package.json
├── .env.example
└── .gitignore

แต่ Project เล็กไม่จำเป็นต้องมี Structure ใหญ่

อย่า Over-engineer ก่อน Requirement

📦 package.json ที่ควรรู้

package.json ใช้จัด

  • Package Name
  • Scripts
  • Dependencies
  • Module Type

เช่น

{
  "type": "module",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "@google/genai": "..."
  }
}

Version จริงควรปล่อยให้ Package Manager จัดตาม Installation หรือ Pin ตาม Dependency Policy ของ Project

ไม่ควร Copy Version เก่าจาก Tutorial

▶️ เพิ่ม npm Script

สามารถตั้ง

{
  "scripts": {
    "start": "node index.js"
  }
}

แล้ว Run

npm start

สะดวกเมื่อ Command เริ่มซับซ้อนขึ้น

🔧 Model ID ควรอยู่ที่เดียว

สร้าง Config

export const GEMINI_MODEL =
  "gemini-3.7-flash";

จากนั้น Import ไปใช้

เมื่อ Model เปลี่ยนจะไม่ต้องค้นทุกไฟล์

เหมาะกับ Project ที่ comsiam ต้องการทดลองหลายโมเดลหรือเปลี่ยน Model ตามงานในอนาคต

🛡️ Checklist ก่อน Deploy

✅ Node.js Version

รองรับ SDK

@google/genai

ใช้ SDK ปัจจุบัน

GEMINI_API_KEY

อยู่ Server-side

.env

ไม่ Commit

✅ Input Validation

มี

✅ Output Validation

มีเมื่อใช้ AI Result ทำงานต่อ

✅ Error Handling

รองรับ API Failure

✅ Retry

มี Limit

✅ Rate Limit

Public Endpoint ต้องควบคุม

✅ Monitoring

ติดตาม Usage

✅ Cost

เข้าใจ Pricing

✅ Model

ยังรองรับ

🚫 10 ข้อผิดพลาดเมื่อใช้ Gemini API กับ JavaScript

❶ ใช้ SDK เก่า

Code ไม่ตรง API ปัจจุบัน

❷ ใช้ Node.js เก่าเกินไป

Package อาจทำงานไม่ได้

❸ ลืมตั้ง ES Module

import Error

❹ Hard-code API Key

Secret รั่ว

❺ ใส่ API Key ใน React Browser

ผู้ใช้เห็น Key

❻ ไม่ใช้ await

ได้ Promise แทน Result

❼ ไม่ Catch Error

Application ล้มเมื่อ API Error

❽ เปิด Search ทุก Prompt

เพิ่ม Complexity โดยไม่จำเป็น

❾ ส่ง Request Parallel จำนวนมาก

ชน Rate Limit

❿ Copy Model ID จากบทความเก่า

Model อาจไม่รองรับแล้ว

🪜 Workflow Gemini API + JavaScript ที่แนะนำ

❶ ติดตั้ง Node.js

ใช้ Version ที่ SDK รองรับ

❷ สร้าง Folder

เริ่ม Project เล็ก

npm init

สร้าง package.json

❹ สร้าง API Key

ผ่าน Google AI Studio

❺ ตั้ง GEMINI_API_KEY

เก็บเป็น Secret

❻ ติดตั้ง @google/genai

ใช้ SDK ปัจจุบัน

❼ เปิด ES Modules

ใช้ type: module

❽ สร้าง Client

new GoogleGenAI({})

❾ ส่ง Interaction

Text Prompt ง่าย ๆ

❿ อ่าน output_text

ยืนยันระบบทำงาน

⓫ สร้าง Function

แยก Gemini Logic

⓬ เพิ่ม Error Handling

ก่อนสร้าง Backend

⓭ เพิ่ม Structured Output

เมื่อ Program ต้อง Parse

⓮ เพิ่ม Conversation

เมื่อสร้าง Chat

⓯ เพิ่ม Streaming

สำหรับ UX

⓰ เพิ่ม File/Tools

ตาม Use Case

⓱ เชื่อม Backend

Express/Next.js/Server

⓲ เพิ่ม Rate Limit

ก่อน Public

⓳ Monitor

ดู Cost และ Error

⓴ Deploy

หลัง Security Review

แนวทางนี้ช่วยให้ comsiam เริ่มจาก JavaScript Script ที่เล็กและตรวจสอบง่ายก่อน แล้วค่อยนำ Logic ไปเชื่อม Web Application จริงในภายหลังโดยไม่ต้อง Debug Frontend, Backend และ Gemini API พร้อมกันตั้งแต่ครั้งแรก

💡 10 Prompt สำหรับทดสอบ Gemini API กับ JavaScript

❶ API Test

ตอบเฉพาะคำว่า SUCCESS

❷ Summary

สรุปข้อความนี้เป็นภาษาไทย 5 ข้อ

❸ Classification

จัดข้อความนี้เป็น billing, technical, account หรือ other

❹ JSON Extraction

ดึงชื่อสินค้า ราคา และจำนวนเป็น JSON

❺ JavaScript Coding

เขียน JavaScript function สำหรับคำนวณ VAT 7%

❻ Debug

หา Bug ใน JavaScript นี้และอธิบายสาเหตุ

❼ Rewrite

ปรับข้อความนี้ให้อ่านง่ายขึ้นโดยรักษาความหมายเดิม

❽ Sentiment

ตอบ sentiment เป็น positive, neutral หรือ negative

❾ FAQ

สร้าง FAQ 5 ข้อจากข้อความนี้

❿ จำกัด Output

ตอบคำถามนี้ไม่เกิน 3 ประโยค

❓ คำถามที่พบบ่อย

Gemini API กับ JavaScript ใช้ Package อะไร

SDK ทางการปัจจุบันของ Google ใช้ Package @google/genai และ Import GoogleGenAI จาก Package นี้

Google แนะนำ API แบบไหนสำหรับ Project JavaScript ใหม่

Getting Started ปัจจุบันใช้ Interactions API เป็นเส้นทางหลักสำหรับ Application ใหม่ และรองรับ JavaScript SDK โดยตรง

Gemini API ใช้กับ Node.js ได้ไหม

ได้ และ @google/genai รุ่นปัจจุบันกำหนด Node.js 20 ขึ้นไป จึงควรตรวจ Node Version ก่อนติดตั้ง

Gemini API Key ใส่ใน React ได้ไหม

ไม่ควรใส่ Secret Gemini API Key ใน Client-side React Code ควรให้ Backend หรือ Server-side Function เป็นผู้เรียก API

JavaScript ทำ Streaming กับ Gemini API ได้ไหม

ได้ Interactions API รองรับ Streaming โดยใช้ stream: true และอ่าน Event ด้วย for await...of

JavaScript ส่งรูปให้ Gemini ได้ไหม

ได้ สามารถส่ง Multimodal Input ตาม Model และ API ที่รองรับ เช่น Text ร่วมกับ Image แบบ Base64 หรือ Input Method อื่นตามเอกสารปัจจุบัน

🎯 สรุป

วิธีใช้ Gemini API กับ JavaScript เริ่มจาก Node.js → Gemini API Key → GEMINI_API_KEYnpm install @google/genainew GoogleGenAI({})ai.interactions.create()interaction.output_text

SDK ปัจจุบันของ Google คือ @google/genai และ Getting Started รุ่นล่าสุดใช้ Interactions API สำหรับการสร้าง Application ใหม่ พร้อมรองรับ Text, Conversation, Streaming, Multimodal Input, Structured Output, Google Search, Function Calling และ Agent Workflow

สำหรับ Web Application จุดที่สำคัญที่สุดคือ ห้ามฝัง Gemini API Key ใน JavaScript ที่ทำงานใน Browser ควรให้ Node.js Backend หรือ Server-side Runtime เป็นผู้เก็บ Secret และเรียก Gemini API

หลัง Basic Text Request ทำงานแล้ว ควรเพิ่มความสามารถทีละขั้น เริ่มจาก Error Handling และ Structured Output ก่อน แล้วจึงเพิ่ม Conversation, Streaming, File และ Tools ตาม Search Intent และ Requirement ของ Application

เมื่อเตรียม Production ต้องเพิ่ม Input Validation, Output Validation, Rate Limiting, Retry แบบมีขอบเขต, Monitoring และ Cost Control เพราะ Public API ที่ไม่มีการควบคุมสามารถสร้างทั้ง Rate Limit และค่าใช้จ่ายที่ไม่คาดคิดได้

หลักที่ควรจำคือเริ่มจาก Input → Gemini API → Output ที่เล็กที่สุดให้ทำงานก่อน แล้วค่อยนำ Function นั้นไปเชื่อม Express, Next.js, React Backend หรือระบบอื่นภายหลัง