{"product_id":"autonomous-coding-agent-ai-tự-viết-code-từ-spec","title":"Autonomous Coding Agent — AI tự viết code từ spec","description":"\n\u003cp\u003eHãy tưởng tượng: bạn viết một file \u003ccode\u003espec.md\u003c\/code\u003e 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 đó.\u003c\/p\u003e\n\n\u003cp\u003eAutonomous 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.\u003c\/p\u003e\n\n\u003ch2\u003eKiến trúc tổng quan\u003c\/h2\u003e\n\n\u003cp\u003eCoding agent hoạt động theo 4 giai đoạn:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003espec.md\n  |\n  v\n[1. Parse Spec] --\u0026gt; Hiểu requirements\n  |\n  v\n[2. Plan] --\u0026gt; Tao file structure, viet pseudocode\n  |\n  v\n[3. Implement] --\u0026gt; Viet tung file, refine code\n  |\n  v\n[4. Test Loop] --\u0026gt; Chay test, sua loi, lap lai\n  |\n  v\nReport ket qua\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003cp\u003eClaude 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 \u003cem\u003eagent\u003c\/em\u003e.\u003c\/p\u003e\n\n\u003ch2\u003eFile Tools — Cấp quyền truy cập filesystem\u003c\/h2\u003e\n\n\u003cp\u003eTrước tiên, định nghĩa các tools để agent tương tác với filesystem:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport anthropic\nimport subprocess\nimport os\nimport json\n\nclient = anthropic.Anthropic()\n\n# Tool 1: Doc file\ndef read_file(path: str) -\u0026gt; str:\n    try:\n        with open(path, 'r', encoding='utf-8') as f:\n            return f.read()\n    except FileNotFoundError:\n        return f\"Error: File '{path}' khong ton tai\"\n    except Exception as e:\n        return f\"Error: {e}\"\n\n# Tool 2: Ghi file (tao moi hoac ghi de)\ndef write_file(path: str, content: str) -\u0026gt; str:\n    try:\n        os.makedirs(os.path.dirname(path), exist_ok=True)\n        with open(path, 'w', encoding='utf-8') as f:\n            f.write(content)\n        return f\"Da ghi file: {path} ({len(content)} ky tu)\"\n    except Exception as e:\n        return f\"Error: {e}\"\n\n# Tool 3: Thuc thi lenh terminal\ndef run_command(command: str, timeout: int = 30) -\u0026gt; str:\n    try:\n        result = subprocess.run(\n            command,\n            shell=True,\n            capture_output=True,\n            text=True,\n            timeout=timeout\n        )\n        output = result.stdout\n        if result.returncode != 0:\n            output += f\"\nSTDERR: {result.stderr}\"\n            output += f\"\nReturn code: {result.returncode}\"\n        return output or \"(No output)\"\n    except subprocess.TimeoutExpired:\n        return f\"Error: Lenh timeout sau {timeout}s\"\n    except Exception as e:\n        return f\"Error: {e}\"\n\n# Tool 4: List files trong thu muc\ndef list_files(directory: str = \".\") -\u0026gt; str:\n    try:\n        files = []\n        for root, dirs, filenames in os.walk(directory):\n            # Bo qua thu muc an\n            dirs[:] = [d for d in dirs if not d.startswith('.')]\n            for fname in filenames:\n                if not fname.startswith('.'):\n                    rel_path = os.path.relpath(\n                        os.path.join(root, fname), directory\n                    )\n                    files.append(rel_path)\n        return \"\n\".join(sorted(files)) or \"(Empty directory)\"\n    except Exception as e:\n        return f\"Error: {e}\"\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eTool Schemas cho Claude\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003ecoding_tools = [\n    {\n        \"name\": \"read_file\",\n        \"description\": \"Doc noi dung mot file\",\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"path\": {\"type\": \"string\", \"description\": \"Duong dan den file\"}\n            },\n            \"required\": [\"path\"]\n        }\n    },\n    {\n        \"name\": \"write_file\",\n        \"description\": \"Ghi noi dung vao file (tao moi hoac ghi de)\",\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"path\": {\"type\": \"string\", \"description\": \"Duong dan file\"},\n                \"content\": {\"type\": \"string\", \"description\": \"Noi dung can ghi\"}\n            },\n            \"required\": [\"path\", \"content\"]\n        }\n    },\n    {\n        \"name\": \"run_command\",\n        \"description\": \"Thuc thi lenh terminal (python, pytest, npm, etc)\",\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"command\": {\"type\": \"string\", \"description\": \"Lenh can chay\"},\n                \"timeout\": {\"type\": \"integer\", \"description\": \"Timeout (giay), mac dinh 30\"}\n            },\n            \"required\": [\"command\"]\n        }\n    },\n    {\n        \"name\": \"list_files\",\n        \"description\": \"Liet ke file trong thu muc\",\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"directory\": {\"type\": \"string\", \"description\": \"Thu muc can liet ke\"}\n            },\n            \"required\": []\n        }\n    }\n]\n\ntool_map = {\n    \"read_file\": read_file,\n    \"write_file\": write_file,\n    \"run_command\": run_command,\n    \"list_files\": list_files\n}\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eSystem Prompt — Định hình hành vi Agent\u003c\/h2\u003e\n\n\u003cp\u003eSystem prompt quyết định cách agent tiếp cận vấn đề:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eCODING_AGENT_SYSTEM = \"\"\"Ban la mot senior software engineer tu dong.\nNhiem vu cua ban: doc spec, viet code, chay test, va sua loi den khi tat ca test pass.\n\nQuy tac:\n1. Luon doc spec truoc khi viet bat ky dong code nao\n2. Viet code theo tung file rieng biet, co comment ro rang\n3. Sau khi viet xong, chay test ngay lap tuc\n4. Neu test fail, phan tich loi va sua code — KHONG bao cao loi cho user\n5. Lap lai cho den khi test pass hoac het 5 lan thu\n6. Chi bao cao cho user khi tat ca test da pass (hoac het so lan thu)\n\nCode style: Python, PEP8, type hints, docstrings.\nTest framework: pytest.\n\"\"\"\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eCoding Agent Loop\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003edef run_coding_agent(spec_path: str, output_dir: str = \".\/output\") -\u0026gt; str:\n    \"\"\"\n    Chay coding agent voi spec cho truoc.\n    Tra ve bao cao ket qua.\n    \"\"\"\n    os.makedirs(output_dir, exist_ok=True)\n\n    # Doc spec\n    spec = read_file(spec_path)\n    if spec.startswith(\"Error:\"):\n        return f\"Khong the doc spec: {spec}\"\n\n    initial_message = (\n        f\"Hay doc va implement spec sau day. \"\n        f\"Tat ca file phai duoc tao trong thu muc '{output_dir}'.\n\n\"\n        f\"SPEC:\n{spec}\"\n    )\n\n    messages = [{\"role\": \"user\", \"content\": initial_message}]\n\n    print(f\"Dang chay coding agent cho: {spec_path}\")\n    print(\"=\" * 60)\n\n    iteration = 0\n    max_iterations = 30  # Phong tranh loop vo han\n\n    while iteration \u0026lt; max_iterations:\n        iteration += 1\n\n        response = client.messages.create(\n            model=\"claude-sonnet-4-5\",\n            max_tokens=8192,\n            system=CODING_AGENT_SYSTEM,\n            tools=coding_tools,\n            messages=messages\n        )\n\n        messages.append({\n            \"role\": \"assistant\",\n            \"content\": response.content\n        })\n\n        if response.stop_reason == \"end_turn\":\n            # Agent bao cao xong\n            final_text = next(\n                (b.text for b in response.content if hasattr(b, \"text\")), \"\"\n            )\n            print(\"\n\" + \"=\" * 60)\n            print(\"KET QUA CUOI CUNG:\")\n            print(final_text)\n            return final_text\n\n        elif response.stop_reason == \"tool_use\":\n            tool_results = []\n\n            for block in response.content:\n                if block.type == \"tool_use\":\n                    print(f\"  [{block.name}] {str(block.input)[:80]}...\")\n\n                    result = safe_execute(block.name, block.input)\n                    print(f\"  -\u0026gt; {str(result)[:120]}...\")\n\n                    tool_results.append({\n                        \"type\": \"tool_result\",\n                        \"tool_use_id\": block.id,\n                        \"content\": result\n                    })\n\n            messages.append({\n                \"role\": \"user\",\n                \"content\": tool_results\n            })\n\n    return \"Het so lan thu toi da\"\n\n\ndef safe_execute(tool_name: str, tool_input: dict) -\u0026gt; str:\n    if tool_name not in tool_map:\n        return f\"Unknown tool: {tool_name}\"\n    try:\n        return tool_map[tool_name](**tool_input)\n    except Exception as e:\n        return f\"Error: {e}\"\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eVí dụ Spec — Calculator Module\u003c\/h2\u003e\n\n\u003cp\u003eTạo file \u003ccode\u003espec.md\u003c\/code\u003e:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e# Calculator Module Spec\n\n## Yeu cau\nXay dung module 'calculator.py' voi cac ham sau:\n- 'add(a, b)' — Cong hai so\n- 'subtract(a, b)' — Tru hai so\n- 'multiply(a, b)' — Nhan hai so\n- 'divide(a, b)' — Chia hai so (raise ZeroDivisionError neu b=0)\n- 'power(base, exp)' — Luy thua\n- 'factorial(n)' — Giai thua (raise ValueError neu n \u0026lt; 0)\n\n## Test requirements\nTao 'test_calculator.py' voi pytest.\nTest cac truong hop: gia tri duong, am, zero, edge cases.\nPhai dat it nhat 90% code coverage.\n\n## Output\n- 'calculator.py' — implementation\n- 'test_calculator.py' — test suite\n- 'README.md' — huong dan su dung\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003cp\u003eChạy agent:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eresult = run_coding_agent(\"spec.md\", output_dir=\".\/calculator_project\")\nprint(result)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eKết quả thực tế\u003c\/h2\u003e\n\n\u003cp\u003eAgent sẽ tự động:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e  [read_file] {'path': 'spec.md'}...\n  -\u0026gt; # Calculator Module Spec...\n  [write_file] {'path': '.\/calculator_project\/calculator.py'}...\n  -\u0026gt; Da ghi file: .\/calculator_project\/calculator.py (847 ky tu)...\n  [write_file] {'path': '.\/calculator_project\/test_calculator.py'}...\n  -\u0026gt; Da ghi file: .\/calculator_project\/test_calculator.py (1203 ky tu)...\n  [run_command] {'command': 'cd calculator_project \u0026amp;\u0026amp; pytest -v'}...\n  -\u0026gt; ===== 12 passed in 0.45s =====...\n  [run_command] {'command': 'cd calculator_project \u0026amp;\u0026amp; pytest --cov=calculator'}...\n  -\u0026gt; Coverage: 96%...\n\nKET QUA CUOI CUNG:\nDa implement thanh cong Calculator Module:\n- calculator.py: 6 ham, day du type hints va docstrings\n- test_calculator.py: 12 test cases, tat ca pass\n- Coverage: 96% (vuot yeu cau 90%)\n- README.md: huong dan su dung day du\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eNâng cao: Self-healing loop\u003c\/h2\u003e\n\n\u003cp\u003eKhi test fail, agent tự phân tích và fix:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e# Gia su pytest output cho thay loi:\n# FAILED test_calculator.py::test_divide_by_zero\n# AssertionError: ZeroDivisionError not raised\n\n# Agent tu dong:\n# 1. Doc lai calculator.py\n# 2. Tim ham divide()\n# 3. Sua code de raise ZeroDivisionError\n# 4. Chay lai test\n# 5. Confirm tat ca pass\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003cp\u003eĐây là \u003cstrong\u003eself-healing\u003c\/strong\u003e — 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.\u003c\/p\u003e\n\n\u003ch2\u003eSecurity Considerations\u003c\/h2\u003e\n\n\u003cp\u003eCoding agent có quyền thực thi lệnh terminal — cần sandbox:\u003c\/p\u003e\n\n\u003cul\u003e\n  \u003cli\u003e\n\u003cstrong\u003eGiới hạn thư mục\u003c\/strong\u003e — chỉ cho phép ghi trong output directory\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eWhitelist commands\u003c\/strong\u003e — chỉ cho phép python, pytest, npm, không cho rm -rf\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eTimeout\u003c\/strong\u003e — giới hạn thời gian mỗi lệnh (30s)\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eResource limits\u003c\/strong\u003e — dùng Docker để cô lập hoàn toàn\u003c\/li\u003e\n\u003c\/ul\u003e\n\n\u003cpre\u003e\u003ccode\u003eALLOWED_COMMANDS = [\"python\", \"pytest\", \"npm test\", \"pip install\"]\n\ndef safe_run_command(command: str) -\u0026gt; str:\n    # Kiem tra command co trong whitelist khong\n    allowed = any(command.strip().startswith(cmd) for cmd in ALLOWED_COMMANDS)\n    if not allowed:\n        return f\"Error: Command '{command}' khong duoc phep\"\n    return run_command(command)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eTổng kết\u003c\/h2\u003e\n\n\u003ctable\u003e\n  \u003cthead\u003e\n    \u003ctr\u003e\n\u003cth\u003eTính năng\u003c\/th\u003e\n\u003cth\u003eCách implement\u003c\/th\u003e\n\u003cth\u003eLợi ích\u003c\/th\u003e\n\u003c\/tr\u003e\n  \u003c\/thead\u003e\n  \u003ctbody\u003e\n    \u003ctr\u003e\n\u003ctd\u003eCode Generation\u003c\/td\u003e\n\u003ctd\u003ewrite_file tool\u003c\/td\u003e\n\u003ctd\u003eSinh code đúng spec\u003c\/td\u003e\n\u003c\/tr\u003e\n    \u003ctr\u003e\n\u003ctd\u003eTest Execution\u003c\/td\u003e\n\u003ctd\u003erun_command tool\u003c\/td\u003e\n\u003ctd\u003eVerify code tự động\u003c\/td\u003e\n\u003c\/tr\u003e\n    \u003ctr\u003e\n\u003ctd\u003eSelf-healing\u003c\/td\u003e\n\u003ctd\u003eAgent loop + error analysis\u003c\/td\u003e\n\u003ctd\u003eTự fix bug không cần can thiệp\u003c\/td\u003e\n\u003c\/tr\u003e\n    \u003ctr\u003e\n\u003ctd\u003eFile System\u003c\/td\u003e\n\u003ctd\u003eread\/write\/list tools\u003c\/td\u003e\n\u003ctd\u003eQuản lý project structure\u003c\/td\u003e\n\u003c\/tr\u003e\n    \u003ctr\u003e\n\u003ctd\u003eSafety\u003c\/td\u003e\n\u003ctd\u003eCommand whitelist + sandbox\u003c\/td\u003e\n\u003ctd\u003eNgăn chạy lệnh nguy hiểm\u003c\/td\u003e\n\u003c\/tr\u003e\n  \u003c\/tbody\u003e\n\u003c\/table\u003e\n\n\u003cp\u003eAutonomous 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 \u003ca href=\"\/collections\/nang-cao\"\u003eLLM Agent từ đầu\u003c\/a\u003e để nắm vững foundation, hoặc \u003ca href=\"\/collections\/ung-dung\"\u003eCustomer Support Agent\u003c\/a\u003e để thấy pattern này áp dụng vào business context.\u003c\/p\u003e\n\n\n\u003chr\u003e\n\u003ch3\u003eBài viết liên quan\u003c\/h3\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ca href=\"\/products\/claude-cho-engineering-chi%E1%BA%BFn-l%C6%B0%E1%BB%A3c-testing-toan-di%E1%BB%87n\"\u003eClaude cho Engineering: Chiến lược testing toàn diện\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/claude-cho-engineering-code-review-t%E1%BB%B1-d%E1%BB%99ng\"\u003eClaude cho Engineering: Code Review tự động\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/claude-cho-engineering-debug-va-x%E1%BB%AD-ly-l%E1%BB%97i\"\u003eClaude cho Engineering: Debug và xử lý lỗi\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/evaluator-optimizer-t%E1%BB%B1-c%E1%BA%A3i-thi%E1%BB%87n-output-v%E1%BB%9Bi-feedback-loop\"\u003eEvaluator-Optimizer — Tự cải thiện output với feedback loop\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/claude-code-toan-t%E1%BA%ADp-l%E1%BA%ADp-trinh-v%E1%BB%9Bi-ai-agent-trong-terminal\"\u003eClaude Code toàn tập — Lập trình với AI agent trong terminal\u003c\/a\u003e\u003c\/li\u003e\n\u003c\/ul\u003e","brand":"Minh Tuấn","offers":[{"title":"Default Title","offer_id":47721909846228,"sku":null,"price":0.0,"currency_code":"VND","in_stock":true}],"thumbnail_url":"\/\/cdn.shopify.com\/s\/files\/1\/0821\/0264\/9044\/files\/autonomous-coding-agent-ai-t_-vi_t-code-t_-spec.jpg?v=1774526594","url":"https:\/\/claude.vn\/products\/autonomous-coding-agent-ai-t%e1%bb%b1-vi%e1%ba%bft-code-t%e1%bb%ab-spec","provider":"CLAUDE.VN","version":"1.0","type":"link"}