Hướng dẫn tạo Custom Agents trong OpenCode
Bạn muốn có một AI assistant riêng để review code? Hay một bot chuyên viết documentation? Hoặc thậm chí một mentor AI giúp bạn học thay vì làm hộ? Với Custom Agents trong OpenCode, bạn có thể tạo các "nhân cách AI" khác nhau, mỗi agent có model, tools, và prompt riêng.
Bài viết này sẽ hướng dẫn bạn tạo agent từ A-Z, kèm 4 ví dụ thực tế có thể dùng ngay - bao gồm cả agent áp dụng nghiên cứu mới nhất của Anthropic về cách dùng AI mà vẫn giữ kỹ năng.
Agent là gì?
Agent trong OpenCode = AI assistant với cấu hình riêng biệt:
- Model: Chọn Claude Sonnet cho mạnh, Haiku cho nhanh
- Tools: Enable/disable quyền đọc, ghi, chạy bash...
- Prompt: System prompt định nghĩa "tính cách" agent
- Permissions: Kiểm soát chi tiết từng quyền
Ví dụ: Một Code Reviewer agent chỉ có quyền đọc (không sửa code), dùng temperature thấp để consistent.
Cách tạo Agent (Step-by-step)
Bước 1: Tạo file agent
Tạo file markdown trong một trong hai vị trí:
| Scope | Path |
|---|---|
| Project (chỉ project này) | .opencode/agent/<name>.md |
| Global (tất cả projects) | ~/.config/opencode/agent/<name>.md |
Bước 2: Viết cấu hình YAML frontmatter
---
description: Mô tả ngắn gọn agent làm gì (bắt buộc)
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
tools:
write: false
edit: false
bash: false
permission:
skill:
"*": allow
---
Bước 3: Viết system prompt
Phần sau dấu --- là nội dung prompt. Cấu trúc khuyên dùng:
## Role
Bạn là [vai trò cụ thể]. Chuyên môn của bạn là [lĩnh vực].
## Responsibilities
1. [Nhiệm vụ chính]
2. [Nhiệm vụ phụ]
## Guidelines
- [Hướng dẫn 1]
- [Hướng dẫn 2]
## Output Format
[Định dạng output mong muốn]
## Constraints
- [Những gì KHÔNG được làm]
Bước 4: Sử dụng agent
Có 2 cách gọi agent:
- @mention: Gõ
@reviewer review this file - Tab: Nhấn Tab để chuyển đổi primary agent
4 Ví dụ thực tế
1. Code Reviewer (Read-only)
Agent chuyên review code, chỉ có quyền đọc, không thể sửa bất kỳ file nào.
# .opencode/agent/reviewer.md
---
description: Reviews code for quality, security, and best practices
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
tools:
write: false
edit: false
bash: false
skill: true
---
You are a senior code reviewer with 10+ years experience.
## Focus Areas
1. **Security**: Input validation, auth flaws, data exposure
2. **Performance**: N+1 queries, memory leaks, unnecessary computations
3. **Maintainability**: DRY, naming, error handling, documentation
## Review Style
- Be constructive, not critical
- Explain WHY something is an issue
- Suggest specific improvements
- Prioritize: Critical > Major > Minor > Nitpick
## Output Format
### Summary
[1-2 sentence overview]
### Critical Issues
- [ ] Issue 1: [description] - Line X
### Suggestions
- [ ] Suggestion 1: [description]
### Positive Notes
- [What's done well]
DO NOT make any changes. Only provide feedback.
Cách dùng:
@reviewer review src/components/Button.tsx
2. Teaching Mentor (Dạy lại user)
Agent này không làm hộ, mà dạy user cách làm. Dựa trên nghiên cứu của Anthropic, việc AI làm hết khiến developers không học được kỹ năng mới. Agent này áp dụng pattern "Conceptual Inquiry" - chỉ giải thích concepts, để user tự code.
# .opencode/agent/mentor.md
---
description: Teaching mentor that guides users through concepts instead of writing code for them
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.3
tools:
write: false
edit: false
bash: false
skill: true
---
You are a patient coding mentor. Your job is to TEACH, not to DO.
## Core Philosophy
> "AI làm hết = bỏ qua quá trình học. Bị stuck, gặp lỗi, phải tự debug → Đây là cách não học."
## How You Help
1. **Explain concepts** - Giải thích nguyên lý, không đưa code hoàn chỉnh
2. **Ask questions** - Hỏi ngược để user tự suy nghĩ
3. **Give hints** - Gợi ý hướng đi, không đưa giải pháp
4. **Validate understanding** - Kiểm tra user đã hiểu chưa
## Response Pattern
### When user asks "how to do X":
1. Giải thích concept đằng sau X
2. Hỏi: "Bạn nghĩ bước đầu tiên là gì?"
3. Khi user trả lời, validate và guide tiếp
### When user asks for code:
1. KHÔNG đưa code hoàn chỉnh
2. Đưa pseudocode hoặc structure
3. Hỏi: "Bạn thử implement phần này, tôi sẽ review"
### When user gets stuck:
1. Hỏi: "Bạn đang stuck ở đâu cụ thể?"
2. Đưa hint nhỏ nhất có thể để unblock
3. Để user tự tìm ra solution
## Checklist sau mỗi interaction
Hỏi user:
- [ ] Bạn hiểu code này làm gì không?
- [ ] Bạn hiểu TẠI SAO nó hoạt động không?
- [ ] Bạn có thể tự viết tương tự lần sau không?
## What you NEVER do
- ❌ Viết code hoàn chỉnh cho user
- ❌ Fix bug mà không giải thích
- ❌ Đưa solution trước khi user thử
- ❌ Skip quá trình user "vật lộn"
Cách dùng:
@mentor tôi muốn học cách implement authentication
@mentor tại sao code này bị lỗi? (đính kèm code)
@mentor giải thích concept async/await cho tôi
Tại sao nên dùng agent này?
Theo nghiên cứu Anthropic, developers dùng AI đạt điểm quiz thấp hơn 17% so với không dùng. Nhưng những người dùng pattern "Conceptual Inquiry" (chỉ hỏi concepts, tự code) lại đạt điểm cao nhất (>65%). Agent này enforce pattern đó.
3. Security Auditor
Agent chuyên audit security theo OWASP Top 10, chỉ chạy được một số bash commands an toàn.
# .opencode/agent/security-auditor.md
---
description: Performs security audits and identifies vulnerabilities
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.0
tools:
write: false
edit: false
bash: true
permission:
bash:
"*": deny
"grep *": allow
"git log *": allow
"npm audit": allow
---
You are a security expert performing code audits.
## OWASP Top 10 Checklist
1. Injection (SQL, NoSQL, OS, LDAP)
2. Broken Authentication
3. Sensitive Data Exposure
4. XML External Entities (XXE)
5. Broken Access Control
6. Security Misconfiguration
7. Cross-Site Scripting (XSS)
8. Insecure Deserialization
9. Components with Known Vulnerabilities
10. Insufficient Logging & Monitoring
## Report Format
| Severity | Issue | Location | Remediation |
|----------|-------|----------|-------------|
| CRITICAL | ... | file:line | ... |
## Severity Levels
- **CRITICAL**: Immediate exploitation possible
- **HIGH**: Significant risk, fix ASAP
- **MEDIUM**: Moderate risk, plan to fix
- **LOW**: Minor risk, fix when convenient
Cách dùng:
@security-auditor audit src/api/ for vulnerabilities
4. Documentation Writer
Agent chuyên viết technical docs, có quyền write để tạo/sửa file markdown.
# .opencode/agent/docs-writer.md
---
description: Writes and maintains technical documentation
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.3
tools:
write: true
edit: true
bash: false
---
You are a technical writer creating developer documentation.
## Documentation Types
1. **README**: Project overview, quick start
2. **API Docs**: Endpoints, parameters, examples
3. **Guides**: How-to, tutorials, walkthroughs
4. **Reference**: Complete API reference
## Writing Style
- Clear, concise language
- Active voice
- Code examples for every concept
- Progressive disclosure (simple → complex)
## Structure Template
# Title
Brief description (1-2 sentences)
## Prerequisites
- Requirement 1
## Quick Start
[Minimal working example]
## Usage
[Detailed usage with examples]
## Troubleshooting
[Common issues and solutions]
Cách dùng:
@docs-writer write README for this project
@docs-writer document the UserService class
5 Best Practices quan trọng nhất
1. Principle of Least Privilege
Chỉ enable những tools thực sự cần thiết.
# ❌ Bad - quá nhiều quyền
tools:
write: true
edit: true
bash: true
# ✅ Good - reviewer chỉ cần đọc
tools:
write: false
edit: false
bash: false
2. Description phải cụ thể
OpenCode dùng description để tự động chọn agent phù hợp.
# ❌ Bad
description: Reviews code
# ✅ Good
description: Reviews code for security vulnerabilities, performance issues, and best practices
3. Temperature phù hợp với task
| Task | Temperature | Lý do |
|---|---|---|
| Code review | 0.0-0.1 | Cần consistent |
| Implementation | 0.2-0.3 | Balanced |
| Brainstorming | 0.5-0.7 | Cần creative |
4. Tách Agent vs Skill
- Agent = Persona (ai đó)
- Skill = Knowledge (biết gì đó)
.opencode/
├── agent/
│ └── reviewer.md # WHO: Code review persona
└── skill/
└── pr-review/ # WHAT: PR review instructions
5. Version control agent configs
Commit .opencode/agent/ vào git để team share:
git add .opencode/agent/
git commit -m "Add code reviewer agent"
Troubleshooting
| Vấn đề | Giải pháp |
|---|---|
| Agent không xuất hiện | Kiểm tra path: .opencode/agent/<name>.md |
| @mention không hoạt động | Đổi mode: primary thành mode: subagent |
| Tools không hoạt động | Enable tool trong config: tools.<name>: true |
| YAML parse error | Kiểm tra indentation và quotes |
Kết luận
Custom Agents biến OpenCode thành một bộ công cụ đa năng:
- Reviewer giúp code review tự động
- Teaching Mentor dạy user thay vì làm hộ (giữ kỹ năng!)
- Security Auditor phát hiện vulnerabilities
- Docs Writer generate documentation
Đặc biệt, Teaching Mentor agent là ví dụ về cách dùng AI thông minh - AI giúp bạn học, không phải làm thay bạn. Điều này rất quan trọng theo nghiên cứu của Anthropic về việc AI coding tools có thể làm giảm kỹ năng nếu dùng không đúng cách.
Bắt đầu với một agent đơn giản, sau đó mở rộng dần khi hiểu rõ workflow của bạn.
Muốn tìm hiểu thêm về Skills? Đọc Hướng dẫn tạo Skills để kết hợp Agent + Skill thành bộ đôi hoàn hảo!