# LangChain สำหรับ Data Scientist ปี 2026: LLM, Agent และคำถามสัมภาษณ์ > เชี่ยวชาญ LangChain 0.3 สำหรับ data science: LCEL chain, รูปแบบ RAG, ReAct agent, ระบบ memory และคำถามสัมภาษณ์สำหรับตำแหน่ง ML engineering - Published: 2026-07-22 - Updated: 2026-07-22 - Author: SharpSkill - Reading time: 5 min --- LangChain 0.3 ได้กลายเป็น framework มาตรฐานสำหรับการสร้างแอปพลิเคชัน LLM ใน workflow ของ data science ระดับ production บทความนี้ครอบคลุม core abstraction, สถาปัตยกรรม agent และรูปแบบ retrieval ที่ data scientist พบในทั้งโปรเจกต์จริงและการสัมภาษณ์เทคนิค > **LangChain ในปี 2026** > > LangChain Expression Language (LCEL) ช่วยให้สามารถประกอบ chain แบบ declarative พร้อม streaming, parallelization และ fallback เชี่ยวชาญไวยากรณ์ LCEL ก่อนที่จะศึกษา agent เนื่องจากคำถามสัมภาษณ์ส่วนใหญ่จะสันนิษฐานว่าคุณคุ้นเคยกับ pipe operator และ runnable ## ทำความเข้าใจ Core Components ของ LangChain LangChain จัดระเบียบการ orchestrate LLM เป็นสี่ abstraction หลัก: Model, Prompt, Chain และ Agent แต่ละ abstraction สร้างขึ้นจาก abstraction ก่อนหน้า สร้างระบบที่สามารถประกอบกันได้สำหรับ workflow AI ที่ซับซ้อน เลเยอร์ Model ห่อหุ้ม LLM provider ต่างๆ (OpenAI, Anthropic, model ในเครื่อง) ภายใต้ interface ที่เป็นหนึ่งเดียว abstraction นี้ช่วยให้สลับ provider ได้โดยไม่ต้องเปลี่ยน logic ของแอปพลิเคชัน ซึ่งสำคัญสำหรับการเพิ่มประสิทธิภาพต้นทุนและความยืดหยุ่นของ vendor ```python # langchain_setup.py from langchain_openai import ChatOpenAI from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage, SystemMessage # Initialize with specific model and temperature openai_model = ChatOpenAI( model="gpt-4o", temperature=0.1, # Lower temperature for deterministic outputs max_tokens=2048 ) # Anthropic model with same interface anthropic_model = ChatAnthropic( model="claude-sonnet-4-20250514", temperature=0.1 ) # Both models accept identical message format messages = [ SystemMessage(content="You are a data science expert."), HumanMessage(content="Explain gradient boosting in one sentence.") ] # Swap models without changing message structure response = openai_model.invoke(messages) ``` Interface ที่เป็นหนึ่งเดียวหมายความว่า data pipeline สามารถสลับระหว่าง provider ตามความต้องการด้านต้นทุน, latency หรือความสามารถ ## การสร้าง Chain ด้วยไวยากรณ์ Pipe LCEL LangChain Expression Language แทนที่คลาส `LLMChain` เดิมด้วยไวยากรณ์แบบ pipe ที่ยืดหยุ่นกว่า LCEL chain คือ runnable ที่รองรับ streaming, batching และการทำงานแบบ async โดยค่าเริ่มต้น ```python # lcel_chain.py from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser, JsonOutputParser from pydantic import BaseModel, Field # Define structured output schema class DataInsight(BaseModel): metric: str = Field(description="The metric being analyzed") trend: str = Field(description="Upward, downward, or stable") confidence: float = Field(description="Confidence score 0-1") # Create prompt template with variables prompt = ChatPromptTemplate.from_messages([ ("system", "Analyze the following data and extract insights."), ("human", "Dataset: {dataset_description}\nFocus on: {metric}") ]) # LCEL chain with pipe operator model = ChatOpenAI(model="gpt-4o", temperature=0) parser = JsonOutputParser(pydantic_object=DataInsight) chain = prompt | model | parser # Pipe syntax composes runnables # Invoke with input dictionary result = chain.invoke({ "dataset_description": "Monthly sales data showing 15% increase", "metric": "revenue growth" }) # Returns: DataInsight(metric='revenue growth', trend='upward', confidence=0.85) ``` LCEL chain จัดการการแปลงชนิดข้อมูลระหว่าง component โดยอัตโนมัติ prompt template ส่งออก `PromptValue` ซึ่ง model แปลงเป็นการตอบกลับ จากนั้น parser จัดโครงสร้างเป็น Pydantic schema ## Retrieval-Augmented Generation สำหรับแอปพลิเคชันข้อมูล รูปแบบ [RAG](/blog/data-science/rag-retrieval-augmented-generation-llm-data-science-interview-2026) เพิ่มประสิทธิภาพการตอบกลับของ LLM ด้วยบริบทเฉพาะ domain ที่ดึงมาจาก vector database สำหรับแอปพลิเคชัน data science RAG ช่วยให้สามารถ query เอกสาร, การวิเคราะห์ก่อนหน้า หรือ knowledge base ของ domain ```python # rag_pipeline.py from langchain_openai import OpenAIEmbeddings, ChatOpenAI from langchain_chroma import Chroma from langchain_core.prompts import ChatPromptTemplate from langchain_core.runnables import RunnablePassthrough # Initialize embeddings and vector store embeddings = OpenAIEmbeddings(model="text-embedding-3-small") vectorstore = Chroma( collection_name="data_docs", embedding_function=embeddings, persist_directory="./chroma_db" ) # Create retriever with relevance threshold retriever = vectorstore.as_retriever( search_type="similarity_score_threshold", search_kwargs={"score_threshold": 0.7, "k": 4} ) # RAG prompt with context injection rag_prompt = ChatPromptTemplate.from_messages([ ("system", """Answer based on the provided context only. Context: {context} If the context doesn't contain relevant information, say so."""), ("human", "{question}") ]) # Format documents into context string def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs) # RAG chain with parallel retrieval rag_chain = ( {"context": retriever | format_docs, "question": RunnablePassthrough()} | rag_prompt | ChatOpenAI(model="gpt-4o", temperature=0) ) # Query with automatic retrieval answer = rag_chain.invoke("What normalization method works best for skewed distributions?") ``` `RunnablePassthrough` รักษาคำถามเดิมในขณะที่ retriever ดึงบริบทแบบขนาน รูปแบบนี้สามารถ scale สำหรับ workload ระดับ production ได้โดยมี latency overhead น้อยที่สุด ## การใช้งาน ReAct Agent สำหรับงานข้อมูล Agent ขยาย chain ด้วยความสามารถในการเรียก tool และ reasoning loop รูปแบบ ReAct (Reasoning + Acting) สลับระหว่างขั้นตอนการคิดและการกระทำ ช่วยให้ agent สามารถแก้ปัญหาหลายขั้นตอนได้ ```python # react_agent.py from langchain_openai import ChatOpenAI from langchain_core.tools import tool from langgraph.prebuilt import create_react_agent import pandas as pd import numpy as np # Define data analysis tools @tool def calculate_statistics(data: str, column: str) -> str: """Calculate descriptive statistics for a column in CSV data.""" df = pd.read_csv(pd.io.common.StringIO(data)) stats = df[column].describe() return stats.to_string() @tool def detect_outliers(data: str, column: str, method: str = "iqr") -> str: """Detect outliers using IQR or Z-score method.""" df = pd.read_csv(pd.io.common.StringIO(data)) values = df[column] if method == "iqr": q1, q3 = values.quantile([0.25, 0.75]) iqr = q3 - q1 outliers = values[(values < q1 - 1.5 * iqr) | (values > q3 + 1.5 * iqr)] else: # z-score z_scores = np.abs((values - values.mean()) / values.std()) outliers = values[z_scores > 3] return f"Found {len(outliers)} outliers: {outliers.tolist()[:10]}" @tool def correlation_analysis(data: str, col1: str, col2: str) -> str: """Calculate Pearson correlation between two columns.""" df = pd.read_csv(pd.io.common.StringIO(data)) corr = df[col1].corr(df[col2]) return f"Correlation between {col1} and {col2}: {corr:.4f}" # Create ReAct agent with tools model = ChatOpenAI(model="gpt-4o", temperature=0) tools = [calculate_statistics, detect_outliers, correlation_analysis] agent = create_react_agent( model=model, tools=tools, state_modifier="You are a data analyst. Use tools to analyze data step by step." ) # Agent reasons about which tools to use result = agent.invoke({ "messages": [("human", "Analyze the sales column for outliers and basic stats")] }) ``` Decorator `@tool` ลงทะเบียน function เป็น tool ของ agent พร้อมการสร้าง schema อัตโนมัติจาก type hint และ docstring Agent ตัดสินใจว่าจะเรียก tool ใดตามความต้องการของงาน ## รูปแบบ Memory สำหรับการวิเคราะห์แบบสนทนา เซสชันการวิเคราะห์ข้อมูลที่ทำงานยาวนานต้องการ conversation memory เพื่อรักษาบริบทข้ามการโต้ตอบ LangChain จัดเตรียมหลายกลยุทธ์ memory ที่ปรับให้เหมาะสมสำหรับกรณีการใช้งานต่างๆ ```python # memory_patterns.py from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.chat_history import InMemoryChatMessageHistory from langchain_core.runnables.history import RunnableWithMessageHistory # Initialize model and prompt with history placeholder model = ChatOpenAI(model="gpt-4o", temperature=0.1) prompt = ChatPromptTemplate.from_messages([ ("system", "You are a data science assistant helping with analysis."), MessagesPlaceholder(variable_name="history"), # Inject conversation history ("human", "{input}") ]) chain = prompt | model # Session-based message store message_stores = {} def get_session_history(session_id: str): if session_id not in message_stores: message_stores[session_id] = InMemoryChatMessageHistory() return message_stores[session_id] # Wrap chain with message history chain_with_history = RunnableWithMessageHistory( chain, get_session_history, input_messages_key="input", history_messages_key="history" ) # Conversation maintains context across invocations config = {"configurable": {"session_id": "analysis_session_1"}} response1 = chain_with_history.invoke( {"input": "I'm analyzing customer churn data with 50k rows"}, config=config ) # Later in the same session response2 = chain_with_history.invoke( {"input": "What sampling strategy should I use for this dataset size?"}, config=config ) # Agent remembers the 50k rows context ``` การ deploy ระดับ production มักจะแทนที่ `InMemoryChatMessageHistory` ด้วย storage แบบ Redis หรือ PostgreSQL สำหรับความคงทนข้ามการ restart server ## คำถามและคำตอบสัมภาษณ์ LangChain การสัมภาษณ์เทคนิคสำหรับตำแหน่ง ML engineering และ data science มีคำถามเกี่ยวกับ LangChain มากขึ้น คำถามเหล่านี้มักประเมินความเข้าใจเกี่ยวกับ core abstraction, ข้อควรพิจารณาสำหรับ production และกลยุทธ์การ debug > **หัวข้อสัมภาษณ์ทั่วไป** > > ผู้สัมภาษณ์เน้นที่สามด้าน: รูปแบบการประกอบ chain, เทคนิคการเพิ่มประสิทธิภาพ RAG และกลยุทธ์ความน่าเชื่อถือของ agent เตรียมพร้อมที่จะวาด retrieval pipeline บน whiteboard หรือ debug สถานการณ์ hallucination **ถ: อธิบายความแตกต่างระหว่าง chain และ agent ใน LangChain** Chain ทำงานตามลำดับการดำเนินการที่กำหนดไว้ล่วงหน้า—prompt ไปยัง model ไปยัง parser—โดยไม่มีการตัดสินใจขณะทำงาน Agent เพิ่ม reasoning loop ที่เลือก tool แบบไดนามิกตามผลลัพธ์ระหว่างทาง Chain เหมาะสำหรับ workflow ที่มีโครงสร้างเช่น pipeline การแปลงข้อมูล; agent จัดการงานที่เปิดกว้างซึ่งต้องการการเลือก tool แบบปรับตัวได้ **ถ: จะลด hallucination ในแอปพลิเคชัน RAG ได้อย่างไร?** หลายกลยุทธ์ทำงานร่วมกัน: เพิ่มความแม่นยำของ retrieval ด้วยการค้นหาแบบ hybrid (รวม dense และ sparse retriever), เพิ่มการให้คะแนน relevance เพื่อกรอง chunk ที่มีความเชื่อมั่นต่ำ, รวมการระบุแหล่งที่มาใน prompt, ใช้การตรวจสอบคำตอบกับบริบทที่ดึงมา และใช้การตั้งค่า temperature ต่ำสำหรับ query เชิงข้อเท็จจริง รูปแบบ [feature engineering](/technologies/data-science/interview-questions/feature-engineering) สำหรับคุณภาพ embedding ก็ส่งผลต่อความแม่นยำของ retrieval ด้วย **ถ: Runnable คืออะไรและทำไม LangChain ถึงใช้?** Runnable คือ base abstraction ที่ implement protocol `Runnable` พร้อมเมธอด `invoke`, `stream`, `batch` และ `ainvoke` ทุก component—prompt, model, parser, retriever—เป็น runnable ความสม่ำเสมอนี้ช่วยให้สามารถประกอบด้วย pipe operator โดยที่ output type จะตรงกับความคาดหวังของ input โดยอัตโนมัติ Runnable ยังให้ parallelization ในตัว, retry logic และ streaming โดยไม่ต้องเขียนโค้ดเพิ่มเติม **ถ: จะ implement streaming response สำหรับ chat interface ได้อย่างไร?** ```python # streaming_example.py from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate.from_template("Explain {concept} in detail") model = ChatOpenAI(model="gpt-4o", streaming=True) chain = prompt | model # Stream yields chunks as they arrive for chunk in chain.stream({"concept": "backpropagation"}): print(chunk.content, end="", flush=True) ``` เมธอด `stream` ให้ผลลัพธ์เป็น object `AIMessageChunk` ที่มี response บางส่วน สำหรับเว็บแอปพลิเคชัน chunk เหล่านี้มักจะถูกส่งเข้าสู่การเชื่อมต่อ Server-Sent Events หรือ WebSocket **ถ: อธิบายกลยุทธ์สำหรับการทดสอบแอปพลิเคชัน LangChain** การทดสอบแอปพลิเคชัน LLM ต้องการหลายแนวทาง: unit test ด้วย mock model response สำหรับพฤติกรรม chain ที่แน่นอน, integration test กับ model จริงสำหรับประสิทธิภาพของ prompt, ชุดข้อมูลประเมินพร้อม output ที่คาดหวังสำหรับการตรวจจับ regression และเครื่องมือ tracing เช่น [LangSmith](https://smith.langchain.com/) สำหรับการ debug production Mock layer ของ model ระหว่าง CI เพื่อหลีกเลี่ยงค่าใช้จ่าย API และความไม่เสถียร ## ข้อควรพิจารณาในการ Deploy Production การ deploy แอปพลิเคชัน LangChain ต้องใส่ใจกับ latency, ต้นทุน และความน่าเชื่อถือ นอกเหนือจากสิ่งที่ environment การพัฒนาแสดง > **การจัดการต้นทุน Token** > > แอปพลิเคชัน RAG ระดับ production สามารถสร้างค่าใช้จ่าย token จำนวนมาก ใช้ middleware นับ token, ตั้งค่าการแจ้งเตือนงบประมาณ และพิจารณากลยุทธ์ caching สำหรับ query ที่ซ้ำกัน agent loop เดียวที่มีการเรียก tool หลายครั้งสามารถใช้ token หลายพันต่อ request Caching ลดทั้ง latency และต้นทุนสำหรับ query ที่ซ้ำกัน เลเยอร์ caching ของ LangChain เก็บ model response โดยใช้ key จาก hash ของ prompt: ```python # caching_setup.py from langchain_core.globals import set_llm_cache from langchain_community.cache import RedisCache import redis # Redis cache for distributed deployments redis_client = redis.Redis(host="localhost", port=6379) set_llm_cache(RedisCache(redis_client)) # Subsequent identical queries hit cache model = ChatOpenAI(model="gpt-4o") response1 = model.invoke("What is gradient descent?") # API call response2 = model.invoke("What is gradient descent?") # Cache hit ``` สำหรับ [pipeline MLOps](/blog/data-science/mlops-mlflow-model-registry-interview-questions-2026) ให้รวม LangChain กับ experiment tracking เพื่อติดตามเวอร์ชัน prompt, การตั้งค่า model และ metric คุณภาพ response ตลอดเวลา ## สรุป - LangChain 0.3 จัดระเบียบการ orchestrate LLM เป็น Model, Prompt, Chain และ Agent—แต่ละ abstraction สามารถประกอบกันได้ผ่านไวยากรณ์ pipe LCEL - การ implement RAG ต้องการ retrieval threshold ที่ปรับแล้ว, การให้คะแนน relevance และการจัดรูปแบบบริบทสำหรับความแม่นยำระดับ production - ReAct agent จัดการงานข้อมูลหลายขั้นตอนโดยการใช้เหตุผลเกี่ยวกับการเลือก tool ขณะทำงาน - รูปแบบ memory รักษาบริบทการสนทนาข้ามเซสชันการวิเคราะห์โดยใช้ message store ตาม session - การเตรียมตัวสัมภาษณ์ควรครอบคลุมความแตกต่างระหว่าง chain กับ agent, กลยุทธ์ลด hallucination และรูปแบบการประกอบ runnable - การ deploy production ต้องการ caching, การจัดงบประมาณ token และเครื่องมือ observability สำหรับการจัดการต้นทุนและความน่าเชื่อถือ --- Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack. HTML version of this page: https://sharpskill.dev/th/blog/data-science/langchain-data-scientists-llms-agents-interview-2026