← Back to Course Summary / 返回课程总结
WEEK 5

Agentic Development
Agent驱动开发

Multi-Agent AI Workflows for Software Development
多Agent AI软件工作流

Learn to create specialized AI agents that collaborate on development tasks. Implement saved prompts, coding rules, and coordinate multi-agent workflows using Claude Code for 2-3x productivity gains.

学习创建专门的AI Agent协作完成开发任务。实现保存的提示词、编码规则,并使用Claude Code协调多Agent工作流,实现2-3倍生产力提升。

Hands-On Tutorial / 实践教程

🎯 This Week's Project / 本周项目
Build an Extraction Enhancement System using 4 specialized agents working together to implement hashtag parsing, task extraction, API endpoints, comprehensive tests, and documentation.

使用4个专门Agent构建提取增强系统,协作实现标签解析、任务提取、API端点、全面测试和文档。

Exercise 1: Create Saved Prompts / 练习1:创建保存的提示词

1
Create Commands Directory / 创建命令目录
Claude Code stores saved prompts in .claude/commands/

Claude Code将保存的提示词存储在.claude/commands/
mkdir -p .claude/commands
2
Create Test Pagination Command / 创建分页测试命令
Create .claude/commands/test-pagination.md

创建.claude/commands/test-pagination.md
# Test Pagination Generator

Generate comprehensive tests for paginated endpoints.

## Usage
/test-pagination 

## Parameters
- endpoint_path: The API endpoint to test (e.g., /notes, /action-items)

## What It Does
1. Analyzes the endpoint router file
2. Generates test cases for:
   - Default pagination (page=1, page_size=10)
   - Custom page sizes
   - Boundary conditions (page_size=1, page_size=100)
   - Invalid parameters (page<1, page_size>100)
   - Empty result sets
   - Page beyond available data
3. Creates test file if needed
4. Runs tests and reports coverage

## Example Usage
/test-pagination /notes
/test-pagination /action-items
3
Create Error Standardization Command / 创建错误标准化命令
Create .claude/commands/standardize-errors.md

创建.claude/commands/standardize-errors.md
# Standardize Error Handling

Apply standard error envelope pattern to all endpoints.

## Usage
/standardize-errors [--full]

## Options
- --full: Apply changes (without flag, shows preview only)

## What It Does
1. Creates error schemas in backend/app/schemas.py
2. Creates error utilities in backend/app/utils/errors.py
3. Adds global exception handlers to backend/app/main.py
4. Updates all endpoints to use custom exceptions
5. Ensures consistent error response format

## Error Response Format
{
  "ok": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable message",
    "details": { ... }
  }
}

## Standard Error Codes
- VALIDATION_ERROR (400)
- NOT_FOUND (404)
- CONFLICT (409)
- INTERNAL_ERROR (500)

Exercise 2: Create Coding Rules / 练习2:创建编码规则

1
Create Rules Directory / 创建规则目录
Create .claude/rules/ for coding standards

创建.claude/rules/用于编码标准
mkdir -p .claude/rules
2
Create Pagination Pattern Rule / 创建分页模式规则
Create .claude/rules/pagination-pattern.md

创建.claude/rules/pagination-pattern.md
# Pagination Pattern Rule

All list endpoints MUST follow this pagination pattern.

## Request Parameters
| Parameter | Type | Default | Min | Max | Description |
|-----------|------|---------|-----|-----|-------------|
| page | int | 1 | 1 | - | Page number (1-indexed) |
| page_size | int | 10 | 1 | 100 | Items per page |

## Response Schema
{
  "items": List[T],      # The paginated items
  "total": int,          # Total count across all pages
  "page": int,           # Current page number
  "page_size": int       # Current page size
}

## Pydantic Schemas
class PaginationParams(BaseModel):
    page: int = Field(default=1, ge=1)
    page_size: int = Field(default=10, ge=1, le=100)

class PaginatedResponse(BaseModel, Generic[T]):
    items: List[T]
    total: int
    page: int
    page_size: int

## SQLAlchemy Helper
def paginate_query(query, session, page, page_size):
    offset = (page - 1) * page_size
    total = session.execute(select(func.count()).select_from(query.subquery())).scalar()
    items = session.execute(query.offset(offset).limit(page_size)).scalars().all()
    return items, total
3
Create Error Envelope Rule / 创建错误信封规则
Create .claude/rules/error-envelope.md

创建.claude/rules/error-envelope.md
# Error Envelope Pattern Rule

All endpoints MUST use standard error response format.

## Success Response
{
  "ok": true,
  "data": { ... }
}

## Error Response
{
  "ok": false,
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable message",
    "details": { ... }
  }
}

## Custom Exceptions
class AppException(HTTPException):
    def __init__(self, code, message, status_code=500, details=None):
        self.code = code
        self.message = message
        self.details = details or {}
        super().__init__(status_code=status_code, detail=message)

class NotFoundException(AppException):
    def __init__(self, resource, identifier=None):
        message = f"{resource} not found"
        if identifier:
            message += f": {identifier}"
        super().__init__("NOT_FOUND", message, 404)

## Usage in Endpoints
note = db.get(Note, note_id)
if not note:
    raise NotFoundException("Note", identifier=str(note_id))

Exercise 3: Implement Multi-Agent Workflow / 练习3:实现多Agent工作流

🎯 Task: Extraction Enhancement / 任务:提取增强
Implement hashtag (#tag) and task (- [ ]) extraction from notes.
实现从笔记中提取标签(#tag)和任务(- [ ])。
1
Create SubAgents Directory / 创建SubAgent目录
Create .claude/subagents/

创建.claude/subagents/
mkdir -p .claude/subagents
2
Define ParserAgent / 定义ParserAgent
Create .claude/subagents/parser-agent.md

创建.claude/subagents/parser-agent.md
# ParserAgent - Text Parsing Specialist

You are an expert in text parsing, regex patterns, and data extraction.

## Role
Implement robust text parsing functions to extract structured data from unstructured text.

## Responsibilities
1. Extract hashtags (#tag) from text
2. Extract tasks (- [ ] text) from text
3. Handle edge cases (empty input, malformed syntax)
4. Write unit tests for parsing logic

## Hashtag Extraction
- Pattern: # followed by word characters
- Example: "Meeting #team #urgent" → ["team", "urgent"]
- Edge cases: Multiple hashtags, duplicates, case sensitivity

## Task Extraction
- Pattern: "- [ ]" followed by task text
- Example: "- [ ] Review PR" → "Review PR"
- Nested items: Support indentation levels
- Completed tasks: "- [x]" (optional)

## Implementation Location
backend/app/services/extract.py

## Function Signatures
def extract_hashtags(text: str) -> list[str]:
    """Extract all hashtags from text."""
    pass

def extract_tasks(text: str) -> list[str]:
    """Extract all tasks from text."""
    pass

## Testing
Write comprehensive tests in backend/tests/test_extract.py covering:
- Normal cases
- Empty strings
- No matches
- Multiple matches
- Edge cases
3
Define BackendAgent / 定义BackendAgent
Create .claude/subagents/backend-agent.md

创建.claude/subagents/backend-agent.md
# BackendAgent - API Implementation Specialist

You are an expert in FastAPI, database operations, and REST API design.

## Role
Implement API endpoints that use ParserAgent's extraction functions.

## Responsibilities
1. Create Pydantic schemas for extraction responses
2. Implement POST /notes/{id}/extract endpoint
3. Add optional ?apply=true parameter for persistence
4. Handle errors with custom exceptions
5. Document the endpoint

## Endpoint Specification
POST /notes/{note_id}/extract?apply=false

Response (apply=false):
{
  "ok": true,
  "data": {
    "hashtags": ["team", "urgent"],
    "tasks": ["Review PR", "Update docs"]
  }
}

Response (apply=true):
{
  "ok": true,
  "data": {
    "note": { ... },
    "extracted": {
      "hashtags": ["team", "urgent"],
      "tasks": ["Review PR", "Update docs"]
    }
  }
}

## Implementation
backend/app/routers/notes.py

## Error Handling
- Note not found: NotFoundException(404)
- Invalid note ID: ValidationException(400)
4
Define TestAgent / 定义TestAgent
Create .claude/subagents/test-agent.md

创建.claude/subagents/test-agent.md
# TestAgent - Testing Specialist

You are an expert in writing comprehensive tests with pytest.

## Role
Ensure complete test coverage for extraction functionality.

## Responsibilities
1. Unit tests for parsing functions
2. Integration tests for API endpoint
3. Edge case testing
4. Coverage verification (>80%)

## Test Structure
backend/tests/test_extract.py:
- test_extract_hashtags_normal()
- test_extract_hashtags_empty()
- test_extract_hashtags_none()
- test_extract_hashtags_multiple()
- test_extract_tasks_normal()
- test_extract_tasks_nested()
- test_extract_tasks_completed()
- test_extract_endpoint_apply_false()
- test_extract_endpoint_apply_true()
- test_extract_endpoint_note_not_found()

## Coverage Goal
> 80% for backend/app/services/extract.py
> 80% for backend/app/routers/notes.py
5
Define DocsAgent / 定义DocsAgent
Create .claude/subagents/docs-agent.md

创建.claude/subagents/docs-agent.md
# DocsAgent - Documentation Specialist

You are an expert in writing clear, comprehensive documentation.

## Role
Document the extraction feature for users and developers.

## Responsibilities
1. Update API documentation (OpenAPI spec)
2. Add usage examples (curl, Python, JavaScript)
3. Update README.md
4. Document schema types

## Documentation Sections
1. Feature Overview
2. Endpoint Specification
3. Request/Response Examples
4. Error Codes
5. Use Cases

## Update Locations
- backend/app/routers/notes.py (docstrings)
- README.md (usage section)
- docs/API.md (if exists)

Exercise 4: Execute Multi-Agent Workflow / 练习4:执行多Agent工作流

🔍 ParserAgent
Define & Implement
⚙️ BackendAgent
Create Endpoint
🧪 TestAgent
Verify
📚 DocsAgent
Document
⚡ Workflow Execution / 工作流执行
Sequential Handoffs: Each agent builds on the previous agent's work
Interface Contracts: Agents agree on data structures upfront
Parallel Opportunities: DocsAgent can prepare template while BackendAgent implements

顺序交接:每个Agent建立在之前Agent的工作基础上
接口契约:Agent预先就数据结构达成一致
并行机会:在BackendAgent实现时,DocsAgent可以准备模板

Efficiency Metrics / 效率指标

30x
Test Generation Speed
测试生成速度提升
12x
Error Handling Speed
错误处理速度提升
2-3x
Overall Feature Speed
整体功能开发速度提升
95%+
Test Coverage
测试覆盖率

Before vs After / 之前 vs 之后

Aspect / 方面 Before (Manual) / 之前(手动) After (Multi-Agent) / 之后(多Agent)
Test Writing / 编写测试 30 minutes per endpoint 1 minute (/test-pagination)
Error Handling / 错误处理 Inconsistent across endpoints Standardized (/standardize-errors)
Code Quality / 代码质量 Varies by developer Consistent (rules enforced)
Documentation / 文档 Often incomplete Automatic (DocsAgent)
Feature Time / 功能开发时间 4-6 hours 2-3 hours

Key Takeaways / 关键收获

💾 Consistency / 一致性

Rules ensure consistent code patterns across the entire project.

规则确保整个项目中一致的代码模式。

🔄 Reusability / 可重用性

Commands and rules can be used repeatedly across different projects.

命令和规则可以在不同项目中重复使用。

🤖 Specialization / 专业化

Agents have focused expertise for specific domains, producing higher quality work.

Agent具有特定领域的专业知识,产生更高质量的工作。

⚡ Velocity / 速度

Multi-agent workflows achieve 2-3x productivity improvements over manual development.

多Agent工作流相比手动开发实现2-3倍生产力提升。

Achievements / 成就

  • ✅ Created 5+ slash commands (test-pagination, standardize-errors, etc.)
  • ✅ Defined coding rules (pagination-pattern, error-envelope)
  • ✅ Built 4 specialized SubAgents (Parser, Backend, Test, Docs)
  • ✅ Coordinated multi-agent workflow for extraction feature
  • ✅ Achieved 95%+ test coverage with TestAgent
  • ✅ Reduced feature development time by 2-3x
  • ✅ 创建了5+个斜杠命令(test-pagination、standardize-errors等)
  • ✅ 定义了编码规则(pagination-pattern、error-envelope)
  • ✅ 构建了4个专门SubAgent(Parser、Backend、Test、Docs)
  • ✅ 协调了多Agent工作流用于提取功能
  • ✅ 通过TestAgent实现95%+测试覆盖率
  • ✅ 将功能开发时间减少了2-3倍