วิธีใช้ Gemini API กับ Python แบบ Step by Step

การใช้ Gemini API กับ Python เป็นหนึ่งในวิธีที่ง่ายที่สุดสำหรับผู้เริ่มต้นที่ต้องการนำ AI ของ Google ไปสร้างโปรแกรม ระบบอัตโนมัติ Chatbot เครื่องมือวิเคราะห์ข้อมูล หรือ Web Application ของตัวเอง

ขั้นตอนพื้นฐานมีเพียง ติดตั้ง Python → สร้าง Gemini API Key → ตั้ง Environment Variable → ติดตั้ง google-genai → สร้าง Client → ส่ง Prompt → รับ Response

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

Workflow พื้นฐานคือ

Python Program
↓
Google Gen AI SDK
↓
Gemini API
↓
Gemini Model
↓
Response
↓
Python Program

บทความนี้จะพาทำตั้งแต่เริ่มต้นจนสามารถส่ง Prompt, รับคำตอบ, ทำ Conversation, Streaming และ Structured Output เบื้องต้นได้

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

เมื่อเชื่อม Python กับ Gemini API แล้วสามารถสร้างระบบได้หลายประเภท เช่น

  • AI Chatbot
  • Text Generator
  • Article Summarizer
  • Document Analyzer
  • Data Extraction
  • Classification
  • Sentiment Analysis
  • Translation
  • Coding Assistant
  • Customer Support
  • PDF Analyzer
  • Image Analyzer
  • Audio Analyzer
  • Video Analyzer
  • Structured JSON Generator
  • Search Assistant
  • Automation Script
  • AI Agent

ตัวอย่างง่าย ๆ

ข้อความลูกค้า
↓
Python
↓
Gemini API
↓
วิเคราะห์
↓
Category

จากนั้น Python สามารถนำ Category ไป

  • บันทึก Database
  • ส่ง Email
  • สร้าง Report
  • Route Ticket

ต่อได้

❷ ✅ สิ่งที่ต้องเตรียมก่อนเริ่ม

ควรมี

Python

Google Gen AI Python SDK รุ่นปัจจุบันต้องใช้ Python รุ่นที่รองรับ โดย Package ปัจจุบันกำหนด Python 3.10 ขึ้นไป

ตรวจ Version ด้วย

python --version

หรือบางเครื่อง

python3 --version

Google Account

สำหรับเข้า Google AI Studio

Gemini API Key

ใช้ Authentication กับ Gemini API

Internet

Python ต้องเชื่อมไปยัง Google API

Terminal

ใช้ติดตั้ง Package และ Run Script

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

เพราะโมเดล Gemini ทำงานบน Infrastructure ของ Google

❸ 📁 สร้าง Project Folder

เริ่มจากสร้าง Folder

gemini-python

เข้า Folder นั้น

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

gemini-python/
└── main.py

อย่าเพิ่งเพิ่ม

  • Flask
  • Django
  • FastAPI
  • Database
  • Docker

ในขั้นแรก

เป้าหมายแรกคือทำ API Call ให้สำเร็จก่อน

❹ 🧪 สร้าง Virtual Environment

สำหรับ Project จริงควรใช้ Virtual Environment เพื่อป้องกัน Package ของแต่ละ Project ชนกัน

สร้างด้วย

python -m venv .venv

บน Windows สามารถ Activate ตาม Shell ที่ใช้

ตัวอย่างแนวคิด

gemini-python/
├── .venv/
└── main.py

เมื่อ Environment ถูก Activate แล้ว Package ที่ติดตั้งจะถูกแยกสำหรับ Project นี้

ทำไมควรใช้ venv

สมมติมี

Project A
ใช้ Package Version A

และ

Project B
ใช้ Package Version B

หากติดตั้งทุกอย่าง Global อาจเกิด Conflict

Virtual Environment ช่วยแยก Dependency

❺ 🔑 สร้าง Gemini API Key

เข้า Google AI Studio

จากนั้นเปิด

Dashboard
↓
API Keys

สำหรับผู้ใช้ใหม่ Google AI Studio อาจมี Project และ API Key เริ่มต้นถูกสร้างให้อยู่แล้ว

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

Create API key

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

เมื่อได้ Key แล้วให้ Copy ไปเก็บในที่ปลอดภัย

⚠️ ห้ามโพสต์ API Key

อย่าใส่ Key จริงใน

  • GitHub Public
  • Blog
  • Screenshot
  • Facebook
  • LINE
  • Source Code ที่เผยแพร่

API Key ควรถูกถือเป็น Secret

❻ 🔐 ตั้ง GEMINI_API_KEY

Google Getting Started ใช้ Environment Variable ชื่อ

GEMINI_API_KEY

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

export GEMINI_API_KEY="YOUR_API_KEY"

YOUR_API_KEY ให้แทนด้วย Key จริงของคุณ

แต่ไม่ควรนำ Command ที่มี Secret จริงไป Commit

แนวคิดคือ

Environment
↓
GEMINI_API_KEY
↓
Python SDK
↓
Gemini API

ทำให้ Code ไม่ต้องมี Key อยู่ภายใน

❼ 🚫 ไม่ควร Hard-code Key แบบนี้

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

from google import genai

client = genai.Client(
    api_key="REAL_API_KEY"
)

แม้การส่ง Key ให้ Client โดยตรงอาจใช้ได้ในบาง Workflow แต่ Source Code ถูกแชร์หรือ Commit ได้ง่ายมาก

สำหรับ Project จริงควรใช้

  • Environment Variable
  • Secret Manager
  • Hosting Secret

แทน

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

Package Python ทางการปัจจุบันคือ

google-genai

ติดตั้ง

pip install -U google-genai

หรือ

python -m pip install -U google-genai

วิธีหลังมีข้อดีคือช่วยให้แน่ใจว่า pip เป็นของ Python Interpreter ที่กำลังใช้อยู่

หลังติดตั้งลอง

python -m pip show google-genai

เพื่อดูข้อมูล Package

❾ ⚠️ อย่าใช้ Library เก่า

Tutorial เก่าบางแห่งอาจแนะนำ

google-generativeai

หรือ Import

import google.generativeai as genai

สำหรับ Development ใหม่ควรใช้ SDK ปัจจุบัน

from google import genai

Package

google-genai

การเอา Code SDK เก่ากับ SDK ใหม่มาปนกันเป็นสาเหตุ Error ที่พบได้บ่อย

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

เปิด

main.py

ใส่ Code

from google import genai

client = genai.Client()

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

print(interaction.output_text)

จากนั้น Run

python main.py

หากใช้ python3

python3 main.py

ถ้าทุกอย่างถูกต้อง Gemini จะส่ง Response กลับมา

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

Import SDK

from google import genai

โหลด Google Gen AI Python SDK

สร้าง Client

client = genai.Client()

Client จะใช้ Configuration ของ SDK รวมถึง GEMINI_API_KEY ที่กำหนดไว้ใน Environment

สร้าง Interaction

interaction = client.interactions.create(

เป็นการส่ง Interaction ไปยัง Gemini API

เลือก Model

model="gemini-3.7-flash",

กำหนดโมเดลที่จะใช้

Model ID สามารถเปลี่ยนแปลงตาม Model Lifecycle ของ Google จึงควรตรวจ Model ปัจจุบันก่อนใช้ Production

ส่ง Prompt

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

นี่คือข้อมูลที่ส่งให้ Gemini

อ่าน Response

print(interaction.output_text)

output_text เป็น Property ที่ช่วยดึงข้อความ Output ออกมาได้สะดวก

⓬ 🎯 เปลี่ยน Prompt ได้อย่างไร

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

ตัวอย่าง

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="สร้างชื่อร้านกาแฟภาษาไทย 20 ชื่อ",
)

หรือ

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="เขียน Python function สำหรับคำนวณ VAT 7%",
)

หรือ

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="สรุปข้อดีและข้อเสียของ Wi-Fi 7 เป็นตาราง",
)

โครงสร้าง Program เหมือนเดิม

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

⓭ 📝 ใช้ Prompt หลายบรรทัด

Python สามารถใช้ Triple Quotes

prompt = """
อ่านข้อความด้านล่าง

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

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

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input=prompt,
)

print(interaction.output_text)

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

⓮ 🧠 สูตรเขียน Prompt สำหรับ Python App

ใช้รูปแบบ

Role
+
Task
+
Input
+
Constraints
+
Output

ตัวอย่าง

prompt = """
คุณเป็นผู้ช่วยจัดหมวดหมู่ข้อความลูกค้า

งาน:
จัดข้อความเป็นหนึ่งในหมวดต่อไปนี้

- billing
- technical
- account
- other

ข้อกำหนด:
ตอบเฉพาะชื่อหมวดหมู่

ข้อความ:
อินเทอร์เน็ตเชื่อมต่อไม่ได้หลังเปลี่ยน Router
"""

ผลลัพธ์ควรมี Scope ชัดกว่า Prompt

วิเคราะห์ข้อความนี้

⓯ 📥 รับ Input จากผู้ใช้

สามารถใช้ input() ของ Python

from google import genai

client = genai.Client()

user_text = input("ถาม Gemini: ")

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input=user_text,
)

print(interaction.output_text)

Run แล้วผู้ใช้สามารถพิมพ์ Prompt ผ่าน Terminal

ตัวอย่าง

ถาม Gemini: อธิบาย Python list comprehension

จากนั้นระบบส่งข้อความไป Gemini API

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

Interactions API รองรับ Conversation แบบ Stateful โดยใช้

previous_interaction_id

ตัวอย่าง

from google import genai

client = genai.Client()

first = client.interactions.create(
    model="gemini-3.7-flash",
    input="ฉันมีสุนัข 2 ตัว",
)

print(first.output_text)

second = client.interactions.create(
    model="gemini-3.7-flash",
    previous_interaction_id=first.id,
    input="ทั้งหมดมีกี่ขา",
)

print(second.output_text)

Interaction ที่สองอ้างอิง Interaction แรก

ทำให้โมเดลสามารถใช้ Conversation Context ที่ Server จัดการให้ตาม Workflow นี้

⓱ 🆚 Stateful กับ Stateless

Stateful

ใช้

previous_interaction_id

เหมาะกับ Chat/Agent จำนวนมาก เพราะ Server ช่วยรักษา History

Stateless

Application เก็บ History เองแล้วส่งข้อมูลที่จำเป็นกลับไปทุก Request

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

สำหรับมือใหม่ Stateful เข้าใจง่ายกว่า

⓲ ⚠️ Conversation ยาวมี Cost

แม้ Server ช่วยจัด State ไม่ได้หมายความว่า Context ใช้ฟรีไม่จำกัด

Conversation ยิ่งยาวสามารถเกี่ยวข้องกับ

  • Token Usage
  • Cost
  • Latency
  • Context Limit

ตาม Model/API

Production Chatbot ควรมี Strategy สำหรับ

  • Session
  • Conversation Length
  • Summary
  • Cleanup

ตาม Requirement

⓳ 🌊 Streaming Response ด้วย Python

ถ้า Response ยาว ไม่จำเป็นต้องรอคำตอบทั้งหมด

สามารถเปิด

stream=True

ตัวอย่าง

from google import genai

client = genai.Client()

stream = client.interactions.create(
    model="gemini-3.7-flash",
    input="อธิบายการทำงานของอินเทอร์เน็ตแบบละเอียด",
    stream=True,
)

for event in stream:
    if event.event_type == "step.delta":
        if event.delta.type == "text":
            text = getattr(event.delta, "text", None)

            if text:
                print(text, end="", flush=True)

ผลลัพธ์จะทยอยแสดงออกมา

เหมาะกับ

  • Chatbot
  • Long Answer
  • Interactive Interface

⓴ 🚀 Streaming ช่วยอะไร

แบบปกติ

Request
↓
รอ
↓
คำตอบทั้งหมด

Streaming

Request
↓
ข้อความส่วนแรก
↓
ข้อความส่วนต่อไป
↓
จนจบ

ผู้ใช้จึงรู้สึกว่า Application ตอบเร็วขึ้น

แต่ Streaming ไม่ได้แปลว่า Total Generation Time ต้องลดลงเสมอ

ประโยชน์หลักคือ Time to First Output

📦 Structured Output ด้วย Pydantic

Python เหมาะมากกับ Structured Output เพราะสามารถใช้ Pydantic Model กำหนด Schema ได้

ติดตั้ง Pydantic ถ้าจำเป็น

pip install pydantic

ตัวอย่าง

from typing import Literal

from google import genai
from pydantic import BaseModel


class Feedback(BaseModel):
    sentiment: Literal[
        "positive",
        "neutral",
        "negative",
    ]
    summary: str


client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="บริการดีมาก ส่งของเร็ว ประทับใจ",
    response_format={
        "type": "text",
        "mime_type": "application/json",
        "schema": Feedback.model_json_schema(),
    },
)

feedback = Feedback.model_validate_json(
    interaction.output_text
)

print(feedback)

แทนที่จะได้ข้อความอิสระ

Application สามารถได้ข้อมูลตาม Structure

📋 ทำไม Structured Output สำคัญ

สมมติระบบต้องการ

{
  "sentiment": "positive",
  "summary": "ลูกค้าพอใจกับบริการ"
}

ถ้ารับ Text อิสระ เช่น

จากข้อความนี้ดูเหมือนลูกค้าจะรู้สึกดีมากครับ

Python ต้อง Parse ยากขึ้น

Structured Output ทำให้

Gemini
↓
JSON
↓
Pydantic
↓
Python Object
↓
Application

สะดวกกว่า

⚠️ Structured Output ยังต้อง Validate

แม้มี JSON Schema ก็ควร Validate ข้อมูลก่อนใช้กับ Action สำคัญ

ตัวอย่าง

AI Output
↓
Validate
↓
Business Rule
↓
Database

ไม่ควร

AI Output
↓
Execute immediately

โดยเฉพาะ

  • Payment
  • Delete
  • Permission
  • User Account

🖼️ ส่งรูปภาพให้ Gemini ด้วย Python

Interactions API รองรับ Multimodal Input

ตัวอย่างแนวคิดสำหรับ Local Image คืออ่าน Binary แล้ว Encode เป็น Base64

import base64

from google import genai

client = genai.Client()

with open("sample.jpg", "rb") as file:
    image_bytes = file.read()

image_base64 = base64.b64encode(
    image_bytes
).decode("utf-8")

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

print(interaction.output_text)

นี่เป็นตัวอย่าง Multimodal ที่มี

Text
+
Image

ใน Interaction เดียว

📄 PDF, Audio และ Video ใช้แนวคิดเดียวกันไหม

แนวคิดพื้นฐานคล้ายกันคือส่ง Media Input ที่ API รองรับพร้อม Prompt

แต่แต่ละประเภทมีเรื่อง

  • MIME Type
  • File Size
  • Input Method
  • Context Limit
  • Upload Method

แตกต่างกัน

สำหรับ Production ควรตรวจ Documentation ของ Input Type ที่ใช้งานจริงก่อน

ไม่ควรสมมติว่าไฟล์ทุกประเภทส่งแบบเดียวกันได้ทั้งหมด

🔎 ใช้ Google Search กับ Python

Gemini API มี Google Search Tool ใน Feature ที่รองรับ

ตัวอย่างแนวคิด

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="สรุปข่าวเทคโนโลยีล่าสุด",
    tools=[
        {
            "type": "google_search",
        }
    ],
)

print(interaction.output_text)

เหมาะกับข้อมูลที่ต้องอัปเดต

เช่น

  • ข่าว
  • เหตุการณ์ล่าสุด
  • ข้อมูลปัจจุบัน

แต่การใช้ Search มี Pricing และ Usage Conditions ตาม Model/Tier

⚠️ อย่าเปิด Search หากไม่จำเป็น

คำถาม

2 + 2 เท่ากับเท่าไร

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

หรือ

อธิบาย Python dictionary

ก็ไม่จำเป็นในหลายกรณี

Tool Call เพิ่ม

  • Latency
  • Complexity
  • Potential Cost

จึงควรใช้เมื่อข้อมูลภายนอกช่วยตอบจริง

🧰 ใช้ Stable API Version ได้ไหม

Google Gen AI SDK ปัจจุบัน Default ไปที่

v1beta

เพื่อเปิดใช้ Feature Preview

แต่สามารถกำหนด Stable

v1

ได้ใน Feature ที่รองรับ รวมถึง Interactions API ปัจจุบัน

ตัวอย่าง

from google import genai

client = genai.Client(
    http_options={
        "api_version": "v1",
    }
)

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="อธิบาย Python แบบสั้น ๆ",
)

print(interaction.output_text)

🆚 v1 กับ v1beta เลือกอะไร

v1

เหมาะเมื่อ

  • ต้องการ Stable API
  • Feature ที่ใช้มีใน v1
  • Production ต้องการลด Preview Dependency

v1beta

เหมาะเมื่อ

  • ต้องการ Preview Feature
  • Documentation ของ Feature นั้นใช้ v1beta
  • ยอมรับการเปลี่ยน API ได้มากกว่า

อย่าเปลี่ยน Version เพียงเพราะเลขสูงหรือต่ำกว่า

ต้องดู Feature Compatibility

🧩 แยก Gemini Client เป็น Function

เมื่อ Program เริ่มใหญ่ ไม่ควรเขียนทุกอย่างใน Global Scope

ตัวอย่าง

from google import genai


def ask_gemini(prompt: str) -> str:
    client = genai.Client()

    interaction = client.interactions.create(
        model="gemini-3.7-flash",
        input=prompt,
    )

    return interaction.output_text


answer = ask_gemini(
    "อธิบาย API สำหรับมือใหม่"
)

print(answer)

ต่อไปสามารถนำ ask_gemini() ไปใช้ใน

  • CLI
  • Web API
  • Background Job

ได้

🧱 Project ใหญ่ควรสร้าง Client ครั้งเดียวหรือไม่

โดยทั่วไปไม่ควรสร้าง Object ที่ไม่จำเป็นซ้ำโดยไม่มีเหตุผล

สามารถออกแบบ

Application Start
↓
Create Client
↓
Reuse Client
↓
Multiple Requests

ตาม Lifecycle ของ Framework และ SDK

แต่ต้องคำนึงถึง

  • Threading
  • Async
  • Process
  • Runtime

ของ Application

อย่า Copy Global Singleton Pattern ไปใช้ทุก Framework โดยไม่เข้าใจ Environment

⚡ Async Python ใช้เมื่อไร

Python Application บางประเภทใช้ Async เช่น

  • FastAPI
  • Async Worker
  • Concurrent I/O

Google Gen AI SDK มี Async Capabilities สำหรับ Workflow ที่รองรับ

แต่สำหรับมือใหม่ควรเริ่ม Sync API ก่อน

เพราะง่ายกว่าในการ Debug

เมื่อระบบต้องรองรับ Concurrency จึงค่อยพิจารณา Async

🧠 Sync กับ Async ต่างกันอย่างไร

Sync

ส่ง Request
↓
รอ Response
↓
ทำงานต่อ

Async

ช่วยให้ Program จัดการ I/O อื่นระหว่างรอได้

Request A ──────┐
Request B ──────┤
Request C ──────┘

แต่ Async ไม่ได้ทำให้ Model Generate เร็วขึ้น

ประโยชน์อยู่ที่ Application Concurrency

🚨 วิธีจัดการ Error

Production Code ไม่ควรสมมติว่า API จะสำเร็จทุกครั้ง

อย่างน้อยควรจับ Error

from google import genai
from google.genai.errors import APIError


client = genai.Client()

try:
    interaction = client.interactions.create(
        model="gemini-3.7-flash",
        input="อธิบาย Gemini API",
    )

    print(interaction.output_text)

except APIError as error:
    print(
        "Gemini API error:",
        error,
    )

จากนั้นจึงออกแบบ Handling ตาม Error Type

⚠️ อย่าจับ Exception แล้วทำเหมือนไม่มีอะไรเกิดขึ้น

ตัวอย่างที่ไม่ดี

try:
    call_api()
except Exception:
    pass

เพราะ Application จะ

  • ซ่อน Error
  • Debug ยาก
  • ไม่รู้ว่า Request ล้มเหลว
  • อาจคืนข้อมูลผิดให้ User

ควร Log ข้อมูลที่จำเป็นโดยไม่ Log Secret

🔁 Retry อย่างถูกวิธี

Error บางประเภทอาจ Retry ได้

แต่ไม่ควรเขียน

while True:
    call_gemini()

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

แนวทางที่ดีกว่าคือ

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

เรียกว่า Backoff

ควร Retry เฉพาะ Error ที่เหมาะสม

🚨 Error 429

429 มักเกี่ยวข้องกับ Rate Limit หรือ Resource/Quota

อย่าแก้ด้วย

สร้าง API Key ใหม่

ทันที

ควรตรวจ

  • Rate Limit
  • Model
  • Project
  • Tier
  • Request Pattern
  • Retry

ก่อน

❌ Error 400

400 มักชี้ไปที่ Request ที่ไม่ถูกต้อง เช่น

  • Parameter
  • Input Structure
  • Model/Feature Combination

ต้องอ่านข้อความ Error

อย่าเปลี่ยน API Key ก่อน

⛔ Error 403

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

  • Permission
  • Access
  • Project
  • Billing/Feature
  • Credential

ตาม Request

ควรแก้ Root Cause

🔍 Error 404

อาจเกิดจาก

  • Model ID
  • Endpoint
  • Resource
  • API Version

ไม่ตรง

โดยเฉพาะเมื่อ Copy Code เก่าที่ใช้ Model ถูกเลิกใช้งานแล้ว

📜 Logging ที่เหมาะสม

สามารถ Log

timestamp
model
latency
status
error_code

ตามความเหมาะสม

แต่ไม่ควร Log

API Key
Password
Private Token

และ Prompt/Response ที่มีข้อมูลลูกค้าก็ควรมี Policy ก่อนเก็บ

📊 จับเวลา API Call

สามารถวัด Latency

import time

from google import genai

client = genai.Client()

start = time.perf_counter()

interaction = client.interactions.create(
    model="gemini-3.7-flash",
    input="อธิบาย Cloud Computing แบบสั้น ๆ",
)

elapsed = time.perf_counter() - start

print(interaction.output_text)
print(f"Time: {elapsed:.2f}s")

ช่วยให้รู้ Performance ก่อนสร้าง Production App

💰 ควรติดตาม Token Usage

Gemini API Usage ส่งผลต่อ

  • Cost
  • Rate Limit
  • Capacity Planning

Project จริงควรเก็บ Metric เช่น

requests
input_tokens
output_tokens
latency
errors

ตามข้อมูลที่ API Response มีให้

อย่าเปิด Public Application ก่อนมี Monitoring เลย

🔐 สร้าง Backend แทน Frontend

ถ้าจะสร้างเว็บไซต์ที่ใช้ Gemini API

ควรใช้

Browser
↓
Python Backend
↓
GEMINI_API_KEY
↓
Gemini API

เช่นใช้

  • FastAPI
  • Flask
  • Django

ตาม Project

Browser ไม่จำเป็นต้องรู้ API Key

Python Backend ทำหน้าที่ควบคุม

  • Authentication
  • Rate Limit
  • Validation
  • Cost

ได้

🌐 ตัวอย่าง Architecture กับ FastAPI

แนวคิด

User
↓
Frontend
↓
POST /ask
↓
FastAPI
↓
Gemini API
↓
Response

ก่อนทำควรให้ Basic Script ใน main.py ทำงานก่อน

จากนั้นจึงย้าย Logic เข้า Endpoint

อย่า Debug FastAPI และ Gemini API พร้อมกันตั้งแต่ Request แรก

🧪 สร้าง Function ให้ Test ง่าย

ตัวอย่าง

def build_prompt(
    customer_message: str,
) -> str:
    return f"""
จัดข้อความต่อไปนี้เป็น
billing, technical, account หรือ other

ข้อความ:
{customer_message}
"""

Function นี้ไม่เรียก API

จึง Unit Test ได้ง่าย

แยกออกจาก

Gemini API Call

ช่วยให้ Code ดูแลรักษาง่ายขึ้น

🔒 Validate Input ก่อนส่ง Gemini

ถ้า API รับข้อความจาก User

ควรตรวจ

  • Empty
  • Length
  • File Type
  • Maximum Size

ก่อนเรียก Gemini

ตัวอย่าง

if not user_text.strip():
    raise ValueError(
        "ข้อความต้องไม่ว่าง"
    )

ช่วยลด Request ที่ไม่มีประโยชน์

💸 จำกัด Input ช่วยลด Cost

ถ้า Application เปิดให้ผู้ใช้ Paste ข้อความไม่จำกัด

อาจมี User ส่ง

500,000 characters

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

ควรกำหนด Product Limit ตาม Use Case

เช่น

สูงสุด 20,000 characters

ตัวเลขต้องเลือกตาม Requirement จริง

ไม่ใช่ค่าตายตัวสำหรับทุก Application

📤 จำกัด Output ด้วย Prompt

ถ้าต้องการ Category หนึ่งคำ

ควรสั่ง

ตอบเฉพาะ billing, technical, account หรือ other

ไม่จำเป็นต้องให้โมเดลสร้างคำอธิบายหลายย่อหน้า

ช่วยลด

  • Token
  • Parsing
  • Latency

ได้

🔧 ใช้ Model เป็น Configuration

ไม่ควรเขียน Model ID กระจาย 20 จุด

ตัวอย่าง

MODEL = "gemini-3.7-flash"

แล้วใช้

interaction = client.interactions.create(
    model=MODEL,
    input=prompt,
)

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

Production อาจเก็บ Model ใน Configuration หรือ Environment ตาม Architecture

🧪 แยก Development กับ Production

อาจมี

Development
Staging
Production

แยก

  • API Key
  • Project
  • Logging
  • Rate Limit

ตามระบบ

อย่าใช้ Production Credential กับ Script ทดลองทุกตัว

📁 โครงสร้าง Project ที่เริ่มดีขึ้น

เมื่อ Project โต อาจจัด

gemini-app/
├── app/
│   ├── gemini_client.py
│   ├── prompts.py
│   └── services.py
├── tests/
├── .env.example
├── .gitignore
└── requirements.txt

แต่ไม่ต้องสร้าง Architecture ใหญ่เกิน Project

Project เล็กหนึ่งไฟล์ก็เพียงพอหาก Requirement มีเพียงหนึ่งงาน

📄 requirements.txt

สามารถเก็บ Dependency

google-genai
pydantic

แล้วติดตั้ง

pip install -r requirements.txt

สำหรับ Production ควรมี Dependency Strategy ที่ควบคุม Version ตามมาตรฐาน Project

🚫 อย่าใส่ API Key ใน requirements.txt

requirements.txt มีไว้เก็บ

Package
Version

ไม่ใช่ Secret

Key ต้องอยู่

  • Environment
  • Secret Store

แยกจาก Dependency

📄 ใช้ .env ได้ไหม

ใน Local Development หลาย Project ใช้ .env

ตัวอย่าง

GEMINI_API_KEY=YOUR_API_KEY

แต่ .env ที่มี Key จริงต้องไม่ Commit ไป Public Git

ควรใส่ใน .gitignore

เช่น

.env
.venv/
__pycache__/

และสามารถมี

.env.example

ที่ไม่มี Secret จริงเพื่อบอกว่าต้องมี Variable อะไร

🐙 ก่อน Push GitHub ต้องตรวจ Secret

ก่อน

git push

ค้นหา

  • API Key
  • .env
  • Password
  • Token
  • Private Key

ก่อนเสมอ

ถ้า Key เคยถูก Commit แล้ว

อย่าเพียงลบจากไฟล์ล่าสุด

ควร Rotate Key เพราะ Key อาจอยู่ใน Git History

🛡️ Checklist Security

ก่อน Deploy Python Gemini App ตรวจ

✅ API Key อยู่ Server-side

✅ ไม่มี Key ใน Git

✅ Input Validation

✅ User Authentication ถ้าจำเป็น

✅ Rate Limiting

✅ Timeout/Retry

✅ Logging ไม่เก็บ Secret

✅ AI Output Validation

✅ Usage Monitoring

✅ Cost Monitoring

การเรียก Gemini สำเร็จเป็นเพียงส่วนหนึ่งของ Production Readiness

🚀 ขั้นตอนจาก Script ไป Production

เริ่มจาก

main.py

แล้วค่อยพัฒนา

Python Function
↓
Service Layer
↓
Web API
↓
Authentication
↓
Rate Limit
↓
Monitoring
↓
Deploy

ไม่ควรสร้างทุก Layer พร้อมกันตั้งแต่วันแรก

สำหรับงานทดลองของ comsiam การสร้าง Script เล็ก ๆ ให้ API ทำงานถูกต้องก่อน แล้วจึงย้าย Logic ไปยัง Backend จะช่วยลดเวลา Debug ได้มาก

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

❶ ใช้ SDK เก่า

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

❷ Python Version เก่าเกินไป

Package ติดตั้งไม่ได้

❸ Hard-code API Key

เสี่ยง Secret รั่ว

❹ ใช้ Key ใน Frontend

ผู้ใช้ดึง Key ได้

❺ ไม่ใช้ Virtual Environment

Dependency ชนกัน

❻ Copy Model ID เก่า

อาจเกิด 404

❼ เริ่มจาก Agent ซับซ้อน

Debug ยาก

❽ ไม่ Validate Input

เสีย Request โดยไม่จำเป็น

❾ Retry ไม่จำกัด

Traffic และ Cost เพิ่ม

❿ ไม่ Monitor Usage

รู้ปัญหาเมื่อสายเกินไป

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

❶ ตรวจ Python

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

❷ สร้าง Project Folder

แยกงานให้ชัด

❸ สร้าง venv

แยก Dependency

❹ สร้าง Gemini API Key

ผ่าน AI Studio

❺ ตั้ง GEMINI_API_KEY

ไม่ Hard-code

❻ ติดตั้ง google-genai

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

❼ สร้าง Client

genai.Client()

❽ ส่ง Interaction แรก

Text Prompt

❾ อ่าน output_text

ยืนยัน API ทำงาน

❿ เพิ่ม User Input

สร้าง CLI ง่าย ๆ

⓫ เพิ่ม Conversation

เมื่อจำเป็น

⓬ เพิ่ม Structured Output

เมื่อ Program ต้องอ่านข้อมูล

⓭ เพิ่ม Streaming

สำหรับ Chat UX

⓮ เพิ่ม Files/Tools

ตาม Requirement

⓯ เพิ่ม Error Handling

ก่อน Production

⓰ เพิ่ม Monitoring

ดู Usage และ Cost

⓱ Deploy

หลัง Security Review

Workflow นี้ช่วยให้เพิ่ม Complexity ทีละระดับและรู้ว่าปัญหาเกิดจากส่วนใด

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

❶ API Test

ตอบเพียงคำว่า SUCCESS

❷ Summary

สรุปข้อความนี้เป็น 5 ข้อ

❸ Classification

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

❹ Extraction

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

❺ Translation

แปลข้อความนี้เป็นภาษาไทย

❻ Coding

อธิบาย Python Function นี้และหา Bug

❼ FAQ

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

❽ Rewrite

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

❾ Sentiment

วิเคราะห์ Sentiment เป็น positive, neutral หรือ negative

❿ Short Output

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

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

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

Google Python SDK ปัจจุบันใช้ Package google-genai และ Import ด้วย from google import genai

Python ต้องเป็น Version ไหน

Google Gen AI Python SDK ปัจจุบันกำหนดให้ใช้ Python 3.10 ขึ้นไป จึงควรตรวจ Version ก่อนติดตั้ง Package

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

เอกสาร Getting Started ปัจจุบันแนะนำ Interactions API สำหรับการเริ่มพัฒนา Application ใหม่ด้วย Gemini

ใช้ Gemini API Key ใน Python อย่างไรให้ปลอดภัย

ควรตั้ง GEMINI_API_KEY เป็น Environment Variable หรือ Secret ใน Hosting แทนการ Hard-code ลง Source Code

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

ได้ Interactions API รองรับ Streaming โดยตั้ง stream=True แล้วอ่าน Event ที่ส่งกลับมาเป็นลำดับ

ใช้ Gemini API กับ Python ส่งรูปได้ไหม

ได้ Gemini รองรับ Multimodal Input ตาม Model และ API ที่ใช้ โดย Python สามารถส่ง Image พร้อม Text ใน Interaction ตาม Format ที่รองรับ

🎯 สรุป

วิธีใช้ Gemini API กับ Python แบบ Step by Step เริ่มจาก Python → Virtual Environment → Gemini API Key → GEMINI_API_KEYgoogle-genaigenai.Client()client.interactions.create()interaction.output_text

สำหรับ Development ใหม่ควรใช้ Google Gen AI Python SDK ชื่อ google-genai แทน Library รุ่นเก่าที่พบใน Tutorial เดิม และ SDK ปัจจุบันต้องการ Python 3.10 ขึ้นไป

Interactions API เป็นแนวทางที่ Google ใช้ใน Getting Started รุ่นปัจจุบัน สามารถเริ่มจาก Text Generation แล้วขยายไปสู่ Conversation แบบ Stateful, Streaming, Multimodal Input, Structured Output, Google Search และ Agent Workflow ได้

เมื่อสร้าง Application จริง ไม่ควร Hard-code API Key หรือส่ง Key ไปยัง Browser ควรให้ Python Backend เป็นผู้เรียก Gemini API พร้อมเพิ่ม Input Validation, Error Handling, Rate Limit และ Monitoring

ผู้เริ่มต้นไม่จำเป็นต้องเรียน Feature ทุกอย่างพร้อมกัน การทำ Request แบบ Text ให้สำเร็จก่อน แล้วค่อยเพิ่ม JSON, Streaming และ Tools ทีละส่วน จะทำให้เข้าใจระบบและ Debug ได้ง่ายกว่ามาก

แนวทางของ comsiam คือใช้ Python Script ขนาดเล็กทดสอบ Input → Gemini API → Output ให้เสถียรก่อน แล้วจึงนำ Function เดิมไปเชื่อม Web App หรือ Automation ภายหลัง วิธีนี้ช่วยลดทั้ง Complexity และความเสี่ยงจากการแก้หลายส่วนพร้อมกัน