Qwen 2.5 dẫn đầu về coding (vượt GPT-4o trên HumanEval), có vocabulary 151K tokens tối ưu cho tiếng Việt/Trung, và là nền tảng lý tưởng để xây dựng AI Agent. Bài viết này bao gồm benchmark coding, khả năng đa ngôn ngữ, deploy Ollama/vLLM, và các pattern ReAct agent, multi-agent pipeline, structured output.
Qwen 2.5: Chinh Phục Code, Đa Ngôn Ngữ và Xây Dựng AI Agent Workflow
Alibaba's Qwen 2.5 là model open-source dẫn đầu về coding và đa ngôn ngữ, đồng thời là nền tảng lý tưởng để xây dựng AI Agent workflow phức tạp. Với dải model từ 0.5B đến 72B và các variant chuyên biệt (Coder, Math), Qwen 2.5 phủ sóng từ edge device đến server enterprise. Bài viết này đi sâu vào benchmark coding, khả năng tiếng Việt, và các pattern xây dựng AI Agent production-grade.
1. Dải Model Qwen 2.5: Kiến Trúc Tổng Quan
Qwen 2.5 ra mắt với nhiều variant chuyên biệt phục vụ từng use case:
Model
Tham số
Đặc điểm
VRAM (Q4)
Qwen2.5-0.5B
0.5B
Edge, mobile
~0.5GB
Qwen2.5-1.5B
1.5B
Edge, speculative draft
~1.5GB
Qwen2.5-3B
3B
Light tasks
~2GB
Qwen2.5-7B
7B
General purpose
~5GB
Qwen2.5-14B
14B
Strong reasoning
~9GB
Qwen2.5-32B
32B
Near-SOTA, balance
~20GB
Qwen2.5-72B
72B
Top-tier open source
~45GB
Qwen2.5-Coder-32B
32B
Code specialist
~20GB
Qwen2.5-Math-72B
72B
Math specialist
~45GB
Điểm Kiến Trúc Nổi Bật
GQA (Grouped Query Attention): Tối ưu KV cache, cho phép batch lớn và context dài
Context window: 128K tokens (cần config trong Ollama để dùng đầy đủ)
Vocab:151,936 tokens — lớn nhất trong các model mainstream, tối ưu cho tiếng Trung, tiếng Việt
YaRN RoPE scaling: Long context extrapolation hiệu quả
SwiGLU activation: Standard trong LLM hiện đại
2. Coding Benchmark: Qwen2.5-Coder Dẫn Đầu Thế Giới
3. Khả Năng Đa Ngôn Ngữ: Tiếng Việt và Tiếng Trung
Benchmark Multilingual
Benchmark
Qwen2.5-72B
Llama 3.3 70B
Mistral Large
C-Eval (Tiếng Trung)
91.1%
75.2%
78.4%
CMMLU
90.7%
73.1%
74.9%
Vietnamese VLSP
78.3%
68.1%
65.2%
M-MMLU (avg 14 langs)
82.5%
74.3%
73.8%
Tại Sao Qwen Tốt Nhất Cho Tiếng Việt?
Vocabulary 151K tokens: Tokenize tiếng Việt hiệu quả, ít split từ → ít token → rẻ hơn, nhanh hơn
Training data đa dạng: Bao gồm văn bản tiếng Việt từ Wikipedia, tin tức, forums
Instruction tuning đa ngôn ngữ: Fine-tune với prompt và response tiếng Việt chất lượng cao
Tự nhiên switch ngôn ngữ: Trả lời bằng ngôn ngữ người dùng dùng, không cần system prompt đặc biệt
Demo: Tiếng Việt với Qwen
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
# Qwen tự động trả lời tiếng Việt khi được hỏi tiếng Việt
response = client.chat.completions.create(
model="qwen2.5:72b",
messages=[{
"role": "user",
"content": "Giải thích thuật toán Dijkstra bằng tiếng Việt và viết code Python minh họa."
}],
temperature=0.3
)
print(response.choices[0].message.content)
4. Deploy Qwen 2.5 với Ollama
# Model phổ thông
ollama pull qwen2.5:7b # ~5GB — RTX 3060 12GB
ollama pull qwen2.5:14b # ~9GB — RTX 4080/3090
ollama pull qwen2.5:32b # ~20GB — 2× RTX 3090 hoặc A100 40GB
ollama pull qwen2.5:72b # ~45GB — 2× A100 40GB# Code specialist
ollama pull qwen2.5-coder:32b
# Tăng context (Ollama mặc định 2K, cần config)cat > Qwen-Modelfile << 'EOF'
FROM qwen2.5:72b
PARAMETER num_ctx 32768
PARAMETER temperature 0.7
PARAMETER top_p 0.9
SYSTEM "You are a helpful AI assistant. Respond in the same language as the user."
EOF
ollama create qwen25-72b-32k -f Qwen-Modelfile
Qwen 2.5 đặc biệt mạnh trong agentic tasks — tuân theo instruction phức tạp, gọi tools, và duy trì context dài qua nhiều bước.
ReAct Agent
import json
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="qwen")
tools = [
{
"type": "function",
"function": {
"name": "search_web",
"description": "Tìm kiếm thông tin trên web",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}
},
{
"type": "function",
"function": {
"name": "execute_python",
"description": "Thực thi code Python và trả về kết quả",
"parameters": {
"type": "object",
"properties": {
"code": {"type": "string"}
},
"required": ["code"]
}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Đọc nội dung file",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"}
},
"required": ["path"]
}
}
}
]
defrun_agent(user_task: str, max_steps: int = 10) -> str:
messages = [
{
"role": "system",
"content": "Bạn là AI agent có khả năng sử dụng tools. Hoàn thành nhiệm vụ bằng cách gọi tools phù hợp theo từng bước."
},
{"role": "user", "content": user_task}
]
for step inrange(max_steps):
response = client.chat.completions.create(
model="qwen2.5-72b-instruct",
messages=messages,
tools=tools,
tool_choice="auto",
temperature=0.1# Thấp để agent ổn định
)
msg = response.choices[0].message
messages.append(msg)
# Agent hoàn thành khi không gọi toolifnot msg.tool_calls:
return msg.content
# Thực thi tool callsfor tool_call in msg.tool_calls:
result = execute_tool(
tool_call.function.name,
json.loads(tool_call.function.arguments)
)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": str(result)
})
return"Max steps reached"defexecute_tool(name: str, args: dict) -> str:
if name == "search_web":
# Tích hợp với Tavily, SerpAPI, v.v.returnf"[Search results for: {args['query']}]"elif name == "execute_python":
import subprocess
result = subprocess.run(
["python3", "-c", args["code"]],
capture_output=True, text=True, timeout=30
)
return result.stdout or result.stderr
elif name == "read_file":
withopen(args["path"]) as f:
return f.read()
return"Tool not found"# Ví dụ sử dụng
result = run_agent(
"Phân tích file sales_data.csv và tạo báo cáo với các chỉ số doanh thu theo tháng."
)
print(result)
7. Multi-Agent Pipeline
from openai import OpenAI
classQwenAgent:
def__init__(self, name: str, system_prompt: str, model: str = "qwen2.5:72b"):
self.name = name
self.system_prompt = system_prompt
self.client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
self.model = model
defrun(self, task: str, context: str = "") -> str:
messages = [
{"role": "system", "content": self.system_prompt},
{"role": "user", "content": f"Context:\n{context}\n\nTask: {task}"}
]
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.3
)
return response.choices[0].message.content
# Định nghĩa agents chuyên biệt
researcher = QwenAgent(
"Researcher",
"Bạn là chuyên gia nghiên cứu. Thu thập và tóm tắt thông tin về chủ đề được yêu cầu."
)
coder = QwenAgent(
"Coder",
"Bạn là senior software engineer. Viết code Python sạch, có test, và có documentation.",
model="qwen2.5-coder:32b"
)
reviewer = QwenAgent(
"Reviewer",
"Bạn là technical reviewer. Đánh giá code về performance, security, và best practices."
)
defrun_pipeline(task: str) -> dict:
# Step 1: Research
research = researcher.run(f"Nghiên cứu và tóm tắt về: {task}")
# Step 2: Code generation
code = coder.run(
f"Implement solution for: {task}",
context=research
)
# Step 3: Code review
review = reviewer.run(
"Review đoạn code này và đề xuất cải tiến",
context=code
)
return {"research": research, "code": code, "review": review}
result = run_pipeline("Xây dựng REST API endpoint phân tích sentiment tiếng Việt")
8. Structured Output với Pydantic
from pydantic import BaseModel
from typing importListimport json
classTaskBreakdown(BaseModel):
objective: str
subtasks: List[str]
estimated_complexity: str# "low", "medium", "high"
dependencies: List[str]
suggested_tech_stack: List[str]
defanalyze_task(description: str) -> TaskBreakdown:
response = client.chat.completions.create(
model="qwen2.5:72b",
messages=[
{
"role": "system",
"content": "Bạn là technical architect. Phân tích task và trả về JSON."
},
{
"role": "user",
"content": f"""Phân tích task này theo schema TaskBreakdown:
Task: {description}
Schema:
{{
"objective": "string",
"subtasks": ["string"],
"estimated_complexity": "low|medium|high",
"dependencies": ["string"],
"suggested_tech_stack": ["string"]
}}
Chỉ trả về JSON thuần, không có text khác."""
}
],
temperature=0.1,
response_format={"type": "json_object"}
)
data = json.loads(response.choices[0].message.content)
return TaskBreakdown(**data)
result = analyze_task("Xây dựng hệ thống RAG chatbot customer service")
print(f"Độ phức tạp: {result.estimated_complexity}")
print(f"Subtasks: {', '.join(result.subtasks)}")
9. Code Assistant Production-Grade
classQwenCodeAssistant:
def__init__(self):
self.client = OpenAI(
base_url="http://localhost:8001/v1", # Coder model port
api_key="qwen"
)
defgenerate_code(self, spec: str, language: str = "python") -> str:
response = self.client.chat.completions.create(
model="qwen2.5-coder-32b-instruct",
messages=[
{
"role": "system",
"content": f"Bạn là expert {language} developer. Viết code sạch, có docstring, và unit tests."
},
{"role": "user", "content": spec}
],
temperature=0.1,
max_tokens=4096
)
return response.choices[0].message.content
defreview_code(self, code: str) -> str:
response = self.client.chat.completions.create(
model="qwen2.5-coder-32b-instruct",
messages=[
{
"role": "system",
"content": "Review code và chỉ ra: bugs, security issues, performance bottlenecks, code style."
},
{"role": "user", "content": f"```\n{code}\n```"}
],
temperature=0.2
)
return response.choices[0].message.content
defexplain_code(self, code: str, audience: str = "junior developer") -> str:
response = self.client.chat.completions.create(
model="qwen2.5-coder-32b-instruct",
messages=[{
"role": "user",
"content": f"Giải thích đoạn code này cho {audience}:\n```\n{code}\n```"
}],
temperature=0.5
)
return response.choices[0].message.content
assistant = QwenCodeAssistant()
code = assistant.generate_code(
"Viết FastAPI endpoint upload và phân tích CSV, trả về thống kê cơ bản"
)
print(code)
10. So Sánh Qwen 2.5 vs Các Model Khác
Tiêu chí
Qwen 2.5-72B
Llama 3.3 70B
DeepSeek V3
GPT-4o
Coding (HumanEval)
88.2%
88.4%
91.6%
90.2%
Coding chuyên biệt (Coder-32B)
92.7%
N/A
N/A
N/A
Tiếng Việt
Tốt nhất OS
Tốt
Tốt
Tốt (API)
Tiếng Trung
Tốt nhất
Kém
Tốt
Tốt
Agentic tasks
✅ Xuất sắc
✅ Tốt
✅ Tốt
✅ Tốt nhất
Context window
128K
128K
64K
128K
Self-host cost
Trung bình
Trung bình
Cao (671B)
N/A
11. Lựa Chọn Model Theo Use Case
Use Case
Model Khuyên Dùng
Lý Do
Code generation & review
Qwen2.5-Coder-32B
SOTA coding, vượt GPT-4o
Tiếng Việt/Trung đa dạng
Qwen2.5-72B
Vocab 151K, training data tốt
AI Agent phức tạp
Qwen2.5-72B
Tool calling mạnh, context dài
Edge/mobile
Qwen2.5-1.5B hoặc 3B
Nhỏ gọn, chạy offline
Math reasoning
Qwen2.5-Math-72B
Chuyên biệt toán học
General API server
Qwen2.5-32B
Balance tốt performance/cost
Speculative draft
Qwen2.5-1.5B
Tốc độ cao khi kết hợp 72B
Tổng Kết
Qwen 2.5 nổi bật nhờ ba điểm mạnh cốt lõi:
Coding SOTA: Qwen2.5-Coder-32B là model open-source tốt nhất cho coding, vượt cả GPT-4o trên HumanEval (92.7%) và LiveCodeBench
Đa ngôn ngữ hàng đầu: Vocabulary 151K tokens và training data phong phú làm cho Qwen là lựa chọn số một cho tiếng Việt và tiếng Trung trong nhóm self-hosted
AI Agent mạnh mẽ: Tool calling chính xác, instruction following ổn định, hỗ trợ structured JSON output — tất cả cần thiết cho agent workflow production
Cho doanh nghiệp muốn self-host model đa ngôn ngữ tốt nhất hoặc xây dựng code assistant và AI agent production-grade, Qwen 2.5 là lựa chọn khó có đối thủ trong thế giới open-source.