LangChain cho Data Scientist 2026: LLM, Agent và Câu hỏi Phỏng vấn
Làm chủ LangChain 0.3 cho data science: LCEL chain, mẫu RAG, ReAct agent, hệ thống bộ nhớ, và câu hỏi phỏng vấn cho vị trí ML engineering.

LangChain 0.3 đã trở thành framework tiêu chuẩn để xây dựng ứng dụng LLM trong quy trình data science production. Hướng dẫn này trình bày các abstraction cốt lõi, kiến trúc agent, và các mẫu retrieval mà data scientist thường gặp trong cả dự án thực tế lẫn phỏng vấn kỹ thuật.
LangChain Expression Language (LCEL) cho phép tổ hợp chain theo kiểu khai báo với streaming, song song hóa, và fallback. Nắm vững cú pháp LCEL trước khi đi sâu vào agent—hầu hết câu hỏi phỏng vấn đều giả định sự quen thuộc với toán tử pipe và runnable.
Hiểu các Thành phần Cốt lõi của LangChain
LangChain tổ chức orchestration LLM thành bốn abstraction chính: Model, Prompt, Chain, và Agent. Mỗi abstraction được xây dựng trên abstraction trước đó, tạo ra một hệ thống có thể tổ hợp cho các workflow AI phức tạp.
Lớp Model bọc các nhà cung cấp LLM khác nhau (OpenAI, Anthropic, model cục bộ) sau một interface thống nhất. Abstraction này cho phép hoán đổi nhà cung cấp mà không thay đổi logic ứng dụng—quan trọng cho tối ưu chi phí và linh hoạt vendor.
# 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 thống nhất có nghĩa là pipeline dữ liệu có thể chuyển đổi giữa các nhà cung cấp dựa trên yêu cầu về chi phí, độ trễ, hoặc khả năng.
Xây dựng Chain với Cú pháp Pipe LCEL
LangChain Expression Language thay thế class LLMChain cũ bằng cú pháp dựa trên pipe linh hoạt hơn. LCEL chain là các runnable hỗ trợ streaming, batching, và thực thi async theo mặc định.
# 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 tự động xử lý chuyển đổi kiểu giữa các thành phần. Template prompt xuất ra PromptValue, được model chuyển đổi thành phản hồi, sau đó parser cấu trúc nó thành schema Pydantic.
Retrieval-Augmented Generation cho Ứng dụng Dữ liệu
Các mẫu RAG tăng cường phản hồi LLM với ngữ cảnh đặc thù domain được truy xuất từ vector database. Đối với ứng dụng data science, RAG cho phép truy vấn tài liệu, các phân tích trước đó, hoặc knowledge base domain.
# 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 giữ nguyên câu hỏi gốc trong khi retriever lấy ngữ cảnh song song. Mẫu này có thể mở rộng cho workload production với overhead độ trễ tối thiểu.
Sẵn sàng chinh phục phỏng vấn Data Science & ML?
Luyện tập với mô phỏng tương tác, flashcards và bài kiểm tra kỹ thuật.
Triển khai ReAct Agent cho Tác vụ Dữ liệu
Agent mở rộng chain với khả năng gọi tool và vòng lặp suy luận. Mẫu ReAct (Reasoning + Acting) xen kẽ các bước suy nghĩ và hành động, cho phép agent giải quyết các vấn đề nhiều bước.
# 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 đăng ký function như tool của agent với việc tạo schema tự động từ type hint và docstring. Agent quyết định khi nào gọi mỗi tool dựa trên yêu cầu tác vụ.
Các Mẫu Bộ nhớ cho Phân tích Hội thoại
Các phiên phân tích dữ liệu kéo dài yêu cầu bộ nhớ hội thoại để duy trì ngữ cảnh qua các tương tác. LangChain cung cấp nhiều chiến lược bộ nhớ được tối ưu cho các trường hợp sử dụng khác nhau.
# 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 contextTriển khai production thường thay thế InMemoryChatMessageHistory bằng lưu trữ dựa trên Redis hoặc PostgreSQL để duy trì qua các lần khởi động lại server.
Câu hỏi và Câu trả lời Phỏng vấn LangChain
Phỏng vấn kỹ thuật cho các vị trí ML engineering và data science ngày càng bao gồm câu hỏi LangChain. Những câu hỏi này thường đánh giá sự hiểu biết về các abstraction cốt lõi, các cân nhắc production, và chiến lược debugging.
Người phỏng vấn tập trung vào ba lĩnh vực: mẫu tổ hợp chain, kỹ thuật tối ưu RAG, và chiến lược độ tin cậy agent. Hãy chuẩn bị vẽ pipeline retrieval trên bảng trắng hoặc debug kịch bản hallucination.
H: Giải thích sự khác biệt giữa chain và agent trong LangChain.
Chain thực thi một chuỗi thao tác được định trước—prompt đến model đến parser—không có quyết định runtime. Agent thêm vòng lặp suy luận chọn tool động dựa trên kết quả trung gian. Chain phù hợp cho workflow có cấu trúc như pipeline biến đổi dữ liệu; agent xử lý các tác vụ mở yêu cầu lựa chọn tool thích ứng.
H: Làm thế nào để giảm hallucination trong ứng dụng RAG?
Nhiều chiến lược kết hợp với nhau: tăng độ chính xác retrieval với tìm kiếm hybrid (kết hợp retriever dense và sparse), thêm chấm điểm relevance để lọc chunk có độ tin cậy thấp, bao gồm ghi nguồn trong prompt, triển khai xác minh câu trả lời so với ngữ cảnh đã truy xuất, và sử dụng cài đặt temperature thấp cho truy vấn thực tế. Các mẫu feature engineering cho chất lượng embedding cũng ảnh hưởng đến độ chính xác retrieval.
H: Runnable là gì và tại sao LangChain sử dụng chúng?
Runnable là abstraction cơ sở triển khai giao thức Runnable với các method invoke, stream, batch, và ainvoke. Mọi thành phần—prompt, model, parser, retriever—đều là runnable. Sự đồng nhất này cho phép tổ hợp với toán tử pipe, nơi kiểu output tự động khớp với kỳ vọng input. Runnable cũng cung cấp song song hóa tích hợp, logic retry, và streaming mà không cần code bổ sung.
H: Làm thế nào để triển khai streaming response cho giao diện chat?
# 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)Method stream yield các đối tượng AIMessageChunk chứa phản hồi từng phần. Đối với ứng dụng web, các chunk này thường được đưa vào kết nối Server-Sent Events hoặc WebSocket.
H: Mô tả các chiến lược kiểm thử ứng dụng LangChain.
Kiểm thử ứng dụng LLM yêu cầu nhiều phương pháp: unit test với response model được mock cho hành vi chain xác định, integration test với model thực cho hiệu quả prompt, dataset đánh giá với output kỳ vọng để phát hiện regression, và công cụ tracing như LangSmith cho debugging production. Mock lớp model trong CI để tránh chi phí API và sự không ổn định.
Cân nhắc Triển khai Production
Triển khai ứng dụng LangChain yêu cầu chú ý đến độ trễ, chi phí, và độ tin cậy vượt ra ngoài những gì môi trường development cho thấy.
Ứng dụng RAG production có thể phát sinh chi phí token đáng kể. Triển khai middleware đếm token, thiết lập cảnh báo ngân sách, và cân nhắc chiến lược caching cho truy vấn lặp lại. Một vòng lặp agent với nhiều lần gọi tool có thể tiêu thụ hàng nghìn token mỗi request.
Caching giảm cả độ trễ và chi phí cho truy vấn lặp lại. Lớp caching của LangChain lưu trữ response model được đánh khóa theo hash prompt:
# 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Đối với pipeline MLOps, tích hợp LangChain với experiment tracking để giám sát phiên bản prompt, cấu hình model, và các chỉ số chất lượng response theo thời gian.
Bắt đầu luyện tập!
Kiểm tra kiến thức với mô phỏng phỏng vấn và bài kiểm tra kỹ thuật.
Kết luận
- LangChain 0.3 tổ chức orchestration LLM thành Model, Prompt, Chain, và Agent—mỗi abstraction có thể tổ hợp thông qua cú pháp pipe LCEL
- Triển khai RAG yêu cầu ngưỡng retrieval được điều chỉnh, chấm điểm relevance, và định dạng ngữ cảnh cho độ chính xác production
- ReAct agent xử lý các tác vụ dữ liệu nhiều bước bằng cách suy luận về lựa chọn tool tại runtime
- Các mẫu bộ nhớ duy trì ngữ cảnh hội thoại qua các phiên phân tích sử dụng lưu trữ message theo session
- Chuẩn bị phỏng vấn nên bao gồm sự khác biệt chain vs agent, chiến lược giảm hallucination, và mẫu tổ hợp runnable
- Triển khai production cần caching, ngân sách token, và công cụ observability để quản lý chi phí và độ tin cậy
Chia sẻ
Bài viết liên quan

MLOps năm 2026: MLflow, Model Registry và Câu Hỏi Phỏng Vấn Kỹ Thuật
Các câu hỏi phỏng vấn MLOps bao quát vòng đời ML, theo dõi thí nghiệm với MLflow, thăng cấp model registry, các mẫu triển khai, giám sát drift và thiết kế hệ thống cho năm 2026, kèm mã Python và câu trả lời.

RAG và LLM năm 2026: Retrieval-Augmented Generation cho phỏng vấn Data Science
Retrieval-Augmented Generation (RAG) giải thích cho phỏng vấn data science năm 2026. Bao gồm cơ sở dữ liệu vector, chiến lược chunking, mô hình embedding, agentic RAG, Graph RAG và kiến trúc pipeline sẵn sàng cho sản xuất.

Hugging Face Transformers 2026: NLP, Fine-Tuning va Cau Hoi Phong Van
Huong dan chi tiet Hugging Face Transformers v5 nam 2026: kien truc, fine-tuning voi LoRA, tokenization, quantization va cau hoi phong van data science NLP.