← Writing
AI & Generative AI

Agentic RAG

Data Mastery Series — Episode 51: เปลี่ยน RAG ให้ “คิด” ได้

14 Apr 202514 min readLangChainLangGraphRAGAI AgentMachine Learning
Advanced RAG · Part 2 of 4

Agentic RAG

Data Mastery Series — Episode 51: เปลี่ยน RAG ให้ “คิด” ได้

📌 Connect with me and follow our journey: Linkedin, Facebook

ใน Episode 50 เราได้เรียนรู้วิธีสร้าง Agent ที่มีความสามารถมากขึ้นด้วย LangGraph — ตั้งแต่การใช้ LLM พื้นฐาน, การเสริม Search Tool เพื่อดึงข้อมูลจากภายนอก, ไปจนถึงการเพิ่ม Memory ที่ช่วยให้ Agent จดจำบริบทในการสนทนาได้อย่างต่อเนื่อง

วันนี้ เราจะพาไปอีกระดับ ด้วยแนวคิด Agentic RAG — การผสาน ความสามารถในการตัดสินใจของ Agent เข้ากับกระบวนการ Retrieval-Augmented Generation (RAG) เพื่อให้ระบบสามารถวางแผน, ดึงข้อมูล, และตอบคำถามได้อย่างแม่นยำและชาญฉลาดยิ่งขึ้น

1. Agentic RAG คืออะไร?

Agentic RAG คือการเสริม “ความสามารถในการคิดและตัดสินใจ” ให้กับ RAG แบบดั้งเดิม โดยเพิ่ม AI Agent เข้ามาใน pipeline เพื่อทำหน้าที่สำคัญ เช่น:

  • ตัดสินใจว่าจะค้นข้อมูลจากแหล่งใด
  • ปรับคำถามหรือคำค้นให้เหมาะสม
  • ตรวจสอบและกลั่นกรองข้อมูลที่ได้
  • และวางแผนการตอบกลับอย่างเป็นระบบ

💡 พูดง่าย ๆ:

RAG ที่ไม่ใช่แค่ “ค้นแล้วตอบ” แต่เป็น RAG ที่ “รู้จักคิดก่อนตอบ”

Figure: Agentic RAG vs Traditional RAG

Agentic RAG ทำงานอย่างไร?

ระบบ Agentic RAG มี 4 องค์ประกอบหลักที่ทำให้มัน “ฉลาด” กว่าเดิม:

  1. Autonomous Reasoning: Agent วิเคราะห์คำถามและตัดสินใจเองว่าควรค้นข้อมูลหรือไม่, ใช้เครื่องมือไหน, หรือควรปรับคำถามก่อน
  2. Dynamic Retrieval: ไม่จำกัดที่ vector DB เท่านั้น แต่สามารถค้นจาก Web, เรียก API, ดูอีเมล หรือแม้แต่ใช้ calculator
  3. Augmented Generation: ข้อมูลที่ดึงมา จะถูกวิเคราะห์เพิ่มเติมก่อนส่งเข้า LLM เพื่อสร้างคำตอบที่ “เข้าใจบริบทจริง ๆ”
  4. Feedback Loop: Agent จะเรียนรู้จากการโต้ตอบก่อนหน้า และสามารถปรับกระบวนการตอบคำถามให้ดีขึ้นในรอบถัดไป

ตัวอย่าง Use Case ที่น่าสนใจ

  • Customer Support: ตอบคำถามทั่วไปทันที หรือดึงข้อมูล API มาใช้เมื่อจำเป็น
  • Healthcare: ค้น Guideline ล่าสุด + วิเคราะห์ประวัติผู้ป่วยเพื่อช่วยวินิจฉัย
  • Business Reporting: รวบรวม KPI → วิเคราะห์ → เสนอ Insight
  • Education: ปรับเนื้อหาให้ตรงกับระดับความเข้าใจของผู้เรียนแต่ละคน

ข้อจำกัดของ Agentic RAG

แม้จะทรงพลัง แต่ Agentic RAG ก็มีข้อควรพิจารณา เช่น:

  • ❗ ซับซ้อนกว่าเดิม: ต้องออกแบบ Flow และ Logic อย่างรอบคอบ
  • 💰 ต้นทุนสูงขึ้น: ใช้หลายรอบ → เปลือง Token
  • 🤖 มีโอกาสตัดสินใจผิด: มีโอกาสหลุด logic หรือ “หลอน” ถ้า agent ตัดสินใจผิดพลาด

ดังนั้น การวางโครงสร้าง agent และใส่ fallback mechanism (แผนสำรอง ที่ระบบจะใช้เมื่อตัวหลักทำงานผิดพลาด หรือไม่สามารถให้ผลลัพธ์ที่ต้องการได้) จึงเป็นสิ่งสำคัญ

2. เริ่มต้นใช้งาน Agentic RAG

หลังจากที่เราเข้าใจแนวคิด Agentic RAG แล้ว คราวนี้เราจะมาดู ตัวอย่างการใช้งานจริง โดยอ้างอิงจาก LangChain’s official demo

ในตัวอย่างนี้ เราจะใช้ LangGraph เพื่อสร้าง Agent ที่สามารถ:

  • วิเคราะห์คำถามของผู้ใช้
  • เลือกว่าจะใช้ Tool หรือไม่
  • ตรวจสอบว่าข้อมูลที่ได้ “เกี่ยวข้อง” หรือไม่
  • และสุดท้าย ตอบคำถามอย่างมีบริบท

1️⃣ Load เอกสาร และสร้าง Vectorstore

ขั้นตอนแรกคือการโหลดข้อมูลต้นทาง เช่น blog posts ของ Lilian Weng และจัดเก็บไว้ใน Vector Store เพื่อให้ LLM ค้นหาข้อมูลที่เกี่ยวข้องได้

1. Load documents and create vectorstore

urls = [
"https://lilianweng.github.io/posts/2023-06-23-agent/",
"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/",
]

docs = [WebBaseLoader(url).load() for url in urls]
docs_list = [item for sublist in docs for item in sublist]

text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=100, chunk_overlap=50
)
doc_splits = text_splitter.split_documents(docs_list)

vectorstore = Chroma.from_documents(
documents=doc_splits,
collection_name="rag-chroma",
embedding=OpenAIEmbeddings(),
persist_directory="db",
)

retriever = vectorstore.as_retriever()

📝 สรุป: เตรียมข้อมูลด้านบน เพื่อช่วยในการทำ RAG

2️⃣ สร้าง Tool สำหรับ Retrieval

สร้าง Tool ใหม่ที่ชื่อว่า Retriever Tool ที่จะให้ Agent เรียกใช้ได้ตามบริบท

2. Create retriever tool

retriever_tool = create_retriever_tool(
retriever,
"retrieve_blog_posts",
"Search and return information about Lilian Weng blog posts.",
)

tools = [retriever_tool]

3️⃣ เขียน Node Functions ที่จำเป็น

เราจะนิยาม 4 ฟังก์ชันสำคัญ ที่แต่ละ Node ใน LangGraph จะเรียกใช้ ได้แก่:

  • agent: ตัดสินใจว่าจะใช้ Tool หรือไม่

def agent(state):
messages = state["messages"]
model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4o")
model = model.bind_tools(tools)
response = model.invoke(messages)
return {"messages": [response]}

  • grade_documents: ตรวจสอบว่าข้อมูลที่ได้ “เกี่ยวข้อง” หรือไม่

def grade_documents(state) -> Literal["generate", "rewrite"]:
class Grade(BaseModel):
binary_score: str = Field(description="Relevance score 'yes' or 'no'")

model = ChatOpenAI(temperature=0, model="gpt-4o", streaming=True)  
llm_with_tool = model.with_structured_output(Grade)  

prompt = PromptTemplate(  
    template="""You are a grader...""", # ย่อเพื่อความกระชับ  
    input_variables=["context", "question"],  
)  

chain = prompt | llm_with_tool  
messages = state["messages"]  
question = messages[0].content  
docs = messages[-1].content  
result = chain.invoke({"question": question, "context": docs})  
return "generate" if result.binary_score.lower() == "yes" else "rewrite"
  • rewrite: ปรับคำถามใหม่ให้ชัดเจนขึ้น

def rewrite(state):
messages = state["messages"]
question = messages[0].content
msg = [HumanMessage(content=f"""
Here is the initial question:\n ------- \n{question}\n ------- \n
Please rephrase it to make it clearer or more specific.
""")]
model = ChatOpenAI(temperature=0, model="gpt-4o", streaming=True)
response = model.invoke(msg)
return {"messages": [response]}

  • generate: ตอบคำถามโดยใช้ context ที่ดึงมา

def generate(state):
messages = state["messages"]
question = messages[0].content
docs = messages[-1].content

# ✅ Format context  
if isinstance(docs, str):  
    context = docs  
elif isinstance(docs, list):  
    context = "\n\n".join([doc.page_content for doc in docs])  
else:  
    context = str(docs)  

prompt = hub.pull("rlm/rag-prompt")  
llm = ChatOpenAI(model_name="gpt-4o", temperature=0, streaming=True)  
rag_chain = prompt | llm | StrOutputParser()  
response = rag_chain.invoke({"context": context, "question": question})  
return {"messages": [response]}

4️⃣ สร้าง Graph Workflow ด้วย LangGraph

เมื่อเรามีทุก Node พร้อมแล้ว ก็ถึงเวลาต่อเป็นกราฟ:

5. Build LangGraph

workflow = StateGraph(AgentState)
workflow.add_node("agent", agent)
workflow.add_node("retrieve", ToolNode([retriever_tool]))
workflow.add_node("rewrite", rewrite)
workflow.add_node("generate", generate)

workflow.add_edge(START, "agent")
workflow.add_conditional_edges("agent", tools_condition, {
"tools": "retrieve",
END: END
})

workflow.add_conditional_edges("retrieve", grade_documents, {
"generate": "generate",
"rewrite": "rewrite"
})
workflow.add_edge("generate", END)
workflow.add_edge("rewrite", "agent")

graph = workflow.compile()

เมื่อรันโค้ดนี้ LangGraph จะสร้าง workflow แบบมีเงื่อนไข (conditional flow) ที่ Agent สามารถตัดสินใจเองได้ว่าจะ:

  • ใช้ Tool
  • ปรับคำถาม
  • หรือสร้างคำตอบเลยทันที

Figure: โครงสร้างของ Graph กรณี Agentic RAG

5️⃣ Run และดูผลลัพธ์

Figure: Result เมื่อถามว่า What does Lilian Weng say about the types of agent memory?

Figure: Result เมื่อถามว่า Recommend food from Thailand 3 item

จะเห็นได้ว่า Chatbot สามารถเลือกได้ว่าจะตอบเองเมื่อไหร่ (ดังรูปที่ 2) และจะดึงข้อมูล (retrieve) มาช่วยเพิ่มความสามารถในการตอบคำถามเมื่อไหร่ (ดังรูปที่ 1)

3. ทดลองรูปแบบอื่น ๆ ของ Agentic RAG

นอกจากโครงสร้างพื้นฐานที่เราได้ลองสร้างในตัวอย่างก่อนหน้าแล้ว เรายังสามารถทดลองปรับเปลี่ยนรูปแบบของ Agentic RAG ให้ตอบโจทย์แต่ละ Use Case ได้มากยิ่งขึ้น โดยในส่วนนี้ ผมจะสาธิต 2 รูปแบบที่ปรับจาก official demo เพื่อให้เห็นถึงความยืดหยุ่นของ LangGraph ในการสร้าง Agent Workflow

1️⃣ ปรับแบบที่ 1: ตัด Rewrite เพิ่ม Tool

ในรูปแบบนี้ เราทดลองเปลี่ยนจากการดึงข้อมูล blog post → มาใช้ เอกสารเฉพาะทาง (ในที่นี้คือนิทาน “ลูกหมู 3 ตัว”) โดย:

  • ✅ ตัดฟังก์ชัน rewrite ออก
  • ➕ เพิ่ม Node สำหรับ Search Tool (เช่น Tavily) เพื่อดึงข้อมูลแบบ real-time

Figure: โครงสร้างของ Graph กรณีเพิ่ม Tool

ผลลัพธ์ที่ได้จากการทดลอง

Question: What are the name of 3 little pigs?
Answer: The names of the three little pigs are Khao Suay, Khao Hom, and Khao Suk.
Route: start --> reception --> retrieve --> generate --> end
##################################################
Question: ผมชื่อนัท
Answer: ยินดีที่ได้รู้จักครับ คุณนัท! มีอะไรที่ผมสามารถช่วยเหลือหรือแนะนำได้บ้างครับ?
Route: start --> reception --> end
##################################################
Question: ผมชื่ออะไรนะ
Answer: คุณบอกว่าชื่อ "นัท" ครับ!
Route: start --> reception --> end
##################################################
Question: What is Real Madrid soccer result (13 Apr 2025)
Answer: Real Madrid won 1-0 against Alavés on April 13, 2025.
Route: start --> reception --> tools --> generate --> end
##################################################

2️⃣ ปรับแบบที่ 2: แยก Node การ Generate ตามประเภท

ในเวอร์ชันนี้ เราแยกกระบวนการตอบออกเป็น Node ต่างหากตามประเภทของคำถาม

  • story_response: สำหรับข้อมูลจากเอกสาร
  • chat_response: สำหรับ general Q&A
  • search_response: สำหรับข้อมูลอัปเดตจาก search tools

Figure: โครงสร้างของ Graph กรณีแยก Response Type ตาม Use Case

ผลลัพธ์ที่ได้จากการทดลอง

Question: What are the name of 3 little pigs?
Answer: The names of the three little pigs are Khao Suay, Khao Hom, and Khao Suk.
Route: start --> reception --> retrieve --> story_response --> end
##################################################
Question: ผมชื่อนัท
Answer: ยินดีที่ได้รู้จักครับ คุณนัท! มีอะไรที่ผมสามารถช่วยเหลือหรือพูดคุยด้วยได้บ้างครับ?
Route: start --> reception --> chat_response --> end
##################################################
Question: What is Generative AI?
Answer:
"""
Generative AI refers to a category of artificial intelligence systems designed to generate new content, such as text, images, music, or other data, that is similar to the data they were trained on. These systems use machine learning models, particularly deep learning techniques, to learn patterns and structures from existing data and then create new instances that mimic those patterns.
Key components and concepts related to generative AI include:

  1. Generative Adversarial Networks (GANs): A popular framework for generative AI, GANs consist of two neural networks—a generator and a discriminator—that are trained together. The generator creates new data instances, while the discriminator evaluates them against real data, providing feedback to improve the generator's outputs.
  2. Variational Autoencoders (VAEs): Another approach to generative modeling, VAEs learn to encode input data into a compressed representation and then decode it back to the original form, allowing for the generation of new data by sampling from the latent space.
  3. Transformer Models: These models, such as GPT (Generative Pre-trained Transformer), are particularly effective in generating human-like text. They use attention mechanisms to understand context and generate coherent and contextually relevant text.
  4. Applications: Generative AI has a wide range of applications, including creating realistic images and videos, generating music and art, writing articles and stories, designing products, and even drug discovery.
    Generative AI is a rapidly evolving field with significant potential to impact various industries by automating creative processes and enabling new forms of content creation. However, it also raises ethical considerations, such as the potential for misuse in creating deepfakes or generating misleading information.
    """
    Route: start --> reception --> chat_response --> end
    ##################################################
    Question: ผมชื่ออะไรนะ
    Answer: คุณบอกว่าชื่อ "นัท" ครับ! มีอะไรที่ผมสามารถช่วยเหลือเพิ่มเติมได้ไหมครับ?
    Route: start --> reception --> chat_response --> end
    ##################################################
    Question: What is Real Madrid soccer result (13 Apr 2025)
    Answer: Real Madrid won 1-0 against Alavés on April 13, 2025.
    Route: start --> reception --> tool_planner --> TavilySearch --> search_response --> end
    ##################################################

ในบทความนี้ เราได้เห็นว่า Agentic RAG ไม่ใช่แค่การเชื่อม LLM เข้ากับฐานข้อมูลเท่านั้น แต่เป็นการยกระดับให้ระบบสามารถ “วิเคราะห์ก่อนลงมือ”, “เลือกแหล่งข้อมูลที่เหมาะสม”, “กลั่นกรองสิ่งที่เกี่ยวข้อง” และที่สำคัญคือ “เรียนรู้และปรับตัวจากการสนทนาเดิม” ได้อย่างชาญฉลาด ทั้งหมดนี้สามารถสร้างได้ง่ายด้วย LangGraph ที่เปิดโอกาสให้เราร้อยเรียง Node และกำหนด Flow แบบมีเงื่อนไขได้อย่างยืดหยุ่น

ในตอนถัดไป เราจะก้าวไปอีกขั้นกับ Adaptive RAG — RAG ที่ไม่เพียงแค่ค้นและตอบ แต่สามารถเรียนรู้จากประสบการณ์ เพื่อให้ตอบได้ดีขึ้นเรื่อย ๆ ฝากติดตามกันด้วยนะครับ ^__^


Data Science Explore the world of data science with Donato_Story

Dashboard Discover the power of data visualization with Donato_Story

Donato_Journey Join me on my journey (Thai version)

Course_Review Discover the training courses with Donato_Story (Thai version)

Let’s Connect!

Your thoughts and feedback are invaluable. Feel free to share them in the comments or connect with me on

Originally published on Medium

Related