Trung cấpHướng dẫnClaude CodeNguồn: Anthropic

Agentic Coding — Phần 5: Ứng dụng sáng tạo, tương lai và TDD workflow

Nghe bài viết
00:00

Điểm nổi bật

Nhấn để đến mục tương ứng

  1. 1 Bước 3: Generate implementation với Claude Code Claude Code sẽ tạo implementation bao gồm: Bước 4: Chạy test lại (phải pass) Đây là giai đoạn "gree...
  2. 2 Đây là phương pháp được Anthropic khuyến nghị để kiểm soát chất lượng code do AI tạo ra.
  3. 3 Ứng dụng 3: Động cơ tài liệu liên tục Phát triển các agent giám sát thay đổi code, hiểu các quyết định kiến trúc, và tự động cập nhật tài liệu kỹ t...
  4. 4 Ứng dụng 4: Agent tối ưu hiệu suất Xây dựng các agent chuyên biệt phân tích hiệu suất ứng dụng, xác định bottleneck và triển khai các tối ưu hóa.
  5. 5 Chúng có thể giám sát hiệu suất truy vấn database, đề xuất chiến lược indexing, hoặc tối ưu hóa triển khai thuật toán dựa trên số liệu production.
Man gives robot bottles on a tray

Nguồn gốc: Dịch và biên soạn từ "Scaling Agentic Coding Across Your Organization" của Anthropic.

Tải tài liệu gốc (PDF tiếng Anh)

Chuỗi bài viết: Triển khai Agentic Coding quy mô doanh nghiệp

Vượt xa việc sinh code

Những use case agentic coding thú vị nhất thường đến từ những nơi bất ngờ. Các tổ chức như Brex và Rakuten đang phát hiện rằng khả năng của Claude Code mở rộng vượt xa việc tạo code cơ bản, đi vào các quy trình kinh doanh mang tính chuyển đổi.

Các đội đang xây dựng các agent chuyên dụng trên nền tảng agentic coding như Claude Code SDK, tạo ra các trợ lý AI theo lĩnh vực cụ thể, hiểu được các thách thức kỹ thuật và yêu cầu kinh doanh riêng biệt.

Ứng dụng 1: Tự động hóa On-call thông minh

Triển khai các agent giám sát sức khỏe hệ thống, phân tích file log phức tạp, liên kết lỗi giữa các microservice, và thực hiện các bản sửa có mục tiêu. Các agent này có thể xử lý các sự cố thường gặp như memory leaks, vấn đề kết nối database, hoặc co giãn dịch vụ, chỉ leo thang khi cần phán đoán của con người.

# Vi du agent on-call voi Claude Code SDK
claude "Design an on-call automation agent that:
1. Monitors CloudWatch/Datadog alerts via webhook
2. When alert fires:
   a. Pulls relevant logs from the last 30 minutes
   b. Correlates errors across related microservices
   c. Checks recent deployments for potential cause
   d. Attempts automated remediation for known patterns:
      - Memory leak: restart service with graceful drain
      - DB connection pool exhaustion: increase pool size
      - High latency: check and clear cache
   e. If automated fix doesn't resolve in 5 min, escalate to human
3. Generates post-incident summary with root cause analysis
4. Updates runbook with new patterns discovered"

Đối với các đội SRE Việt Nam đang vận hành các hệ thống e-commerce với peak traffic vào các dịp lễ (Black Friday, 11.11, Tết), on-call automation có thể giảm đáng kể thời gian phản hồi sự cố và giảm gánh nặng cho đội trực.

Ứng dụng 2: Chuyên gia Migration và Hiện đại hóa

Tạo các agent chuyên dụng cho các chuyển đổi công nghệ cụ thể. Một agent chuyên legacy-to-cloud có thể hiểu các pattern mainframe COBOL của bạn và chuyển đổi một cách có hệ thống sang containerized microservices, giữ nguyên business logic trong khi cập nhật kiến trúc.

claude "Create a migration plan for converting this PHP Laravel monolith
to NestJS microservices:
1. Analyze all Laravel controllers, models, and routes
2. Map each module to a potential microservice boundary
3. Identify shared dependencies and data relationships
4. Propose migration order (least dependencies first)
5. For each module, generate:
   - NestJS module structure
   - API contract (OpenAPI spec)
   - Database migration scripts
   - Test suite matching current behavior
6. Create a shared library for common utilities
7. Design inter-service communication (REST vs. message queue)"

Ứng dụng 3: Động cơ tài liệu liên tục

Phát triển các agent giám sát thay đổi code, hiểu các quyết định kiến trúc, và tự động cập nhật tài liệu kỹ thuật. Các agent này duy trì API documentation, sơ đồ hệ thống, và runbooks đồng bộ với triển khai thực tế.

claude "Set up a documentation automation workflow:
1. On each PR merge to main:
   - Detect which API endpoints were modified
   - Update OpenAPI spec automatically
   - Generate changelog entry
   - Update architecture diagrams if new services added
2. Weekly:
   - Scan for undocumented public functions
   - Check for stale documentation (code changed but docs didn't)
   - Generate 'documentation debt' report
3. Create a /update-docs slash command that:
   - Analyzes recent changes
   - Updates relevant documentation
   - Creates a PR with documentation changes"

Ứng dụng 4: Agent tối ưu hiệu suất

Xây dựng các agent chuyên biệt phân tích hiệu suất ứng dụng, xác định bottleneck và triển khai các tối ưu hóa. Chúng có thể giám sát hiệu suất truy vấn database, đề xuất chiến lược indexing, hoặc tối ưu hóa triển khai thuật toán dựa trên số liệu production.

claude "Analyze the slow query log and:
1. Identify top 10 slowest queries
2. For each query:
   - Explain why it's slow (missing index, full table scan, N+1, etc.)
   - Provide optimized version
   - Suggest indexes to add
   - Estimate performance improvement
3. Check for N+1 query patterns in the ORM layer
4. Propose a caching strategy for frequently repeated queries
5. Create a monitoring dashboard query for ongoing tracking"

Ứng dụng 5: Agent tuân thủ quy định

Tạo các agent hiểu các yêu cầu quy định cụ thể (GDPR, SOX, HIPAA) và kiểm toán codebase liên tục về các vấn đề tuân thủ, tự động triển khai các kiểm soát và tài liệu bắt buộc.

Với các công ty Việt Nam trong lĩnh vực fintech hoặc healthtech, agent tuân thủ có thể kiểm tra xem code có tuân theo Nghị định 13 về bảo vệ dữ liệu cá nhân, Thông tư NHNN về giao dịch điện tử, hay các chuẩn quốc tế như PCI DSS.

Nhìn về tương lai

Agentic coding đại diện cho một sự chuyển dịch căn bản trong cách chúng ta xây dựng phần mềm — từ phát triển do con người viết sang phát triển do con người hướng dẫn (human-guided development). Các tổ chức thành công nhất không phải là những tổ chức di chuyển nhanh nhất, mà là những tổ chức xây dựng nền tảng vững chắc nhất.

Lộ trình của Anthropic:

  1. Bắt đầu nhỏ với nhóm pilot
  2. Xây dựng chuyên môn nội bộ
  3. Tạo cơ sở hạ tầng cho thành công
  4. Mở rộng có chủ đích, sử dụng hackathon và champion nội bộ để thúc đẩy việc áp dụng

Agentic coding là bộ khuếch đại nhận thức của đội bạn. Câu hỏi duy nhất là: bạn có thể giúp họ khai thác nó nhanh đến mức nào?

Phụ lục: TDD Workflow với Claude Code — 5 bước thực tế

Dưới đây là quy trình Test-Driven Development đầy đủ với Claude Code, minh họa qua ví dụ xây dựng hệ thống xác thực người dùng. Đây là phương pháp được Anthropic khuyến nghị để kiểm soát chất lượng code do AI tạo ra.

Bước 1: Định nghĩa yêu cầu với Claude Code

Bắt đầu bằng việc yêu cầu Claude Code viết test toàn diện:

claude "Create comprehensive tests for a user authentication system
with registration, login, password reset, and JWT token management"

Claude Code sẽ tạo một bộ test đầy đủ bao gồm:

# tests/test_auth_system.py
import pytest
import jwt
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
from auth_system import AuthSystem, User, AuthenticationError, ValidationError

class TestUserAuthentication:
    @pytest.fixture
    def auth_system(self):
        return AuthSystem(secret_key="test_secret", db_connection=Mock())

    @pytest.fixture
    def valid_user_data(self):
        return {
            "email": "user@example.com",
            "password": "SecurePass123!",
            "confirm_password": "SecurePass123!"
        }

    # Registration Tests
    def test_register_user_success(self, auth_system, valid_user_data):
        """Test successful user registration"""
        with patch.object(auth_system.db, 'user_exists', return_value=False):
            with patch.object(auth_system.db, 'create_user', return_value=True):
                result = auth_system.register(**valid_user_data)
                assert result['success'] == True
                assert result['user_id'] is not None

    def test_register_invalid_email_format(self, auth_system):
        """Test registration with invalid email format"""
        invalid_data = {
            "email": "invalid-email",
            "password": "SecurePass123!",
            "confirm_password": "SecurePass123!"
        }
        with pytest.raises(ValidationError) as exc_info:
            auth_system.register(**invalid_data)
        assert "Invalid email format" in str(exc_info.value)

    def test_register_weak_password(self, auth_system):
        """Test registration with weak password"""
        weak_data = {
            "email": "user@example.com",
            "password": "123",
            "confirm_password": "123"
        }
        with pytest.raises(ValidationError) as exc_info:
            auth_system.register(**weak_data)
        assert "Password must be at least 8 characters" in str(exc_info.value)

    # Login Tests
    def test_login_success(self, auth_system):
        """Test successful login"""
        mock_user = Mock()
        mock_user.id = 1
        mock_user.email = "user@example.com"
        with patch.object(auth_system.db, 'get_user_by_email', return_value=mock_user):
            with patch.object(auth_system, '_verify_password', return_value=True):
                result = auth_system.login("user@example.com", "correct_password")
                assert result['success'] == True
                assert 'access_token' in result
                assert 'refresh_token' in result

    # JWT Token Tests
    def test_verify_expired_token(self, auth_system):
        """Test verification of expired JWT token"""
        payload = {
            'user_id': 1,
            'type': 'access',
            'exp': datetime.utcnow() - timedelta(hours=1)
        }
        expired_token = jwt.encode(payload, "test_secret", algorithm="HS256")
        result = auth_system.verify_token(expired_token)
        assert result['valid'] == False
        assert result['error'] == 'Token expired'

Bước 2: Chạy test (phải fail)

pytest tests/test_auth_system.py -v

# Expected: Tat ca test fail vi chua co implementation

Đây là bước quan trọng trong TDD: xác nhận test thực sự kiểm tra điều gì đó (nếu test pass mà chưa có code, test đó vô nghĩa).

Bước 3: Generate implementation với Claude Code

claude "Implement the AuthSystem class to pass all the existing tests.
Focus on security best practices for password hashing and JWT token management."

Claude Code sẽ tạo implementation bao gồm:

# auth_system.py
import bcrypt
import jwt
import re
from datetime import datetime, timedelta
from typing import Dict, Optional, Any
import secrets

class AuthenticationError(Exception):
    """Raised when authentication fails"""
    pass

class ValidationError(Exception):
    """Raised when input validation fails"""
    pass

class AuthSystem:
    def __init__(self, secret_key: str, db_connection,
                 access_token_expire_hours: int = 1,
                 refresh_token_expire_days: int = 30):
        self.secret_key = secret_key
        self.db = db_connection
        self.access_token_expire_hours = access_token_expire_hours
        self.refresh_token_expire_days = refresh_token_expire_days
        self.min_password_length = 8

    def register(self, email: str, password: str,
                 confirm_password: str) -> Dict[str, Any]:
        """Register a new user"""
        self._validate_registration_input(email, password, confirm_password)

        if self.db.user_exists(email):
            raise ValidationError("Email already registered")

        password_hash = bcrypt.hashpw(
            password.encode('utf-8'), bcrypt.gensalt()
        ).decode('utf-8')

        user_id = self.db.create_user(email, password_hash)
        return {
            'success': True,
            'user_id': user_id,
            'message': 'User registered successfully'
        }

    def login(self, email: str, password: str) -> Dict[str, Any]:
        """Authenticate user and return tokens"""
        user = self.db.get_user_by_email(email)
        if not user:
            raise AuthenticationError("Invalid credentials")

        if not self._verify_password(password, user.password_hash):
            raise AuthenticationError("Invalid credentials")

        access_token = self.generate_access_token(user.id)
        refresh_token = self.generate_refresh_token(user.id)
        return {
            'success': True,
            'access_token': access_token,
            'refresh_token': refresh_token,
            'user': {'id': user.id, 'email': user.email}
        }

    def generate_access_token(self, user_id: int) -> str:
        """Generate JWT access token"""
        payload = {
            'user_id': user_id,
            'type': 'access',
            'exp': datetime.utcnow() + timedelta(
                hours=self.access_token_expire_hours
            ),
            'iat': datetime.utcnow()
        }
        return jwt.encode(payload, self.secret_key, algorithm='HS256')

    def verify_token(self, token: str) -> Dict[str, Any]:
        """Verify JWT token"""
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
            return {'valid': True, 'user_id': payload['user_id']}
        except jwt.ExpiredSignatureError:
            return {'valid': False, 'error': 'Token expired'}
        except jwt.InvalidTokenError:
            return {'valid': False, 'error': 'Invalid token'}

Bước 4: Chạy test lại (phải pass)

pytest tests/test_auth_system.py -v

# Expected: Tat ca test pass!

Đây là giai đoạn "green" trong TDD: code mới làm cho tất cả test pass.

Bước 5: Refactor và cải thiện

claude "Review the authentication system for security improvements,
add rate limiting for login attempts, and enhance error handling.
Maintain all existing test compatibility."

Claude Code sẽ:

  • Thêm rate limiting cho login attempts (chống brute force)
  • Cải thiện error handling với các edge cases
  • Tối ưu hóa performance
  • Giữ nguyên tương thích với tất cả test hiện có

Tại sao TDD đặc biệt quan trọng với agentic coding?

  • Rào chắn an toàn: Test là "hàng rào" đảm bảo code do AI tạo hoạt động đúng
  • Định nghĩa thành công rõ ràng: Test cho AI biết chính xác kết quả mong đợi là gì
  • Kiểm soát chất lượng: Mỗi bước được xác nhận trước khi tiến lên bước tiếp
  • Refactor an toàn: Có thể cải thiện code mà không lo làm hỏng chức năng hiện có
  • Documentation tự động: Test là tài liệu sống về cách code nên hoạt động

Áp dụng TDD cho dự án Việt Nam

# Vi du TDD cho API thanh toan VNPay
claude "Write comprehensive tests for a VNPay payment integration:
1. Create payment URL with correct checksum
2. Verify IPN (Instant Payment Notification) callback
3. Handle successful payment
4. Handle failed payment
5. Handle duplicate IPN callbacks (idempotency)
6. Validate amount format (VND, no decimals)
7. Check timeout scenarios
8. Verify refund flow

Use pytest. Mock VNPay API responses.
Include edge cases: network timeout, invalid checksum, amount mismatch."

# Sau do implement
claude "Implement the VNPay integration to pass all tests.
Follow VNPay API v2.1.0 documentation.
Use HMAC-SHA512 for checksum."

Tổng kết chuỗi bài viết

Qua 5 phần của chuỗi bài viết này, chúng ta đã đi qua toàn bộ hành trình triển khai agentic coding quy mô doanh nghiệp:

  1. Nền tảng: Hiểu agentic coding là gì và xây dựng chiến lược triển khai 3 bước
  2. Đo lường: Thiết lập hệ thống đo ROI để chứng minh giá trị
  3. Vượt rào cản: Xử lý các thách thức phổ biến và xây dựng kỹ năng prompt engineering
  4. Bảo mật: Đảm bảo an toàn với policy-as-code, MCP governance và enterprise permissions
  5. Đổi mới: Khai thác tiềm năng vượt xa việc sinh code và áp dụng TDD để kiểm soát chất lượng

Hãy bắt đầu từ việc nhỏ: cài đặt Claude Code, tạo file CLAUDE.md cho dự án của bạn, và thử với 2-3 task lặp lại. Từ đó, xây dựng dần lên theo lộ trình đã trình bày.

Khám phá thêm các hướng dẫn về Claude Code tại Thư viện Ứng dụngThư viện Nâng cao.

Chuỗi bài viết: Triển khai Agentic Coding quy mô doanh nghiệp

Tính năng liên quan:On-call AutomationMigration AgentsPerformance OptimizationTDD WorkflowClaude Code SDK

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ẻ.

Bình luận (0)
Ảnh đại diện
Đăng nhập để bình luận...
Đăng nhập để bình luận
  • Đang tải bình luận...

Đăng ký nhận bản tin

Nhận bài viết hay nhất về sản phẩm và vận hành, gửi thẳng vào hộp thư của bạn.

Bảo mật thông tin. Hủy đăng ký bất cứ lúc nào. Chính sách bảo mật.