Basic LangChain: วิธีใช้ LangChain เพื่อทำงานกับ LLM อย่างง่าย ใน 5 ขั้นตอน—ตัวอย่างการสร้าง AI ตอบคำถามเรื่อง Mental Model

langchain เป็น framework สำหรับสร้างแอปพลิเคชั่นที่ใช้ large language model (LLM) ที่ช่วยลดความยุ่งยากการเรียกใช้งาน API โดยตรง

langchain มีข้อดี 3 อย่าง:

  1. Modular: ใช้งานง่าย ด้วยการเขียนเป็นส่วน ๆ หรือ module (เหมือนเลโก้)
  2. Use case: รองรับการใช้งานหลายหลาก เพราะสามารถประกอบ module เข้าด้วยกันได้หลายแบบ (ต่อเลโก้ได้หลายแบบ)
  3. Integration: ใช้งานร่วมเครื่องมือได้กับหลากหลาย เช่น OpenAI, Hugging Face, databricks

ในบทความนี้ เรามาดูวิธีใช้ langchain เพื่อทำงานกับ LLM อย่างง่ายกัน

ถ้าพร้อมแล้ว ไปเริ่มกันเลย


  1. 🧠 Mental Model
  2. 🤖 Step 1. Set LLM
  3. 💬 Step 2. Set Prompt
  4. 📦 Step 3. Set Output Structure
  5. ⛓️‍💥 Step 4. Chain
  6. 🏃 Step 5. Run
    1. ☝️ Single Run
    2. 🎳 Batch Run
  7. 💪 Summary
  8. 🫵 Your Turn
  9. 📄 References

🧠 Mental Model

การใช้งาน langchain มีอยู่ 5 ขั้นตอน ได้แก่:

  1. Set LLM: เลือก LLM ที่ต้องการ
  2. Set prompt: สร้าง prompt สำหรับคุยกับ LLM
  3. Set output structure: กำหนดหน้าตา output ที่ต้องการ
  4. Chain: เชื่อม LLM และ prompt เข้าด้วยกัน เพื่อสร้าง pipeline ในการเรียกใช้ LLM
  5. Run: เรียกใช้งาน LLM

เราไปดูการใช้งาน ผ่านการสร้าง chatbot ตอบคำถามเกี่ยวกับ mental model กัน


🤖 Step 1. Set LLM

langchain รองรับการใช้งาน LLM หลายเจ้า เช่น:

ในตัวอย่าง เราจะเลือกใช้ Gemini โดยเริ่มจากโหลด module สำหรับเชื่อมกับ Gemini:

# Import package
from langchain_google_genai import ChatGoogleGenerativeAI

แล้วสร้าง LLM instance ขึ้นมา:

# Create model instance
llm = ChatGoogleGenerativeAI(
    model="gemini-2.5-flash",
    temperature=0.5,
    api_key="YOUR_API_KEY"
)
  • model: ชื่อ LLM ที่เราต้องการใช้งาน
  • temperature: ระดับความสุ่มของคำตอบจาก LLM (ค่ายิ่งสูง คำตอบยิ่งมีความหลากหลาย ส่วนยิ่งค่าน้อย คำตอบจะยิ่งมีความคล้ายคลึงกัน)
  • api_key: API key สำหรับใช้งาน LLM (ดูวิธีการสร้าง Gemini API key ฟรี)

💬 Step 2. Set Prompt

ในขั้นที่ 2 เราจะสร้าง prompt สำหรับคุยกับ LLM กัน:

  1. โหลด module
  2. กำหนด prompt

ขั้นย่อยที่ 1. โหลด module สำหรับสร้าง prompt:

# Import package
from langchain_core.prompts import ChatPromptTemplate

ขั้นย่อยที่ 2. กำหนด prompt โดยแยกระหว่าง:

  1. System prompt: บทบาทและสไตล์การตอบคำถามของ LLM (เช่น ผู้เชี่ยวชาญด้าน mental model)
  2. User prompt: คำถามที่จะส่งให้ LLM (เช่น บอกให้อธิบาย mental model ที่ต้องการ)

ตัวอย่าง system และ user prompts:

# Define system prompt
system_prompt = """
You are an expert curator of mental models across science, philosophy, and applied reasoning.

Your task is to explain mental models clearly and accurately using a fixed schema.

If the origin of a model is unclear or debated, state that explicitly.

Do not invent historical sources. Be concise and concrete.
"""

# Define user prompt
user_prompt = "Explain the following mental model: {model_query}"

จากนั้น ประกอบ prompts เข้าด้วยกัน:

# Create prompt template
prompts = ChatPromptTemplate.from_messages(
    [
        # System prompt
        ("system", system_prompt.strip()),

        # User prompt
        ("human", user_prompt)
    ]
)

เราสามารถดูตัวอย่าง prompt ได้ด้วย .format_messages():

# Inspect prompt template
prompts.format_messages(model_query="Pareto Principle")

ผลลัพธ์:

[SystemMessage(content='You are an expert curator of mental models across science, philosophy, and applied reasoning.\\n\\nYour task is to explain mental models clearly and accurately using a fixed schema.\\n\\nIf the origin of a model is unclear or debated, state that explicitly.\\n\\nDo not invent historical sources. Be concise and concrete.', additional_kwargs={}, response_metadata={}),
 HumanMessage(content='Explain the following mental model: Pareto Princinple', additional_kwargs={}, response_metadata={})]

📦 Step 3. Set Output Structure

ในขั้นที่ 3 เราจะกำหนดหน้าตา output ที่เราต้องการ

เช่น ถ้าเราต้องการให้คืนค่า JSON แบบนี้:

{
"model_name": "",
"origin": "",
"description": "",
"example": "",
"tags": []
}

เรากำหนดได้โดยใช้ pydantic และ typing packages แบบนี้:

# Import packages
from pydantic import BaseModel, Field
from typing import List, Literal

# Define output structure
class MentalModel(BaseModel):

    # Mental model name
    model_name: str = Field(description="The commonly accepted name of the mental model")

    # Source/origin
    origin: str = Field(
        description="Where the model comes from (person, book, field, or cultural origin)"
    )

    # Brief description
    description: str = Field(
        description="A brief explanation of what the mental model is and why it matters"
    )

    # Example
    example: str = Field(
        description="A concrete real-world example illustrating the mental model"
    )

    # Tags
    tags: List[str] = Field(
        description="Short tags such as decision-making, systems thinking, learning, philosophy"
    )

Note: ดูวิธีใช้ Pydantic

หลังกำหนดหน้าตา output แล้ว ให้ใส่เข้าไปใน LLM instance แบบนี้:

# Add output structure to LLM
llm_with_structured_output = llm.with_structured_output(MentalModel)

⛓️‍💥 Step 4. Chain

ในขั้นที่ 4 ให้เราสร้าง chain โดยเชื่อม LLM instance เข้ากับ prompts ด้วย pipe operator (|):

# Build chain
chain = prompts | llm_with_structured_output

Note: ให้มองว่า | เป็นลูกศรชี้ทางขวา (prompt → llm)


🏃 Step 5. Run

ในขั้นสุดท้าย เราจะเรียกใช้งาน chain ซึ่งทำได้ 2 แบบ:

  1. Single run: เรียกใช้ครั้งเดียว
  2. Batch run: เรียกใช้หลายครั้งพร้อมกัน

.

☝️ Single Run

เราเรียกใช้งานครั้งเดียวด้วย .invoke()

ในตัวอย่าง เราจะถามเกี่ยวกับ “compound interest” กัน:

# Run query
result = chain.invoke({"model_query": "Compound Interest"})

แสดงผลลัพธ์ใน console:

# Import package
import json

# Load result
result_dict = result.model_dump()

# Print
print(json.dumps(result_dict, indent=4))

ผลลัพธ์:

{
    "model_name": "Compound Interest",
    "origin": "Finance, Mathematics; concept dates back to ancient times, formalized in the Renaissance.",
    "description": "Compound interest is the interest on a loan or deposit calculated based on both the initial principal and the accumulated interest from previous periods. It is often called 'interest on interest' and leads to exponential growth over time, making it a powerful force in finance for both wealth creation and debt accumulation.",
    "example": "If you invest $1,000 at an annual interest rate of 5% compounded annually, after the first year you'll have $1,050. In the second year, the 5% interest is calculated on $1,050, not just the original $1,000, leading to a balance of $1,102.50. This snowball effect accelerates over decades, significantly increasing the total return compared to simple interest.",
    "tags": [
        "Finance",
        "Economics",
        "Wealth Building",
        "Decision-making",
        "Long-term thinking"
    ]
}

.

🎳 Batch Run

สำหรับการรันหลายครั้งพร้อมกัน เราจะใช้ .batch() แบบนี้:

# Create list of mental models
mental_model_queries = [
    "First Principles Thinking",
    "Occam's Razor",
    "Confirmation Bias"
]

# Create batch inputs
batch_inputs = [{"model_query": query} for query in mental_model_queries]

# Run queries
results = chain.batch(batch_inputs)

# Instantiate collector
query_collector = [result.model_dump() for result in results]

แสดงผลลัพธ์ใน console:

# Instantiate counter
i = 1

# Loop through elements in collector
for result in query_collector:

    # Print result
    print(f"👉 Query {i}:")
    print(json.dumps(result, indent=4))
    print("\\n")

    # Add 1 to counter
    i += 1

ผลลัพธ์:

👉 Query 1:
{
    "model_name": "First Principles Thinking",
    "origin": "Often attributed to Aristotle; popularized in modern business by Elon Musk.",
    "description": "First Principles Thinking involves breaking down complex problems into their most basic, fundamental truths or 'first principles,' rather than reasoning by analogy or conventional wisdom. It matters because it allows for innovative solutions by challenging assumptions and building new knowledge from the ground up.",
    "example": "Instead of accepting the high cost of batteries for electric cars, Elon Musk famously broke down a battery into its constituent raw materials (cobalt, nickel, lithium, etc.) to understand their actual cost, then sought ways to procure and assemble them more efficiently, leading to significant cost reductions and innovation.",
    "tags": [
        "Problem-solving",
        "Innovation",
        "Critical Thinking",
        "Decision-making"
    ]
}

👉 Query 2:
{
    "model_name": "Occam's Razor",
    "origin": "William of Ockham (14th-century philosopher and theologian)",
    "description": "Occam's Razor is a problem-solving principle stating that among competing hypotheses that explain an event or phenomenon equally well, the simplest solution is most likely the correct one. It advocates for parsimony, suggesting that one should not multiply entities beyond necessity, thereby favoring theories with fewer assumptions.",
    "example": "If you hear hoofbeats outside, it is more likely to be horses than zebras, assuming you are in a location where horses are common and zebras are not. The 'horse' explanation is simpler and requires fewer extraordinary assumptions.",
    "tags": [
        "Philosophy",
        "Decision-making",
        "Problem-solving",
        "Critical thinking",
        "Science"
    ]
}

👉 Query 3:
{
    "model_name": "Confirmation Bias",
    "origin": "Psychology; early concepts traced to Francis Bacon's Novum Organum (1620)",
    "description": "Confirmation bias is the tendency to search for, interpret, favor, and recall information in a way that confirms one's pre-existing beliefs or hypotheses. It matters because it can lead to flawed reasoning, poor decision-making, and resistance to new or contradictory evidence, hindering objective analysis.",
    "example": "A person who believes a certain stock will perform well might selectively read news articles and analyst reports that support this positive outlook, while ignoring or downplaying any negative news or warnings about the company.",
    "tags": [
        "cognitive bias",
        "decision-making",
        "psychology",
        "critical thinking"
    ]
}

💪 Summary

เราจะได้เห็นได้ว่า langchain เป็น package ที่ใช้ทำงานกับ LLM ได้อย่างง่าย ๆ ใน 5 ขั้นตอน:

Set LLM: เลือก model
Set prompt: กำหนด system และ user prompt
Set output: กำหนด output structure
Chain: สร้าง pipeline
Run: เรียกใช้งาน (single & batch)

🫵 Your Turn

สำหรับคนที่สนใจศึกษา langchain เพิ่มเติม:


📄 References

Comments

Leave a comment