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

RAG และ LLMOps: สร้าง AI Second Brain ให้พร้อมขึ้น Production

คุณทำ RAG chatbot ที่รันบน laptop ได้ดีมาก ถามอะไรจาก PDF ไม่กี่ไฟล์ก็ตอบได้ คำตอบดูฉลาด ตื่นเต้นสุด ๆ แต่พอจะเอาขึ้น production จริง ทุกอย่างกลับยุ่งไปหมด

Knowledge base จะอัปเดตให้ทันได้ยังไง? LLM เริ่มตอบมั่วเมื่อไหร่ จะรู้ได้ยังไง? จะ fine-tune model ด้วยข้อมูลของเราเองยังไงไม่ให้ของที่ใช้ได้อยู่แล้วพัง? มี query วันละ 10,000 ตัว จะเฝ้ายังไงว่าคุณภาพไม่ตก?

โจทย์พวกนี้แหละคืองานของ LLMOps

โพสต์นี้จะพาดู architecture ครบทั้งระบบที่ใช้งานได้จริง เป็น Second Brain AI assistant ที่รวม RAG, LLM ที่ fine-tune เอง, agentic inference และ observability layer ไว้ด้วยกัน ใช้ pattern แบบเดียวกับที่ทีม ML ระดับท็อปรันใน production ปี 2026 เราจะไล่ทุก step ที่มีหมายเลขในระบบ บอก ว่าทำไม แต่ละ component ต้องมี และให้ดูโค้ดจริงไปด้วย


Part 1: LLMOps คืออะไร แล้วมีไว้ทำไม?

MLOps (Machine Learning Operations) คือวิธีทำงานที่พา ML model ขึ้น production แล้วดูแลให้ใช้งานได้ดีต่อเนื่อง ทั้ง versioning, pipeline, monitoring และ retraining MLOps ช่วยปิดปัญหา "บนเครื่องผมรันได้นะ" ของ ML แบบดั้งเดิมไปได้

LLMOps คือ MLOps ที่ปรับมาใช้กับ large language model โดยเฉพาะ แต่ LLM มีโจทย์ใหม่หลายข้อที่เครื่องมือ MLOps แบบเดิมไม่ได้ออกแบบมารับ:

โจทย์ MLOps แบบเดิม LLMOps
ขนาด model หลัก megabyte ถึง gigabyte หลายพันล้าน parameter ขนาดหลายสิบ gigabyte
Data pipeline ข้อมูลตาราง / structured Unstructured text, PDF, หน้าเว็บ
Evaluation Accuracy, F1, AUC ตอบถูกไหม, hallucination rate, citation ดีแค่ไหน
Latency หลัก millisecond หลักวินาทีต่อ token stream
ความรู้ที่ต้องทันสมัย Retrain ตามรอบ RAG ดึงข้อมูลสด + fine-tune เป็นระยะ
Output monitoring Drift ของ prediction ที่เป็นตัวเลข Semantic drift, tone, safety violation

LLMOps คือชุดเครื่องมือและวิธีทำงานที่แก้ปัญหาพวกนี้ Architecture ที่เราจะไล่ดูเป็นระบบ LLMOps เต็มชุดของ assistant แบบ "Second Brain" คือ AI ส่วนตัวที่รู้ทุกอย่างใน Notion workspace ของคุณ ถามอะไรก็ตอบได้แม่น มี citation และรับ scale ได้


Part 2: ภาพรวมทั้งระบบ

Architecture นี้มี 10 step ที่มีหมายเลข กระจายอยู่ใน 5 pipeline หลัก:

┌──────────────────────────────────────────────────────────────────┐
│                                                                  │
│  PIPELINE 1: Data Collection     Raw Notion → S3 (Markdown)     │
│                    ↓                                             │
│  PIPELINE 2: ETL + Filtering     S3 → MongoDB (quality-gated)   │
│                    ↓                         ↓                   │
│  PIPELINE 3: Dataset Generation  MongoDB → Instruct dataset      │
│                    ↓                                             │
│  PIPELINE 4: Training            Dataset → Fine-tuned LLM        │
│                    ↓                                             │
│  PIPELINE 5: RAG Feature         LLM + Docs → Vector Index      │
│                    ↓                                             │
│  PIPELINE 6: Inference           User Q → Retriever → Agent → A │
│                    ↓                                             │
│  PIPELINE 7: Observability       Traces → Monitoring + Eval      │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘

Tools: ZenML (pipelines), MongoDB (docs), opik (observability), unsloth (fine-tuning)

ไล่ไปทีละ step กันเลย


Part 3: ชั้นข้อมูล (Step 1–3)

Step 1 — Data Collection Pipeline: ดึงจาก Notion ไปเก็บใน S3

ทุกอย่างเริ่มที่ raw data ระบบนี้ใช้ Notion เป็นแหล่งความรู้ เครื่องมือที่หลายคนใช้ทำ wiki ส่วนตัว เอกสารบริษัท และจดโน้ตงานวิจัยกันอยู่แล้ว

Data Collection Pipeline ดึงทุกหน้าใน Notion ออกมาแปลงเป็น Markdown ทั้ง stack ใช้ Markdown เป็น format กลาง เพราะ LLM อ่านและเขียนได้คล่อง ไฟล์เบา และเก็บเป็น plain text ใน S3 ได้สบาย ๆ

# Pseudo-code: collect and store Notion pages
import boto3
from notion_client import Client

notion = Client(auth=NOTION_TOKEN)
s3 = boto3.client("s3")

def collect_notion_pages(database_id: str) -> None:
    pages = notion.databases.query(database_id=database_id)["results"]

    for page in pages:
        content = export_page_as_markdown(page["id"])  # Notion → Markdown
        s3.put_object(
            Bucket="my-second-brain",
            Key=f"notion/{page['id']}.md",
            Body=content.encode("utf-8"),
        )

S3 bucket ตัวนี้คือ raw data lake ของคุณ เป็น snapshot ของข้อมูลทั้งหมดแบบดิบ ๆ ยังไม่ผ่านการ transform ใด ๆ

Step 2 — ETL Pipeline: จาก S3 เข้า MongoDB

ETL (Extract, Transform, Load) pipeline อ่านไฟล์ Markdown จาก S3 แล้วโหลดเข้า MongoDB ที่เลือก MongoDB เพราะเก็บ document เป็น object หน้าตาคล้าย JSON ที่ยืดหยุ่น จะแปะ metadata (author, เวลาอัปเดตล่าสุด, source URL, resource ที่ crawl มา) ไว้คู่กับเนื้อหาดิบก็ทำได้ง่าย

นอกจากนี้ pipeline ยัง ingest external resource ที่ crawl มา ด้วย เช่น บทความ หน้าเอกสาร และเนื้อหาจากเว็บที่ช่วยเติมโน้ตใน Notion ให้ครบขึ้น

# ETL: load a Markdown file into MongoDB with metadata
from pymongo import MongoClient
from datetime import datetime

db = MongoClient(MONGO_URI)["second_brain"]

def load_to_mongo(page_id: str, content: str, metadata: dict) -> None:
    db.documents.update_one(
        {"page_id": page_id},
        {"$set": {
            "content": content,
            "metadata": metadata,
            "source": "notion",
            "loaded_at": datetime.utcnow(),
            "quality_score": None,  # filled by the filter step
        }},
        upsert=True,
    )

Step 3 — Quality Filtering: กรองสองชั้น

หน้า Notion ไม่ได้มีค่าพอจะเอาเข้าระบบทุกหน้า Workspace ส่วนตัวเต็มไปด้วยหน้าที่มีแค่หัวข้อ โน้ตที่เขียนค้างไว้ และเนื้อหาที่แทบไม่มีสาระ ป้อนขยะเข้า RAG เมื่อไหร่ คำตอบก็แย่ลงทันที

Architecture นี้เลยใช้ quality filter สองชั้น:

MongoDB (all documents)
       ↓
  Filter 1: Medium-to-high quality
  (removes obvious low-quality: <200 words, no headers, mostly bullet fragments)
       ↓
  Medium/High quality docs → RAG Feature Pipeline (used for embeddings)
       ↓
  Filter 2: High quality only
  (stricter: well-structured, >500 words, factually dense)
       ↓
  High quality docs → Dataset Generation Pipeline (used for fine-tuning)

ประเด็นสำคัญคือ fine-tuning ต้องใช้ข้อมูลสะอาดกว่า RAG ฝั่ง RAG ถ้ามี document คุณภาพกลาง ๆ หลุดเข้ามา อย่างมากก็แค่โดน retrieve น้อยหน่อย ยังพอรับได้ แต่ฝั่ง fine-tuning ตัวอย่าง training ที่เขียนแย่จะทำให้ model เรียนพฤติกรรมเพี้ยนไปเลย

ตัวอย่าง function ให้คะแนนคุณภาพที่เอาไปใช้ได้จริง:

def score_document(content: str) -> float:
    score = 0.0
    words = len(content.split())

    if words > 200: score += 0.2
    if words > 500: score += 0.2
    if "## " in content: score += 0.2      # has section headers
    if content.count("\n") > 10: score += 0.2  # well-structured
    if not content.startswith("TODO"): score += 0.2  # not a stub

    return score  # 0.0 to 1.0

# threshold: >= 0.4 → medium quality (RAG)
#            >= 0.8 → high quality (fine-tuning)

Part 4: Fine-Tuning Pipeline (Step 4–5)

Step 4 — Dataset Generation: เปลี่ยน Doc คุณภาพสูงเป็น Instruct Dataset

Fine-tuning ใช้ document ดิบไม่ได้ ต้องเป็น instruction-response pair Dataset Generation pipeline จึงแปลง document คุณภาพสูงให้เป็น Summarization Instruct Dataset หน้าตาประมาณนี้:

{
  "instruction": "Summarize the following Notion page about Transformer architecture.",
  "input": "## Transformers\nTransformers use self-attention...",
  "output": "Transformers are a neural network architecture that replaces RNNs with self-attention, allowing parallel processing of sequences and capturing long-range dependencies efficiently."
}

Dataset ชุดนี้เก็บไว้ใน Data Registry ซึ่งเป็นที่เก็บ training dataset แบบมี version และตรวจย้อนหลังได้ ทุก model ที่ train ออกมาจะย้อนดูได้เป๊ะ ๆ ว่าใช้ dataset version ไหน

Step 5 — Training Pipeline: Fine-Tune LLM สำหรับงานสรุป

Training Pipeline เอา instruct dataset มา fine-tune LLM ให้เก่งงาน summarization โดยเฉพาะ คือย่อหน้า Notion ยาว ๆ ให้เหลือสรุปที่สั้น กระชับ และแม่น

ปี 2026 งานนี้ใช้ LoRA + unsloth ประหยัดกว่าและเร็วกว่า full-parameter training แบบคนละเรื่อง:

from unsloth import FastLanguageModel
from trl import SFTTrainer
from transformers import TrainingArguments

# Load base model with 4-bit quantization
model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/llama-3-8b-bnb-4bit",
    max_seq_length=2048,
    load_in_4bit=True,
)

# Inject LoRA adapters (trains only ~1% of parameters)
model = FastLanguageModel.get_peft_model(
    model,
    r=16,                  # LoRA rank
    target_modules=["q_proj", "v_proj"],
    lora_alpha=16,
    lora_dropout=0.05,
)

trainer = SFTTrainer(
    model=model,
    tokenizer=tokenizer,
    train_dataset=summarization_dataset,
    dataset_text_field="text",
    args=TrainingArguments(
        output_dir="./summarization-llm",
        num_train_epochs=3,
        per_device_train_batch_size=4,
        learning_rate=2e-4,
    ),
)
trainer.train()

Model ที่ fine-tune เสร็จแล้วจะ push ขึ้น Model Registry ซึ่งเป็นที่เก็บแบบมี version เหมือน Data Registry ทุก model artifact มี metadata ของ training run เก็บคู่ไว้ด้วย


Part 5: RAG Feature Pipeline (Step 6–8)

ส่วนนี้คือหัวใจของระบบ RAG Feature Pipeline สร้าง knowledge base ที่ค้นหาได้ ไว้ให้ inference layer query ตอน runtime

Step 6 — โหลด LLM ที่ Fine-Tune ไว้

Pipeline โหลด summarization LLM จาก Model Registry ขึ้นมา ตรงนี้ model ไม่ได้มีหน้าที่ตอบคำถาม แต่มีไว้ สรุป แต่ละ document ก่อนเอาไปทำ embedding

ทำไมต้องสรุปก่อน embed? หน้า Notion ยาว 3,000 คำ ถ้า embed ทั้งก้อน vector ที่ได้จะอัดความหมายไว้แน่นมาก เอาไป match กับ query สั้น ๆ ของ user ได้ไม่แม่น ส่วนสรุปสั้น ๆ 150 คำจะได้ vector ที่ใกล้กับสิ่งที่ user ต้องการมากกว่าเยอะ

Step 7 — Ingest Document คุณภาพกลางถึงสูง

Pipeline อ่าน document ที่ผ่าน filter แล้วจาก MongoDB แต่ละ document จะได้ของสองอย่าง: - Doc chunk: document ดิบที่หั่นเป็นท่อน ๆ - Summary: สรุปของ chunk นั้นที่ LLM เขียนให้

จากนั้นเอาทั้งสองอย่างไป embed

Step 8 — Embed แล้วทำ Index

from sentence_transformers import SentenceTransformer
import numpy as np

embed_model = SentenceTransformer("BAAI/bge-large-en-v1.5")

def embed_and_index(doc_id: str, content: str, summary: str) -> None:
    # Embed both raw chunk and its summary
    doc_vector = embed_model.encode(content)
    summary_vector = embed_model.encode(summary)

    # Store in Vector Index (e.g., Qdrant, Weaviate, pgvector)
    vector_store.upsert([
        {
            "id": f"{doc_id}_doc",
            "vector": doc_vector.tolist(),
            "payload": {"type": "doc", "content": content, "doc_id": doc_id}
        },
        {
            "id": f"{doc_id}_summary",
            "vector": summary_vector.tolist(),
            "payload": {"type": "summary", "content": summary, "doc_id": doc_id}
        },
    ])

เก็บทั้ง chunk ดิบและ summary ไว้คู่กัน retriever จะมีสองทางให้ match กับ query ทางแรกคือถ้อยคำตรง ๆ ในข้อความต้นฉบับ อีกทางคือความหมายของ summary ที่ย่อมาแล้ว

ผลที่ได้คือ Vector Index ฐานข้อมูล embedding ที่ document แต่ละตัวเป็นจุดหนึ่งใน high-dimensional space พอมี query เข้ามา ระบบก็ดึง document ที่ความหมายใกล้เคียงที่สุดออกมาได้


Part 6: Inference Pipeline (Step 9)

ส่วนนี้คือสิ่งที่ user ได้ใช้จริง ๆ

User Question (from UI)
        ↓
  Inference Pipeline
  ┌────────────────────────────────────┐
  │  Agentic Layer                     │
  │  ┌──────────────┐  ┌────────────┐ │
  │  │ Retriever    │  │Summarization│ │
  │  │ Tool         │  │Tool         │ │
  │  └──────┬───────┘  └─────┬──────┘ │
  │         │                │        │
  │         └───── Agent ────┘        │
  └─────────────────┬─────────────────┘
                    ↓
               Answer (to UI)

Agentic Layer

Inference pipeline ไม่ได้ทำแค่ retrieve แล้ว generate รอบเดียวจบ แต่มี Agentic Layer คอยคุม tool สองตัว:

Retriever Tool รับคำถามของ user ไป embed แล้ว query Vector Index ได้ top-K chunk ที่เกี่ยวที่สุดกลับมา

def retriever_tool(question: str, top_k: int = 5) -> list[dict]:
    query_vector = embed_model.encode(question)
    results = vector_store.search(
        query_vector=query_vector.tolist(),
        limit=top_k,
    )
    return [{"content": r.payload["content"], "score": r.score} for r in results]

Summarization Tool ถ้า chunk ที่ดึงมายาวเกิน context window ก็เรียก summarization LLM ที่ fine-tune ไว้มาย่อก่อน แล้วค่อยส่งต่อให้ answer LLM

def summarization_tool(text: str) -> str:
    prompt = f"Summarize the following text concisely:\n\n{text}"
    return summarization_llm.generate(prompt, max_new_tokens=200)

Agent เป็นตัวเลือกว่าจะใช้ tool ไหน ตอนไหน ด้วย loop แบบ ReACT คือ retrieve ก่อน ย่อถ้าจำเป็น แล้วค่อย generate คำตอบสุดท้ายพร้อม citation

def answer_question(question: str) -> str:
    # Step 1: Retrieve relevant chunks
    chunks = retriever_tool(question, top_k=5)

    # Step 2: Summarize if total length exceeds context budget
    context_parts = []
    for chunk in chunks:
        text = chunk["content"]
        if len(text.split()) > 300:
            text = summarization_tool(text)
        context_parts.append(text)

    context = "\n\n---\n\n".join(context_parts)

    # Step 3: Generate final answer grounded in retrieved context
    prompt = f"""Answer the question using only the context below.
If the answer isn't in the context, say so.

Context:
{context}

Question: {question}
Answer:"""

    return answer_llm.generate(prompt)

Part 7: Observability Pipeline (Step 10)

Tutorial ส่วนใหญ่ข้ามส่วนนี้ไป แต่ ส่วนนี้แหละที่ทำให้ระบบของเล่นต่างจากระบบ production

Observability Pipeline เก็บ ทุก inference interaction ไว้เป็น trace:

Every question + answer pair → Prompt Traces → Observability store (opik)
                                     ↓
                         ┌──────────────────────┐
                         │ Prompt Monitoring    │  Are prompts drifting?
                         │ LLM Evaluation       │  Is answer quality dropping?
                         └──────────────────────┘

Prompt Monitoring

ดู pattern ของ prompt ว่าเปลี่ยนไปยังไงตามเวลา: - คำถามบางแบบมีคนถามบ่อยขึ้นไหม? (แปลว่าความรู้ตรงนั้นยังมีช่องโหว่) - Prompt ยาวขึ้นเรื่อย ๆ ไหม? (อาจแปลว่า user ถามครั้งแรกแล้วยังไม่ได้คำตอบ) - มี query ไหนที่วนกลับมาซ้ำ แล้ว RAG ก็ตอบได้ไม่ดีทุกครั้งไหม?

LLM Evaluation

ระบบสุ่ม output มารัน automated evaluation แล้วให้คะแนนตามนี้:

Metric วัดอะไร
Faithfulness คำตอบใช้แค่ข้อเท็จจริงจาก context ที่ดึงมาหรือเปล่า?
Answer relevance ตอบตรงคำถามจริงไหม?
Context recall Retrieval ดึง document ที่ใช่ขึ้นมาไหม?
Hallucination rate คำตอบมีข้อความที่ไม่อยู่ใน chunk ไหนเลยหรือเปล่า?
# Using opik for observability
import opik

@opik.track
def answer_question_traced(question: str) -> str:
    with opik.trace(name="second_brain_inference") as trace:
        chunks = retriever_tool(question)
        trace.log({"retrieved_chunks": len(chunks), "question": question})

        answer = generate_answer(question, chunks)
        trace.log({"answer": answer})

        # Automated faithfulness score
        score = evaluate_faithfulness(answer, chunks)
        trace.log({"faithfulness_score": score})

        return answer

ถ้า faithfulness score ตกต่ำกว่า threshold ระบบจะ alert ให้กลับไปตรวจ RAG pipeline ดูว่า vector index ยังทันสมัยไหม หรือ model ที่ fine-tune ไว้เริ่มเพี้ยนหรือเปล่า


Part 8: ใช้ ZenML คุม Pipeline ทั้งหมด

ZenML คือกาวที่เชื่อม pipeline ทั้งหมดเข้าด้วยกัน สิ่งที่ได้คือ:

  • Pipeline versioning: ทุก pipeline run มี track ไว้ครบ ทั้ง input, output และ parameter
  • Step caching: input data ไม่เปลี่ยน ก็ข้าม step ที่คำนวณหนัก ๆ ไปได้เลย
  • Artifact tracking: dataset, model และ embedding มี version และผูกไว้กับ run ที่สร้างขึ้นมา
  • Reproducibility: pipeline run เก่าตัวไหนก็รันซ้ำให้ได้ผลเหมือนเดิมเป๊ะ
from zenml import pipeline, step

@step
def collect_notion_data() -> list[str]:
    ...  # returns list of S3 paths

@step
def filter_documents(paths: list[str]) -> list[str]:
    ...  # returns quality-filtered document paths

@step
def generate_embeddings(doc_paths: list[str]) -> None:
    ...  # embeds and upserts to Vector Index

@pipeline
def rag_feature_pipeline():
    paths = collect_notion_data()
    filtered = filter_documents(paths)
    generate_embeddings(filtered)

# Run it — every artifact is versioned automatically
rag_feature_pipeline()

พอข้อมูลเปลี่ยน ZenML ให้คุณ re-run pipeline ต่อจาก step ไหนก็ได้ ส่วนที่ไม่เปลี่ยนไม่ต้องรันใหม่


Part 9: Stack ทั้งหมดในตารางเดียว

Component Tool หน้าที่
แหล่งความรู้ Notion ที่อยู่ของเนื้อหาดิบ
Raw storage AWS S3 Data lake ของไฟล์ Markdown แบบ immutable
Document store MongoDB เก็บ document พร้อม metadata และ quality score
Pipeline orchestration ZenML Pipeline run ที่มี version และรันซ้ำได้
Fine-tuning unsloth + LoRA Train summarization LLM แบบประหยัด
Model registry ZenML / MLflow เก็บ model artifact แบบมี version
Embeddings bge-large / text-embedding-3 แปลงความหมายเป็น vector
Vector index Qdrant / pgvector Approximate nearest-neighbor search ที่เร็ว
Agent framework LangChain / custom คุม retriever + summarization tool
Observability opik Trace, prompt monitoring, LLM evaluation

Summary

AI assistant ระดับ production ไม่ได้จบแค่ prompt engineering แต่เป็นระบบที่มี pipeline เจ็ดตัวทำงานต่อกัน ได้แก่ data collection, ETL และ quality filtering, dataset generation, fine-tuning, RAG feature indexing, agentic inference และ continuous observability

LLMOps คือสิ่งที่ทำให้ pipeline ทั้งเจ็ดตัวทำงานด้วยกันได้อย่างไว้ใจได้ หลักการหลายข้อยืมมาจาก MLOps แบบเดิม ทั้ง versioning, reproducibility และ monitoring แล้วต่อยอดให้รับโจทย์เฉพาะของ LLM ได้ เช่น unstructured data, semantic quality metric, hallucination detection และ embedding ที่ต้องอัปเดตให้ทัน

การตัดสินใจเชิง architecture ที่ทำให้ระบบนี้ไม่ใช่แค่โปรเจกต์เล่น ๆ ช่วงวันหยุด:

  1. กรองคุณภาพสองชั้น: fine-tuning ต้องใช้ข้อมูลสะอาดกว่า RAG เลยต้องแยก gate กัน
  2. Embed ทั้ง summary และ chunk ดิบ: retrieval recall ดีขึ้น เพราะ match ได้ทั้งถ้อยคำตรง ๆ และความหมาย
  3. Summarization LLM ที่ fine-tune เอง: model ที่สรุปเฉพาะ domain ทำงานกับ document ใน knowledge base ของคุณได้ดีกว่า model ทั่วไปแทบทุกครั้ง
  4. Agentic inference layer: พอ retriever กับ summarizer เป็น tool ที่หยิบมาประกอบกันได้ ระบบก็ยืดหยุ่นกว่า pipeline แบบตายตัวเยอะ
  5. มี observability ตั้งแต่วันแรก: faithfulness และ relevance score จับคุณภาพที่ตกได้ก่อน user จะเจอ

ปี 2026 ทุก component ในนี้มีเครื่องมือที่ mature แล้ว ZenML ใช้ทำ pipeline, MongoDB เก็บ document, unsloth ช่วยให้ fine-tune ได้ในราคาไม่แพง และ opik ดูแล observability Architecture ในโพสต์นี้ไม่ใช่ภาพฝัน ระบบ Second Brain ใน production วันนี้ก็หน้าตาแบบนี้จริง ๆ


อยากได้ repo ที่รันได้ครบทั้งระบบไหม? ทิ้ง comment ไว้ข้างล่างได้เลย ตอนนี้ผมกำลังทำ implementation เต็มชุดลง GitHub อยู่

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

Discussion

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