MinAI - Về trang chủ
Lý thuyết
5/1340 phút
Đang tải...

LangChain Deep Dive cho Text

Khai thac suc manh LangChain cho text processing - chains, memory, callbacks

0

🎯 Mục tiêu bài học

TB5 min

Đi sâu hơn vào LangChain framework - hiểu các components, patterns và best practices cho text processing.

Sau bài này, bạn sẽ:

✅ Hiểu LangChain architecture và chọn model phù hợp ✅ Sử dụng advanced prompt patterns (Few-Shot, Dynamic) ✅ Implement memory systems cho conversational text processing ✅ Sử dụng callbacks, fallbacks và caching để tối ưu pipeline

1

🔍 LangChain Architecture

TB5 min
Diagram
Đang vẽ diagram...

Checkpoint

Bạn đã hiểu kiến trúc tổng thể của LangChain và các components chưa?

2

📐 Model Selection Strategy

TB5 min
python.py
1from langchain_openai import ChatOpenAI
2from langchain_anthropic import ChatAnthropic
3
4# Fast and cheap - high volume tasks
5fast_llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
6
7# Powerful - complex reasoning
8power_llm = ChatOpenAI(model="gpt-4o", temperature=0.3)
9
10# Long context - large documents
11long_llm = ChatAnthropic(
12 model="claude-3-5-sonnet-20241022",
13 max_tokens=4096
14)
Chọn model phù hợp
  • gpt-4o-mini: Fast, cheap - dùng cho batch processing, simple tasks
  • gpt-4o: Balanced - dùng cho content generation, analysis
  • Claude 3.5 Sonnet: Long context - dùng cho document processing

Checkpoint

Bạn đã biết cách chọn model phù hợp cho từng loại task chưa?

3

📐 Advanced Prompt Patterns

TB5 min

Few-Shot Prompting

python.py
1from langchain_core.prompts import FewShotChatMessagePromptTemplate
2
3examples = [
4 {"input": "Toi rat thich san pham nay!", "output": "Positive"},
5 {"input": "San pham kem chat luong", "output": "Negative"},
6 {"input": "San pham binh thuong", "output": "Neutral"},
7]
8
9example_prompt = ChatPromptTemplate.from_messages([
10 ("human", "{input}"),
11 ("ai", "{output}")
12])
13
14few_shot = FewShotChatMessagePromptTemplate(
15 example_prompt=example_prompt,
16 examples=examples
17)
18
19final_prompt = ChatPromptTemplate.from_messages([
20 ("system", "Ban la sentiment analyzer. Phan loai sentiment cua text."),
21 few_shot,
22 ("human", "{text}")
23])
24
25chain = final_prompt | fast_llm
26result = chain.invoke({"text": "Dich vu tuyet voi, se quay lai!"})

Dynamic Prompts

python.py
1from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
2
3dynamic_prompt = ChatPromptTemplate.from_messages([
4 ("system", "Ban la {role} chuyen ve {domain}."),
5 MessagesPlaceholder("history", optional=True),
6 ("human", "{input}")
7])
8
9# Use with different configs
10result = dynamic_prompt.invoke({
11 "role": "content writer",
12 "domain": "technology",
13 "input": "Viet intro cho blog ve AI",
14 "history": []
15})

Checkpoint

Bạn đã hiểu cách sử dụng Few-Shot và Dynamic Prompts chưa?

4

📐 Memory Systems

TB5 min

Conversation Buffer

python.py
1from langchain_core.chat_history import InMemoryChatMessageHistory
2from langchain_core.runnables.history import RunnableWithMessageHistory
3
4store = {}
5
6def get_session_history(session_id: str):
7 if session_id not in store:
8 store[session_id] = InMemoryChatMessageHistory()
9 return store[session_id]
10
11prompt = ChatPromptTemplate.from_messages([
12 ("system", "Ban la writing assistant. Nho context hoi thoai."),
13 MessagesPlaceholder("history"),
14 ("human", "{input}")
15])
16
17chain = prompt | fast_llm
18
19with_memory = RunnableWithMessageHistory(
20 chain,
21 get_session_history,
22 input_messages_key="input",
23 history_messages_key="history"
24)
25
26# Session 1
27config = {"configurable": {"session_id": "user-1"}}
28r1 = with_memory.invoke({"input": "Toi muon viet blog ve Python"}, config=config)
29r2 = with_memory.invoke({"input": "Goi y 5 tieu de"}, config=config)
30# r2 nho context la Python blog

Checkpoint

Bạn đã hiểu cách implement memory cho conversational text processing chưa?

5

🛠️ Callbacks và Logging

TB5 min
python.py
1from langchain_core.callbacks import BaseCallbackHandler
2
3class TokenCounter(BaseCallbackHandler):
4 def __init__(self):
5 self.total_tokens = 0
6
7 def on_llm_end(self, response, **kwargs):
8 if response.llm_output:
9 usage = response.llm_output.get("token_usage", {})
10 self.total_tokens += usage.get("total_tokens", 0)
11 print(f"Tokens used: {usage.get('total_tokens', 0)}")
12
13counter = TokenCounter()
14
15llm_with_callbacks = ChatOpenAI(
16 model="gpt-4o-mini",
17 callbacks=[counter]
18)
19
20# Run chain
21result = (prompt | llm_with_callbacks).invoke({"input": "Hello"})
22print(f"Total tokens: {counter.total_tokens}")

Checkpoint

Bạn đã hiểu cách sử dụng callbacks để tracking tokens chưa?

6

🛠️ Fallback Chains

TB5 min
python.py
1from langchain_core.runnables import RunnableWithFallbacks
2
3primary = ChatOpenAI(model="gpt-4o")
4fallback = ChatOpenAI(model="gpt-4o-mini")
5backup = ChatAnthropic(model="claude-3-5-sonnet-20241022")
6
7# Auto-fallback khi primary fail
8robust_llm = primary.with_fallbacks([fallback, backup])
9
10chain = prompt | robust_llm | StrOutputParser()
11# Neu gpt-4o fail -> try gpt-4o-mini -> try claude

Checkpoint

Bạn đã hiểu cách setup fallback chains để tăng reliability chưa?

7

⚡ Caching

TB5 min
python.py
1from langchain_core.globals import set_llm_cache
2from langchain_community.cache import InMemoryCache
3
4# Enable caching
5set_llm_cache(InMemoryCache())
6
7# First call - hits API
8result1 = llm.invoke("Giai thich AI")
9# Second call with same input - returns cached result
10result2 = llm.invoke("Giai thich AI") # Instant!

Checkpoint

Bạn đã hiểu cách sử dụng caching để tối ưu hiệu suất và chi phí chưa?

8

🎯 Tổng kết

TB5 min
Hands-on Exercise
  1. Build text processing pipeline với few-shot prompting
  2. Implement conversation memory cho writing assistant
  3. Add token counting và cost tracking
  4. Setup fallback chain với multiple providers

Câu hỏi tự kiểm tra

  1. Memory trong LangChain giúp giải quyết vấn đề gì khi xây dựng ứng dụng text processing?
  2. Fallback chains hoạt động như thế nào khi primary model gặp lỗi?
  3. Caching trong LangChain giúp tối ưu hiệu suất và chi phí như thế nào?
  4. Callbacks và token counting được sử dụng để theo dõi những thông tin gì trong quá trình xử lý?

🎉 Tuyệt vời! Bạn đã hoàn thành bài học LangChain Deep Dive cho Text Processing!

Tiếp theo: Hãy khám phá các LCEL Patterns nâng cao để xây dựng pipeline mạnh mẽ hơn!


🚀 Bài tiếp theo

LCEL Patterns nâng cao →