Autonomous Coding Agent — AI tự viết code từ spec
Điểm nổi bật
Nhấn để đến mục tương ứng
- 1 Muốn làm chủ kiến trúc tổng quan, hãy bắt đầu từ việc hiểu Coding agent hoạt động theo 4 giai đoạn: spec.md | v 1. Parse Spec --> Hiểu requirements | v 2. Plan --> Tao file structure, viet pseudocode | v 3. Implement --> Viet tung file, refine code | v 4 — kỹ thuật này được nhiều developer áp dụng thành công trong dự án thực tế.
- 2 Điểm cần cân nhắc khi sử dụng file tools — cấp quyền truy cập filesystem: Trước tiên, định nghĩa các tools để agent tương tác với filesystem: client anthropic.Anthropic # Tool 1: Doc file str -> str: try: with openpath, 'r', encoding'utf-8' as f: return f — không phải mọi trường hợp đều phù hợp, cần đánh giá bối cảnh cụ thể trước khi áp dụng.
- 3 Theo phân tích system prompt — định hình hành vi agent, System prompt quyết định cách agent tiếp cận vấn đề: CODING_AGENT_SYSTEM """Ban la mot senior software engineer tu dong. Nhiem vu cua ban: doc spec, viet code, chay test, va sua loi den khi tat ca test pass — con số thực tế này đáng để tham khảo khi lập kế hoạch triển khai cho dự án của bạn.
- 4 Để áp dụng ví dụ spec — calculator module hiệu quả, bạn cần nắm rõ: Tạo file spec.md : # Calculator Module Spec ## Yeu cau Xay dung module 'calculator — đây là bước quan trọng giúp tối ưu quy trình làm việc với AI trong thực tế.
- 5 Góc nhìn thực tế về nâng cao: self-healing loop: Khi test fail, agent tự phân tích và fix: # Gia su pytest output cho thay loi: # FAILED test_calculator.py::test_divide_by_zero # AssertionError: ZeroDivisionError not raised # Agent tu dong: # 1. Doc lai calculator.py # 2 — hiệu quả phụ thuộc nhiều vào cách triển khai và ngữ cảnh sử dụng cụ thể.
Hãy tưởng tượng: bạn viết một file spec.md mô tả tính năng cần xây dựng, chạy một lệnh, và AI tự động tạo ra toàn bộ code, test, rồi báo cáo kết quả. Đây không phải tương lai — bài viết này sẽ hướng dẫn bạn xây dựng đúng hệ thống đó.
Autonomous Coding Agent sử dụng Claude sonnet làm coding engine, cung cấp cho nó khả năng đọc/ghi file, thực thi lệnh terminal, và tự lặp cho đến khi test pass.
Kiến trúc tổng quan
Coding agent hoạt động theo 4 giai đoạn:
spec.md
|
v
[1. Parse Spec] --> Hiểu requirements
|
v
[2. Plan] --> Tao file structure, viet pseudocode
|
v
[3. Implement] --> Viet tung file, refine code
|
v
[4. Test Loop] --> Chay test, sua loi, lap lai
|
v
Report ket qua
Claude không chỉ sinh code một lần — nó đọc kết quả test, phân tích lỗi, và tự fix cho đến khi test pass. Đây là điểm khác biệt giữa code generator và coding agent.
File Tools — Cấp quyền truy cập filesystem
Trước tiên, định nghĩa các tools để agent tương tác với filesystem:
import anthropic
import subprocess
import os
import json
client = anthropic.Anthropic()
# Tool 1: Doc file
def read_file(path: str) -> str:
try:
with open(path, 'r', encoding='utf-8') as f:
return f.read()
except FileNotFoundError:
return f"Error: File '{path}' khong ton tai"
except Exception as e:
return f"Error: {e}"
# Tool 2: Ghi file (tao moi hoac ghi de)
def write_file(path: str, content: str) -> str:
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
return f"Da ghi file: {path} ({len(content)} ky tu)"
except Exception as e:
return f"Error: {e}"
# Tool 3: Thuc thi lenh terminal
def run_command(command: str, timeout: int = 30) -> str:
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout
)
output = result.stdout
if result.returncode != 0:
output += f"
STDERR: {result.stderr}"
output += f"
Return code: {result.returncode}"
return output or "(No output)"
except subprocess.TimeoutExpired:
return f"Error: Lenh timeout sau {timeout}s"
except Exception as e:
return f"Error: {e}"
# Tool 4: List files trong thu muc
def list_files(directory: str = ".") -> str:
try:
files = []
for root, dirs, filenames in os.walk(directory):
# Bo qua thu muc an
dirs[:] = [d for d in dirs if not d.startswith('.')]
for fname in filenames:
if not fname.startswith('.'):
rel_path = os.path.relpath(
os.path.join(root, fname), directory
)
files.append(rel_path)
return "
".join(sorted(files)) or "(Empty directory)"
except Exception as e:
return f"Error: {e}"
Tool Schemas cho Claude
coding_tools = [
{
"name": "read_file",
"description": "Doc noi dung mot file",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Duong dan den file"}
},
"required": ["path"]
}
},
{
"name": "write_file",
"description": "Ghi noi dung vao file (tao moi hoac ghi de)",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Duong dan file"},
"content": {"type": "string", "description": "Noi dung can ghi"}
},
"required": ["path", "content"]
}
},
{
"name": "run_command",
"description": "Thuc thi lenh terminal (python, pytest, npm, etc)",
"input_schema": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "Lenh can chay"},
"timeout": {"type": "integer", "description": "Timeout (giay), mac dinh 30"}
},
"required": ["command"]
}
},
{
"name": "list_files",
"description": "Liet ke file trong thu muc",
"input_schema": {
"type": "object",
"properties": {
"directory": {"type": "string", "description": "Thu muc can liet ke"}
},
"required": []
}
}
]
tool_map = {
"read_file": read_file,
"write_file": write_file,
"run_command": run_command,
"list_files": list_files
}
System Prompt — Định hình hành vi Agent
System prompt quyết định cách agent tiếp cận vấn đề:
CODING_AGENT_SYSTEM = """Ban la mot senior software engineer tu dong.
Nhiem vu cua ban: doc spec, viet code, chay test, va sua loi den khi tat ca test pass.
Quy tac:
1. Luon doc spec truoc khi viet bat ky dong code nao
2. Viet code theo tung file rieng biet, co comment ro rang
3. Sau khi viet xong, chay test ngay lap tuc
4. Neu test fail, phan tich loi va sua code — KHONG bao cao loi cho user
5. Lap lai cho den khi test pass hoac het 5 lan thu
6. Chi bao cao cho user khi tat ca test da pass (hoac het so lan thu)
Code style: Python, PEP8, type hints, docstrings.
Test framework: pytest.
"""
Coding Agent Loop
def run_coding_agent(spec_path: str, output_dir: str = "./output") -> str:
"""
Chay coding agent voi spec cho truoc.
Tra ve bao cao ket qua.
"""
os.makedirs(output_dir, exist_ok=True)
# Doc spec
spec = read_file(spec_path)
if spec.startswith("Error:"):
return f"Khong the doc spec: {spec}"
initial_message = (
f"Hay doc va implement spec sau day. "
f"Tat ca file phai duoc tao trong thu muc '{output_dir}'.
"
f"SPEC:
{spec}"
)
messages = [{"role": "user", "content": initial_message}]
print(f"Dang chay coding agent cho: {spec_path}")
print("=" * 60)
iteration = 0
max_iterations = 30 # Phong tranh loop vo han
while iteration < max_iterations:
iteration += 1
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=8192,
system=CODING_AGENT_SYSTEM,
tools=coding_tools,
messages=messages
)
messages.append({
"role": "assistant",
"content": response.content
})
if response.stop_reason == "end_turn":
# Agent bao cao xong
final_text = next(
(b.text for b in response.content if hasattr(b, "text")), ""
)
print("
" + "=" * 60)
print("KET QUA CUOI CUNG:")
print(final_text)
return final_text
elif response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(f" [{block.name}] {str(block.input)[:80]}...")
result = safe_execute(block.name, block.input)
print(f" -> {str(result)[:120]}...")
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result
})
messages.append({
"role": "user",
"content": tool_results
})
return "Het so lan thu toi da"
def safe_execute(tool_name: str, tool_input: dict) -> str:
if tool_name not in tool_map:
return f"Unknown tool: {tool_name}"
try:
return tool_map[tool_name](**tool_input)
except Exception as e:
return f"Error: {e}"
Ví dụ Spec — Calculator Module
Tạo file spec.md:
# Calculator Module Spec
## Yeu cau
Xay dung module 'calculator.py' voi cac ham sau:
- 'add(a, b)' — Cong hai so
- 'subtract(a, b)' — Tru hai so
- 'multiply(a, b)' — Nhan hai so
- 'divide(a, b)' — Chia hai so (raise ZeroDivisionError neu b=0)
- 'power(base, exp)' — Luy thua
- 'factorial(n)' — Giai thua (raise ValueError neu n < 0)
## Test requirements
Tao 'test_calculator.py' voi pytest.
Test cac truong hop: gia tri duong, am, zero, edge cases.
Phai dat it nhat 90% code coverage.
## Output
- 'calculator.py' — implementation
- 'test_calculator.py' — test suite
- 'README.md' — huong dan su dung
Chạy agent:
result = run_coding_agent("spec.md", output_dir="./calculator_project")
print(result)
Kết quả thực tế
Agent sẽ tự động:
[read_file] {'path': 'spec.md'}...
-> # Calculator Module Spec...
[write_file] {'path': './calculator_project/calculator.py'}...
-> Da ghi file: ./calculator_project/calculator.py (847 ky tu)...
[write_file] {'path': './calculator_project/test_calculator.py'}...
-> Da ghi file: ./calculator_project/test_calculator.py (1203 ky tu)...
[run_command] {'command': 'cd calculator_project && pytest -v'}...
-> ===== 12 passed in 0.45s =====...
[run_command] {'command': 'cd calculator_project && pytest --cov=calculator'}...
-> Coverage: 96%...
KET QUA CUOI CUNG:
Da implement thanh cong Calculator Module:
- calculator.py: 6 ham, day du type hints va docstrings
- test_calculator.py: 12 test cases, tat ca pass
- Coverage: 96% (vuot yeu cau 90%)
- README.md: huong dan su dung day du
Nâng cao: Self-healing loop
Khi test fail, agent tự phân tích và fix:
# Gia su pytest output cho thay loi:
# FAILED test_calculator.py::test_divide_by_zero
# AssertionError: ZeroDivisionError not raised
# Agent tu dong:
# 1. Doc lai calculator.py
# 2. Tim ham divide()
# 3. Sua code de raise ZeroDivisionError
# 4. Chay lai test
# 5. Confirm tat ca pass
Đây là self-healing — agent không chỉ sinh code, mà còn tự debug và sửa lỗi mà không cần con người can thiệp.
Security Considerations
Coding agent có quyền thực thi lệnh terminal — cần sandbox:
- Giới hạn thư mục — chỉ cho phép ghi trong output directory
- Whitelist commands — chỉ cho phép python, pytest, npm, không cho rm -rf
- Timeout — giới hạn thời gian mỗi lệnh (30s)
- Resource limits — dùng Docker để cô lập hoàn toàn
ALLOWED_COMMANDS = ["python", "pytest", "npm test", "pip install"]
def safe_run_command(command: str) -> str:
# Kiem tra command co trong whitelist khong
allowed = any(command.strip().startswith(cmd) for cmd in ALLOWED_COMMANDS)
if not allowed:
return f"Error: Command '{command}' khong duoc phep"
return run_command(command)
Tổng kết
| Tính năng | Cách implement | Lợi ích |
|---|---|---|
| Code Generation | write_file tool | Sinh code đúng spec |
| Test Execution | run_command tool | Verify code tự động |
| Self-healing | Agent loop + error analysis | Tự fix bug không cần can thiệp |
| File System | read/write/list tools | Quản lý project structure |
| Safety | Command whitelist + sandbox | Ngăn chạy lệnh nguy hiểm |
Autonomous Coding Agent là bước đầu tiên để hiểu Claude Code hoạt động như thế nào. Muốn đi xa hơn? Xem LLM Agent từ đầu để nắm vững foundation, hoặc Customer Support Agent để thấy pattern này áp dụng vào business context.
Bài viết liên quan
Bai viet co huu ich khong?
Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.



