ข้ามไปที่เนื้อหา

Tech Stack ของ AI App ปี 2026: ไล่ครบทุก Layer ตั้งแต่ล่างถึงบน

ใครๆ ก็อยากทำ AI app และเกือบทุกคนเริ่มจากสองบรรทัดนี้เหมือนกันหมด:

import openai
response = openai.chat.completions.create(...)

แบบนี้พอทำ demo ได้ แต่เอาไปทำ product ไม่ได้ พอเปิดให้ user จริงใช้ คำถามจะถาโถมเข้ามาทันที data เก็บไว้ที่ไหน? จะให้ model รู้ข้อมูลใหม่ๆ อยู่ตลอดได้ยังไง? จะรู้ได้ยังไงว่า model เริ่มตอบมั่ว? แล้วจะ deploy ยังไงไม่ให้ต้องรื้อใหม่หมดทุกครั้งที่เปลี่ยน model?

AI application ระดับ production ในปี 2026 ไม่ใช่ Python script ไฟล์เดียว แต่เป็น ระบบ 10 layer แต่ละ layer แก้ปัญหาคนละแบบ และแต่ละ layer ก็มี ecosystem ของ tool เป็นของตัวเอง

โพสต์นี้คือแผนที่ ผมจะไล่ทีละ layer จากล่างขึ้นบน ว่าแก้ปัญหาอะไร วงการใช้ tool ตัวไหนเป็นมาตรฐาน และแต่ละ layer ต่อกันยังไง อ่านจบแล้ว ไม่ว่าจะเจอ AI product ตัวไหน คุณจะบอกได้เลยว่าข้างในมีอะไรรันอยู่บ้าง


ภาพรวม Architecture ทั้งหมด

ก่อนลงรายละเอียด ดูภาพรวมทั้งหมดกันก่อน:

┌─────────────────────────────────────────────────────────────────┐
│  10. Frontend & Interfaces     React, Next.js, Streamlit, Gradio│
├─────────────────────────────────────────────────────────────────┤
│  9.  Security & Compliance     OAuth2, JWT, Guardrails, GDPR    │
├─────────────────────────────────────────────────────────────────┤
│  8.  Model Deployment          FastAPI, Triton, KServe, CI/CD   │
├─────────────────────────────────────────────────────────────────┤
│  7.  Model Versioning          MLflow, ONNX, BentoML            │
├──────────────────────────┬──────────────────────────────────────┤
│  6.  AI Agents             │  5.  RAG & Augmentation            │
│  LangGraph, AutoGen, CrewAI│  Pinecone, LlamaIndex, Embeddings  │
├──────────────────────────┴──────────────────────────────────────┤
│  4.  Model Development         PyTorch, HuggingFace, MLflow     │
├─────────────────────────────────────────────────────────────────┤
│  3.  MLOps Infrastructure      Docker, Kubernetes, Argo, Flyte  │
├─────────────────────────────────────────────────────────────────┤
│  2.  Monitoring & Observability Evidently, Prometheus, Arize    │
├─────────────────────────────────────────────────────────────────┤
│  1.  Data Layer                BigQuery, Airflow, dbt, MongoDB  │
└─────────────────────────────────────────────────────────────────┘

แต่ละ layer ต้องพึ่ง layer ที่อยู่ข้างล่าง ไม่มี versioning ก็ deploy model ให้ไว้ใจได้ยาก ไม่มี data layer ก็ทำ RAG ไม่ได้ ส่วนของที่ยังไม่ได้ deploy ก็ไม่มีอะไรให้ monitor ลำดับเลยสำคัญ


Layer 1: Data Layer — ฐานรากของ AI

"เก็บ ทำความสะอาด และส่ง data ไปให้ model ใช้ได้อย่างคล่องตัว"

AI application จะดีได้แค่ไหน ขึ้นอยู่กับ data ที่ป้อนเข้าไป layer นี้รับข้อมูลดิบ ทั้ง user event, document, database และ web crawl แล้วแปลงเป็น asset ที่สะอาด มีโครงสร้าง และมี version ให้ layer อื่นๆ หยิบไปใช้ต่อ

Storage และ Warehousing

BigQuery    → Google's serverless data warehouse. SQL over petabytes.
              Best for: analytics, feature stores, training data at scale.

Snowflake   → Cloud-agnostic data warehouse with excellent data sharing.
              Best for: multi-cloud organizations, governed data access.

S3          → AWS object storage. The universal raw data lake.
              Best for: storing raw files, model artifacts, logs, any format.

pattern ที่เจอบ่อยคือ raw data ลง S3 ก่อน → data ที่ process แล้วเข้า BigQuery หรือ Snowflake → ส่วน application data เก็บใน PostgreSQL หรือ MongoDB

Database

PostgreSQL  → Relational, ACID-compliant. With the pgvector extension,
              it also serves as a vector database. The Swiss army knife.
              Best for: structured application data, user records, transactions.

MongoDB     → Document store (JSON-like). Flexible schema, fast reads.
              Best for: unstructured/semi-structured content like documents,
              chat history, Notion pages, scraped web content.

Pipeline

Airflow     → The industry standard for workflow orchestration.
              Define pipelines as Python DAGs. Schedule, retry, monitor.
              Best for: batch ETL, daily training data refreshes.

dbt         → SQL transformation layer. Turns raw warehouse tables
              into clean, documented, tested analytical models.
              Best for: building feature tables from warehouse data.

Prefect     → Modern Python-first alternative to Airflow.
              Best for: data science teams who prefer Python-native workflows.

ต่อกันยังไง:

Raw events (S3) → Airflow orchestrates → dbt transforms → BigQuery feature table
                                      → MongoDB document store → RAG pipeline

Quick-Start: Airflow DAG ง่ายๆ สำหรับเตรียม Data ให้ AI

from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta

def extract_notion_pages(): ...   # pull from Notion API → S3
def filter_quality(min_words=200): ...  # remove stubs → MongoDB
def generate_embeddings(): ...    # embed chunks → Vector DB

with DAG(
    dag_id="ai_data_pipeline",
    schedule_interval="@daily",
    start_date=datetime(2026, 1, 1),
    catchup=False,
) as dag:
    t1 = PythonOperator(task_id="extract", python_callable=extract_notion_pages)
    t2 = PythonOperator(task_id="filter",  python_callable=filter_quality)
    t3 = PythonOperator(task_id="embed",   python_callable=generate_embeddings)

    t1 >> t2 >> t3

Layer 2: Monitoring & Observability — ดูแล App ให้แข็งแรงอยู่เสมอ

"ดูแลให้ AI app แข็งแรง ตอบแม่น และอยู่ในการควบคุม"

ผมตั้งใจวาง layer นี้ไว้ลำดับที่สอง เพราะควร instrument ตั้งแต่ก่อนสร้าง ไม่ใช่มาใส่ทีหลัง หลายทีมใส่ monitoring เป็นอย่างสุดท้าย แล้วมานั่งเสียดายตอน model ค่อยๆ แย่ลงเงียบๆ ใน production

Model Monitoring

Evidently AI  → Open-source. Generates data drift and model quality reports.
                Detects when input distributions shift from training data.

WhyLabs       → Managed service. Real-time data quality and drift monitoring
                with automatic anomaly detection.

Arize AI      → Enterprise-grade ML observability. Traces predictions back
                to training examples. Strong LLM evaluation features.

Infrastructure Monitoring

Prometheus    → Pull-based metrics collection. Scrapes endpoints,
                stores time-series data. The standard for K8s environments.

Grafana       → Visualization layer on top of Prometheus (and 50+ other
                data sources). Build dashboards, set alert thresholds.

Data Drift Detection

Fiddler       → Monitors for feature drift, prediction drift, and concept
                drift. Explainability features for regulated industries.

Superwise     → Focuses on model performance monitoring post-deployment.
                Integrates with major ML platforms.

monitoring stack ที่ LLM app ต้องมีจริงๆ:

ต้อง monitor อะไร Tool Key metric
คุณภาพคำตอบ Arize AI / Evidently Faithfulness score, relevance
อัตรา hallucination Custom + LLM judge % คำตอบที่ไม่ได้อิง context
Latency Prometheus + Grafana p50, p95, p99 response time
Token usage / ค่าใช้จ่าย Dashboard ของ provider Tokens/request, cost/day
Input distribution shift WhyLabs ความยาว query, สัดส่วนหัวข้อที่ถาม
สุขภาพ infrastructure Prometheus + Grafana CPU, GPU utilization, memory

Layer 3: MLOps Infrastructure — Scale และ Automation

"จัดการ scale, automation และ production pipeline ในหลาย environment"

MLOps infrastructure เปรียบเหมือนระบบปฏิบัติการของ AI pipeline ถ้าไม่มี layer นี้ การรัน pipeline ก็คือ SSH เข้า server แล้วภาวนาว่าอย่าพัง

Containerization

Docker   → Package your entire training or inference environment
           (Python version, CUDA version, dependencies) into a
           reproducible, portable image. The non-negotiable foundation
           of everything else in this layer.

ทุก step ใน pipeline รันใน Docker container ปัญหา "เครื่องผมรันได้นะ" จบไปได้เลย

Orchestration

Kubernetes   → Container orchestration. Schedules containers across a
               cluster, handles failures, scales up/down automatically.
               The runtime layer for production AI workloads.

Kubeflow     → ML-specific extension of Kubernetes. Adds pipelines,
               experiment tracking, model serving, and Jupyter notebooks
               as Kubernetes-native resources.

MLRun        → End-to-end MLOps platform built on Kubernetes. Strong
               feature store, automated pipelines, serverless ML functions.

Workflow Automation

Argo Workflows  → Kubernetes-native workflow engine. Define multi-step
                  pipelines as YAML DAGs that run as Kubernetes pods.
                  Used by Kubeflow under the hood.

Flyte           → Strongly-typed, reproducible ML workflow platform.
                  Python-native SDK, excellent for data + ML pipelines.
                  Built by Lyft; used at Spotify, Freenome, Union.ai.

MLOps stack มาตรฐานของปี 2026:

Docker (packaging) + Kubernetes (runtime) + Argo/Flyte (pipelines)
= a self-healing, scalable, reproducible ML platform

Layer 4: Model Development — แกนหลักของงาน ML/AI

"พื้นที่ที่ data scientist ใช้ train และทดลอง model"

พูดถึง "AI stack" ทีไร engineer ส่วนใหญ่จะนึกถึง layer นี้ก่อน แต่อย่างที่เห็น นี่เป็นแค่ 1 ใน 10 layer

Framework

PyTorch      → The dominant research and production framework.
               Dynamic computation graph; Pythonic API.
               Used by: Meta, OpenAI, HuggingFace, most academia.

TensorFlow   → Google's framework. Strong production/mobile story
               with TF Lite and TF Serving.
               Best for: teams already in the Google ecosystem.

JAX          → NumPy + automatic differentiation + XLA compilation.
               Favorite of DeepMind and research groups needing
               maximum performance with hardware accelerators.

Library

HuggingFace  → The npm of AI. 500,000+ pre-trained models, datasets,
               tokenizers. transformers, diffusers, datasets, PEFT.
               In 2026: the starting point for almost every LLM project.

Scikit-learn → Classical ML. SVM, random forests, gradient boosting.
               Still essential for tabular data, feature engineering,
               and evaluation metrics.

XGBoost      → Gradient-boosted trees. Still beats deep learning on
               structured tabular data. Fast, reliable, interpretable.

Experiment Tracking

MLflow       → Open-source. Logs parameters, metrics, artifacts.
               Provides model registry and a UI for comparing runs.
               Self-hostable. The most widely adopted option.

Weights & Biases  → Managed service. Beautiful dashboards, team
                    collaboration, hyperparameter sweeps, model lineage.
                    Preferred by research teams and startups.

setup experiment tracking แบบเรียบง่ายที่สุด:

import mlflow
import mlflow.pytorch

with mlflow.start_run(run_name="llama3-lora-v2"):
    mlflow.log_params({
        "model": "llama-3-8b",
        "lora_rank": 16,
        "learning_rate": 2e-4,
        "epochs": 3,
    })

    # ... training loop ...

    mlflow.log_metrics({"train_loss": 0.42, "val_loss": 0.48})
    mlflow.pytorch.log_model(model, "summarization-llm")
    # Model is now versioned, searchable, and deployable from the registry.

Layer 5: Retrieval & Augmentation — เติมความรู้ให้ LLM ตอน Runtime

"ให้ model reasoning ได้ด้วยความรู้จากโลกจริงที่อัปเดตอยู่ตลอด"

layer นี้คือสิ่งที่ทำให้ LLM เอาไปใช้ใน application จริงได้ ถ้าไม่มี model ก็รู้แค่ที่ train มา แต่พอมี layer นี้ model จะ reasoning บน live data ของคุณได้ ทั้ง document, database และ API ที่อัปเดตอยู่ตลอด

Vector Database

Pinecone    → Managed vector database. No ops overhead.
              Best for: startups and teams that don't want to
              manage infrastructure.

Weaviate    → Open-source and managed. Hybrid search (vector + keyword).
              Built-in data schema. Strong for multi-tenant apps.

FAISS       → Facebook AI Similarity Search. Pure library (no server).
              Extremely fast for in-memory similarity search.
              Best for: prototyping and when you want full control.

RAG Framework

LangChain   → The Swiss army knife of LLM application development.
              Document loaders, text splitters, retrievers, chains,
              agents, memory. Large ecosystem but significant complexity.

LlamaIndex  → Focused on data indexing and retrieval for LLMs.
              Better abstractions for document ingestion, structured
              data querying, and multi-document reasoning than LangChain.

Embedding

OpenAI      → text-embedding-3-small / text-embedding-3-large.
              Highest quality, easiest to use. Pay-per-token.

Cohere      → embed-english-v3.0. Excellent multilingual support.
              Strong performance on retrieval benchmarks.

SentenceTransformers → Open-source. Run locally, no API cost.
                       BAAI/bge-large-en-v1.5 is competitive with
                       paid APIs for English text.

RAG pipeline แบบเรียบง่ายที่สุด:

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.vector_stores.pinecone import PineconeVectorStore
import pinecone

# 1. Load documents
docs = SimpleDirectoryReader("./knowledge_base").load_data()

# 2. Build index (embeds and stores in Pinecone)
vector_store = PineconeVectorStore(pinecone_index=pinecone.Index("my-index"))
index = VectorStoreIndex.from_documents(
    docs,
    embed_model=OpenAIEmbedding(model="text-embedding-3-small"),
    vector_store=vector_store,
)

# 3. Query at runtime — retrieves relevant chunks before generating
query_engine = index.as_query_engine()
response = query_engine.query("What is our refund policy for subscriptions?")
print(response)
# Answer is grounded in your actual documents, not model training data.

Layer 6: AI Agent Framework — คิด วางแผน และใช้ Tool

"ให้ AI คิด วางแผน และลงมือทำผ่าน external tool ได้"

agent ไปไกลกว่า RAG อีกขั้น RAG คือ retrieve หนึ่งรอบแล้ว generate หนึ่งรอบ แต่ agent รันเป็น loop คิดก่อน เลือก tool ที่จะใช้ ดูผลลัพธ์ แล้วคิดต่อ วนไปจนกว่างานจะเสร็จ

Agent Framework

LangGraph   → Graph-based agent orchestration from the LangChain team.
              Nodes = LLM calls or tools. Edges = conditional logic.
              Best for: complex stateful agents with branching workflows.

AutoGen     → Microsoft's multi-agent framework. Multiple agents
              with different roles collaborate via a conversation.
              Best for: coding assistants, autonomous research agents.

CrewAI      → Role-based multi-agent system. Define agents as "crew
              members" with goals, backstories, and tools.
              Best for: teams new to agents; clean, readable abstractions.

Workflow Orchestration (No-Code/Low-Code)

n8n         → Open-source workflow automation. 400+ integrations.
              Self-hostable. Connects AI agents to business tools.
              Best for: teams who want Zapier-level power with full control.

Make.com    → Visual workflow builder. Strong API integration.
              Best for: non-technical users automating AI-powered workflows.

Tool Use

agent จะเก่งขึ้นมากเมื่อเรียก tool ได้ ไม่ว่าจะเป็น REST API, browser (เอาไว้ scrape เว็บ) หรือ Python function ตัว tool abstraction นี่แหละที่ทำให้ agent ขยับจากแค่ "รู้" ไปเป็น "ลงมือทำ" ได้จริง

from langchain.tools import tool
from langchain_anthropic import ChatAnthropic
from langgraph.prebuilt import create_react_agent

@tool
def search_database(query: str) -> str:
    """Search the internal product database."""
    return db.execute(f"SELECT * FROM products WHERE name LIKE '%{query}%'")

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email to a customer."""
    return email_client.send(to=to, subject=subject, body=body)

# Agent gets tools and decides when to use them
model = ChatAnthropic(model="claude-sonnet-4.6")
agent = create_react_agent(model, tools=[search_database, send_email])

response = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "Find our top-selling product this month and email a summary to sales@company.com"
    }]
})
# Agent will: call search_database → analyze result → call send_email → report back

Layer 7: Model Versioning & Packaging — Traceability และ Reproducibility

"ทำให้ trace ย้อนกลับได้ reproduce ได้ และ deploy ได้ตามมาตรฐานเดียวกัน"

สมมติคุณ train model มาตัวหนึ่ง วันอังคารที่แล้วยังทำงานดีอยู่เลย แต่ตอนนี้ไม่ดีแล้ว จะ reproduce model ของวันอังคารที่แล้วกลับมาได้ไหม? ถ้าไม่มี layer นี้ ส่วนใหญ่คำตอบคือไม่ได้

Model Registry

MLflow Model Registry  → Track model versions, stages (Staging/Production),
                         and the exact run that produced each version.
                         Links model → training code → dataset → metrics.

SageMaker Model Registry → AWS-native registry. Integrates with SageMaker
                           pipelines, approval workflows, and deployment.
                           Best for: teams already on AWS.

Packaging Tool

Docker   → Package the entire inference environment. Guarantees that
           the model behaves identically in dev, staging, and production.

ONNX     → Open Neural Network Exchange format. Convert models from
           PyTorch/TensorFlow to a framework-neutral format for
           optimized inference (often 2–5× faster on CPU).

BentoML  → Package, serve, and deploy models as production-grade
           services. Handles model loading, batching, and API generation.
           One bento = model + dependencies + serving logic.

promote model จาก staging ไป production ด้วย MLflow:

from mlflow.tracking import MlflowClient

client = MlflowClient()

# After a successful evaluation run:
client.transition_model_version_stage(
    name="summarization-llm",
    version=7,
    stage="Production",
    archive_existing_versions=True,  # move previous version to Archived
)
# Now version 7 is in Production. Full audit trail preserved.

Layer 8: Model Deployment & Serving — จาก Model สู่ Service

"เปลี่ยน model ให้เป็น service ที่ application เรียกใช้ได้"

ไฟล์ model ที่นอนอยู่ใน registry ไม่ได้ช่วยอะไร user เลย layer นี้เอา model มาห่อด้วย API ทำให้ scale ได้ แล้วปล่อยขึ้น production

API Framework

FastAPI   → The preferred choice in 2026 for AI APIs. Async, fast,
            automatic OpenAPI docs, Pydantic validation. Python-native.

Flask     → Simpler, synchronous. Good for internal tools and
            low-traffic endpoints.

gRPC      → Binary protocol, lower latency than REST.
            Best for: inter-service communication in microservices,
            high-throughput model serving.

Inference Server

Triton Inference Server  → NVIDIA's production inference server.
                           Supports PyTorch, TensorFlow, ONNX, TensorRT.
                           Handles dynamic batching and GPU sharing.
                           Best for: GPU-based inference at scale.

TorchServe               → PyTorch's official model server.
                           Simpler than Triton. Good for single-framework
                           deployments.

KServe                   → Kubernetes-native model serving.
                           Standardizes inference across frameworks
                           and adds autoscaling, canary deployments,
                           and A/B testing.

CI/CD สำหรับ Model

GitHub Actions   → Trigger model retraining on data changes,
                   run evaluation gates, deploy on merge to main.

Jenkins          → Self-hosted CI/CD. More control, more maintenance.

GitLab CI/CD     → Integrated with GitLab repositories. Strong
                   container registry support.

FastAPI model serving endpoint แบบครบทั้งตัว:

# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from contextlib import asynccontextmanager
import mlflow

model = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    global model
    model = mlflow.pyfunc.load_model("models:/summarization-llm/Production")
    yield
    model = None

app = FastAPI(title="Summarization Service", lifespan=lifespan)

class SummarizeRequest(BaseModel):
    text: str
    max_length: int = 150

class SummarizeResponse(BaseModel):
    summary: str

@app.post("/summarize", response_model=SummarizeResponse)
async def summarize(request: SummarizeRequest):
    if model is None:
        raise HTTPException(status_code=503, detail="Model not loaded")
    result = model.predict({"text": request.text, "max_length": request.max_length})
    return SummarizeResponse(summary=result["summary"])

Layer 9: Security, Governance & Compliance — สร้างความไว้ใจเมื่อระบบโต

"ขาดไม่ได้ ถ้าอยากให้ enterprise AI app น่าไว้ใจ มีจริยธรรม และ scale ได้"

ตอนทำ prototype คนมักข้าม layer นี้ไป สุดท้ายก็กลายเป็นเหตุผลที่ขาย product ให้ enterprise ไม่ได้ ปี 2026 AI เข้าไปอยู่ใน healthcare, finance และ legal แล้ว security กับ compliance เลยไม่ใช่ของเสริมอีกต่อไป

Auth & Access

OAuth2    → The standard authorization protocol. Used to securely
            grant third-party apps access to user data without
            sharing passwords. Foundation of "Sign in with Google."

JWT       → JSON Web Tokens. Compact, URL-safe tokens for transmitting
            claims between parties. Used to authenticate API calls
            after OAuth2 login.

Auth0     → Managed identity platform. Handles OAuth2, MFA, SSO,
            social login, and user management without building it
            yourself.

Security เฉพาะทางของ AI

Rebuff       → Prompt injection detection. Identifies malicious inputs
               trying to hijack your LLM's behavior ("Ignore previous
               instructions..."). Open-source and managed.

Guardrails AI  → Define rules ("never output PII", "stay on topic",
                 "validate JSON output schema") and wrap your LLM calls.
                 Automatically re-asks or blocks non-compliant outputs.

ตัวอย่างการใช้ Guardrails AI จริง:

from guardrails import Guard
from guardrails.hub import DetectPII, ValidJSON

guard = Guard().use_many(
    DetectPII(pii_entities=["EMAIL_ADDRESS", "PHONE_NUMBER"], on_fail="redact"),
    ValidJSON(on_fail="reask"),
)

response = guard(
    llm_api=openai.chat.completions.create,
    prompt="Summarize this customer record: ...",
    model="gpt-5.4",
)
# PII is automatically redacted. Non-JSON output triggers a re-ask.

Compliance Framework

GDPR    → EU regulation. Users have the right to access, correct,
          and delete their data. AI apps must disclose data usage.

SOC2    → Security audit standard. Five trust criteria: security,
          availability, processing integrity, confidentiality, privacy.
          Required by most enterprise customers before procurement.

HIPAA   → US healthcare data regulation. Strict rules for storing
          and transmitting patient data. AI apps in healthcare must
          be HIPAA-compliant or use a HIPAA Business Associate.

Layer 10: Frontend & Interface — ทำให้คนใช้ AI ได้จริง

"ทำให้ user จริงใช้ AI product ของคุณได้"

model เก่งแค่ไหนก็ไร้ค่าถ้าไม่มี interface ให้คนใช้ layer นี้เปลี่ยนทุกอย่างที่อยู่ข้างล่างให้เป็นสิ่งที่คนโต้ตอบด้วยได้

Web UI

React / Next.js  → The standard for production web applications.
                   Next.js App Router with streaming support makes
                   it ideal for real-time LLM output (token streaming).

Streamlit        → Python-native dashboards. Zero HTML/CSS required.
                   Best for: data scientists building internal tools
                   and demos. Extremely fast to build.

Gradio           → ML demo interfaces. Auto-generates UI from function
                   signatures. Integrated with HuggingFace Spaces.
                   Best for: sharing model demos and prototypes.

Multimodal Interface

Whisper (audio)  → OpenAI's speech-to-text. Supports 99 languages.
                   Powers voice-to-text inputs for AI chat interfaces.

Gemini           → Google's multimodal model. Accepts image, audio,
                   video, and text as inputs. Powers vision-capable
                   AI applications.

API Protocol

REST         → The universal standard. JSON over HTTP. Works everywhere.

WebSockets   → Bidirectional, persistent connection. Essential for
               real-time token streaming (the "typing" effect in
               LLM chat interfaces).

GraphQL      → Flexible query language. Clients request exactly
               what they need. Useful for complex AI applications
               with multiple data models.

Stream LLM output ด้วย Next.js + Vercel AI SDK:

// app/api/chat/route.ts
import { streamText } from 'ai';
import { gateway } from '@ai-sdk/gateway';

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = streamText({
    // Routed through Vercel AI Gateway: auth, failover, and cost tracking
    model: gateway('anthropic/claude-sonnet-4.6'),
    messages,
  });

  return result.toUIMessageStreamResponse();  // streams tokens to the browser
}
// app/chat/page.tsx
'use client';
import { useChat } from '@ai-sdk/react';

export default function ChatPage() {
  const { messages, sendMessage } = useChat();
  const [input, setInput] = useState('');

  return (
    <div>
      {messages.map(m => <div key={m.id}>{m.role}: {m.content}</div>)}
      <form onSubmit={e => { e.preventDefault(); sendMessage({ text: input }); setInput(''); }}>
        <input value={input} onChange={e => setInput(e.target.value)} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

ประกอบร่างทั้งหมด: Reference Architecture

ลองดูว่า 10 layer ต่อกันยังไงใน product จริง โดยใช้ AI assistant สำหรับ customer support เป็นตัวอย่าง:

User (browser)
  │  WebSocket stream
  ▼
Layer 10: Next.js frontend  ←→  REST/WebSocket API
  │
  ▼
Layer 9:  Auth0 validates JWT  →  Guardrails AI screens input
  │
  ▼
Layer 8:  FastAPI inference service  (KServe on Kubernetes)
  │
  ├──────────────────────────────────────────────────┐
  ▼                                                  ▼
Layer 6: LangGraph agent                    Layer 5: RAG pipeline
  (ReACT loop)                               Pinecone vector search
  │   uses tools:                            LlamaIndex retrieval
  │   - search_tickets()                     OpenAI embeddings
  │   - lookup_order_status()                         │
  └─────────────────────────┬──────────────────────────┘
                            ▼
                     Layer 7: Fine-tuned LLM
                     (MLflow registry, ONNX-optimized)
                            │
  ┌─────────────────────────┘
  ▼
Layer 4: Model was trained on:
  - PyTorch + HuggingFace
  - Weights & Biases tracked runs
         ▼
Layer 3: Kubernetes + Argo Workflows automated training pipeline
         ▼
Layer 2: Evidently AI monitors for answer drift
         Prometheus + Grafana watches latency
         ▼
Layer 1: Customer tickets in MongoDB
         Product data in PostgreSQL
         Airflow + dbt refreshes embeddings daily

ข้อความจาก user แต่ละข้อความวิ่งผ่านทั้ง stack ภายในไม่ถึงสองวินาที และทุก component เปลี่ยนตัวได้หมด จะสลับ Pinecone เป็น Weaviate, FastAPI เป็น gRPC หรือ Auth0 เป็น Clerk ก็ได้ เพราะแต่ละ layer มี interface แยกกันชัดเจน


เลือก Stack ยังไงดี: คู่มือฉบับใช้งานจริง

ไม่ใช่ทุก app ที่ต้องจัดเต็มครบ 10 layer ตั้งแต่วันแรก ค่อยๆ เพิ่มตามระยะแบบนี้:

Prototype (วันที่ 1–7):

Data: Local files or MongoDB Atlas free tier
Model: OpenAI API (no training needed)
RAG: LlamaIndex + FAISS (local)
Interface: Streamlit or Gradio
Skip: MLOps infrastructure, model versioning, compliance

Beta (สัปดาห์ที่ 2–8):

Add: FastAPI serving, Docker, Postgres
Add: MLflow experiment tracking
Add: Prometheus + Grafana basic monitoring
Add: Auth0 for user auth, JWT for API security
Interface: Migrate to Next.js for production UX

Production (เดือนที่ 3 ขึ้นไป):

Add: Kubernetes, Argo/Flyte pipelines
Add: Pinecone or Weaviate managed vector DB
Add: Arize AI or Evidently for model monitoring
Add: Guardrails AI for LLM safety
Add: ONNX + Triton for optimized serving
Add: SOC2 audit preparation if targeting enterprise


Summary

AI application ยุคใหม่ในปี 2026 ไม่ได้มีแค่ model แต่เป็น ระบบ 10 layer แต่ละ layer แก้ปัญหาเฉพาะทางที่ layer อื่นแก้แทนไม่ได้

Layer 1 (Data) คือต้นทางของทุกอย่าง data ที่สะอาด มี version และมีโครงสร้างดี เป็น asset ที่ยิ่งสะสมยิ่งมีค่า และทำให้ทุก model ดีขึ้นเรื่อยๆ Layer 2 (Monitoring) ทำให้คุณรู้ว่าระบบมีปัญหาก่อน user จะเจอ Layer 3 (MLOps) ทำให้ pipeline reproduce ได้และ scale ได้ Layer 4 (Model Development) คือส่วนที่ PyTorch, HuggingFace และ MLflow รับหน้าที่ training Layer 5 (RAG) ใช้ vector database กับ embedding model เติมความรู้ล่าสุดและข้อมูลภายในให้ LLM จนใช้งานได้จริง Layer 6 (Agents) ยกระดับระบบจากแค่ตอบคำถาม ไปเป็นใช้ tool ทำงานจนจบ Layer 7 (Versioning) ทำให้ทุก model ที่ deploy ไปแล้ว trace ย้อนกลับไปหา training data และ code ได้ Layer 8 (Deployment) เปลี่ยน model artifact ให้เป็น service จริงที่ scale ได้ Layer 9 (Security) คือสิ่งที่ลูกค้า enterprise ขอดูก่อนเซ็นสัญญา Layer 10 (Frontend) คือส่วนที่ user มองเห็นจริงๆ

ข่าวดีคือปี 2026 ทุก layer มี tool ที่ mature และผ่านสนามจริงมาแล้ว ไม่ต้องสร้างเองจากศูนย์สักอย่าง สิ่งที่ต้องคิดให้ขาดคือ เลือก tool ให้เหมาะกับ scale ของตัวเอง รู้ว่า layer ไหนทำให้เรียบง่ายไว้ก่อนได้ และ รู้ว่า layer ไหนห้ามข้ามเด็ดขาด ซึ่ง monitoring กับ security คือสองตัวที่คนข้ามบ่อยที่สุด และเจ็บหนักที่สุดเวลาข้าม

เริ่มจาก Layer 1 แล้วค่อยๆ ไต่ขึ้นไป แต่อย่า deploy ก่อนจะมี Layer 2


อยากถามเรื่องเลือก tool ให้ stack ของตัวเอง? ทิ้ง comment ไว้ข้างล่างได้เลย ผมยินดีช่วยชั่งข้อดีข้อเสียตาม use case ของคุณ

มีคำถามหรืออยากคุยต่อ? ติดต่อผมได้ทาง LinkedIn, X หรือส่ง email มาได้เลย

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.