Tai lieu ky thuat - BA Agent System
Kien truc, cau hinh, API va huong dan van hanh he thong
Kien truc he thong
BA Agent System su dung kien truc Multi-Agent, trong do moi agent chuyen xu ly mot giai doan cua quy trinh BA.
High-level Architecture
Browser (index.html)
|
v
Express Server (server.js) ---- Confluence DC (REST API)
|
v
AI Service (AIService.js) ---- Claude API (Anthropic SDK)
|
v
Session Manager (SessionManager.js) ---- JSON File Storage
|
v
Multi-Agent System
├── DiscoveryAgent - Thu thap yeu cau
├── AnalysisAgent - Phan tich va phan loai
├── DocumentationAgent - Tao tai lieu (BRD, URD)
├── UseCaseAgent - Tao Use Cases
├── VisualizationAgent - Tao Diagrams
├── ValidationAgent - Kiem tra chat luong
└── PublishAgent - Tong hop va xuat ban
Document Generation Flow
Cong nghe su dung
| Thanh phan | Cong nghe | Phien ban |
|---|---|---|
| Runtime | Node.js | ES Modules |
| Web Framework | Express | 5.x |
| AI SDK | @anthropic-ai/sdk | 0.52+ |
| AI Models | Claude (Haiku/Sonnet/Opus) | 4.5 |
| Frontend | Vanilla HTML/CSS/JS | - |
| Confluence | Confluence DC REST API | v2 |
| Data Storage | JSON Files | - |
| Auth (Confluence) | Personal Access Token (Bearer) | - |
Cau truc thu muc
ba-agent-system/
├── package.json # Dependencies & scripts
├── .env # Environment variables
├── src/
│ ├── index.js # CLI entry point
│ ├── agents/ # Multi-agent implementations
│ │ ├── BaseAgent.js
│ │ ├── DiscoveryAgent.js
│ │ ├── AnalysisAgent.js
│ │ ├── DocumentationAgent.js
│ │ ├── UseCaseAgent.js
│ │ ├── VisualizationAgent.js
│ │ ├── ValidationAgent.js
│ │ └── PublishAgent.js
│ ├── config/
│ │ └── agents.config.js # Model, prompt, temperature config
│ ├── core/
│ │ ├── Orchestrator.js # Agent coordination
│ │ └── SessionManager.js # Session & artifact storage
│ ├── services/
│ │ ├── AIService.js # Claude API wrapper
│ │ └── ConfluenceService.js # Confluence REST API
│ ├── storage/
│ │ └── sessions/ # JSON session files
│ └── web/
│ ├── server.js # Express server + API routes
│ └── public/
│ ├── index.html # Web UI (SPA)
│ ├── user-guide.html # End-user guide
│ └── tech-guide.html # This document
Yeu cau he thong
- Node.js >= 18.x (su dung ES Modules)
- Anthropic API Key - De su dung Claude AI
- Confluence DC (tuy chon) - Voi Personal Access Token
Cai dat
# Clone repository
git clone <repo-url>
cd ba-agent-system
# Cai dat dependencies
npm install
# Tao file cau hinh
cp .env.example .env
# Chinh sua .env voi API keys cua ban
# Chay web server
npm run web
# Truy cap http://localhost:3000
Cau hinh .env
| Bien | Mo ta | Bat buoc |
|---|---|---|
ANTHROPIC_API_KEY | API key tu Anthropic Console | Co |
CONFLUENCE_BASE_URL | URL goc cua Confluence DC (vd: https://wiki.example.com) | Khong |
CONFLUENCE_API_TOKEN | Personal Access Token cho Confluence | Khong |
PORT | Port web server (mac dinh: 3000) | Khong |
.env len git. File nay chua API keys nhay cam.
Multi-Agent System
He thong gom 7 agent chuyen biet, moi agent xu ly mot giai doan:
| Agent | Chuc nang | Model | Thinking |
|---|---|---|---|
DiscoveryAgent | Hoi dap kham pha yeu cau | Haiku 4.5 (Fast) | Off |
AnalysisAgent | Phan tich & phan loai yeu cau | Sonnet 4.5 (Balanced) | On |
DocumentationAgent | Tao BRD, URD | Sonnet 4.5 / Haiku (edit) | On / Off |
UseCaseAgent | Tao Use Cases | Sonnet 4.5 / Haiku (edit) | On / Off |
VisualizationAgent | Tao diagrams (PlantUML) | Sonnet 4.5 | On |
ValidationAgent | Kiem tra chat luong | Sonnet 4.5 | On |
PublishAgent | Tong hop & xuat ban | Haiku 4.5 (Fast) | Off |
AI Service
File: src/services/AIService.js
AIService la lop wrapper cho Anthropic SDK, cung cap:
- requestStream() - Goi API voi streaming, tra ve finalMessage
- chatStream() - Chat voi agent cu the, ho tro onTextDelta callback
- getStreamForAgent() - Lay stream object cho SSE endpoints
- generateURD() - Tao URD tu BRD + discovery data
- updateURD() - Cap nhat URD dua tren phan hoi
- generateBRD() - Tao BRD tu dong tu discovery
- generateUseCasesFromURD() - Tao Use Cases tu URD
- generateUIFromUseCases() - Tao UI Wireframe
- generateSequenceDiagramsFromUseCases() - Tao Sequence Diagrams
- generateSRS() - Tao SRS tu tat ca artifact
- stripCodeFences() - Loai bo markdown code fences tu output AI
Streaming
Tat ca API calls su dung streaming (messages.stream() + .finalMessage()) de tranh timeout. Cau hinh stream: true trong agents.config.js.
Session Manager
File: src/core/SessionManager.js
Quan ly session (project), features, va artifacts:
- loadSession(id) - Tai session tu file JSON
- getFeature(featureId) - Lay thong tin feature
- storeFeatureArtifact(featureId, key, data) - Luu artifact (brd, urd, usecases, ...)
- storeFeatureConversation(featureId, message) - Luu lich su chat
- updateFeaturePhase(featureId, phase) - Cap nhat giai doan hien tai
Data Structure
{
"id": "session-uuid",
"projectName": "Ten du an",
"features": [{
"id": "feature-uuid",
"name": "Ten tinh nang",
"currentPhase": "discovery",
"artifacts": {
"brd": { "source": { "content": "...", "confluencePageId": "..." } },
"urd": { "content": "...", "version": 1, "confluencePageId": "..." },
"usecases": { "content": "...", "version": 1 },
"ui": { "content": "...", "version": 1 },
"sequence": { "content": "...", "version": 1 },
"srs": { "content": "...", "version": 1 }
},
"conversation": [...]
}]
}
Confluence Service
File: src/services/ConfluenceService.js
Tich hop voi Confluence Data Center qua REST API:
| Method | Chuc nang |
|---|---|
getContent(pageId) | Lay noi dung trang |
updateContent(pageId, spaceKey, title, content, version) | Cap nhat trang |
createPage(spaceKey, parentId, title, content) | Tao trang moi |
searchByTitle(spaceKey, title) | Tim kiem theo ten |
htmlToStorage(html) | Chuyen HTML sang XHTML storage format |
markdownToStorage(md) | Chuyen Markdown sang XHTML |
storageToText(xhtml) | Chuyen XHTML sang plain text |
Authentication
Su dung Bearer token (Personal Access Token):
Authorization: Bearer <CONFLUENCE_API_TOKEN>
Agent Configuration
File: src/config/agents.config.js
Moi agent co cau hinh rieng:
agents: {
discovery: {
model: MODELS.FAST, // Haiku 4.5
maxTokens: 8192,
temperature: 0.7,
enableThinking: false,
},
documentation: {
model: MODELS.BALANCED, // Sonnet 4.5
maxTokens: 64000,
temperature: 0.5,
enableThinking: true,
thinkingBudget: 32000,
edit: { // Override cho che do edit
model: MODELS.FAST, // Haiku cho edit
maxTokens: 64000,
temperature: 0.3,
enableThinking: false,
},
},
// ... (xem chi tiet trong agents.config.js)
}
AI Models
| Constant | Model ID | Su dung cho | Gia (Input/Output per 1M) |
|---|---|---|---|
MODELS.FAST | claude-haiku-4-5 | Chat, edit, don gian | $1 / $5 |
MODELS.BALANCED | claude-sonnet-4-5 | Phan tich, tao tai lieu | $3 / $15 |
MODELS.PREMIUM | claude-opus-4-5 | Task quan trong (chua dung) | $15 / $75 |
System Prompts
Tat ca system prompts duoc dinh nghia trong agents.config.js muc CONFIG.prompts. Tat ca prompt yeu cau output bang tieng Viet.
Cac prompt key: discovery, analysis, documentation, documentationEdit, usecase, usecaseEdit, visualization, validation, publish, urdGeneration, urdUpdate, brdGeneration, discoveryFromBRD.
API Overview
Server chay tren Express 5.x, mac dinh port 3000. Tat ca API tra ve JSON.
Base URL: http://localhost:3000/api
Headers:
Content-Type: application/json
Projects API
| Method | Endpoint | Mo ta |
|---|---|---|
| GET | /api/projects | Danh sach project |
| POST | /api/projects | Tao project moi |
| GET | /api/projects/:id | Chi tiet project |
| PUT | /api/projects/:id/confluence | Cau hinh Confluence |
| DELETE | /api/projects/:id | Xoa project |
Features API
| Method | Endpoint | Mo ta |
|---|---|---|
| GET | /api/projects/:id/features | Danh sach features |
| POST | /api/projects/:id/features | Tao feature (voi BRD tuy chon) |
| GET | /api/projects/:id/features/:fid | Chi tiet feature |
| POST | /api/projects/:id/features/:fid/chat | Chat voi AI agent |
| POST | /api/projects/:id/features/:fid/next-phase | Chuyen giai doan tiep |
| POST | /api/projects/:id/features/:fid/switch-phase | Chuyen den giai doan cu the |
| DELETE | /api/projects/:id/features/:fid | Xoa feature |
Documents API
| Method | Endpoint | Mo ta |
|---|---|---|
| GET | .../:fid/document-status | Trang thai tat ca tai lieu (bao gom confluencePageId) |
| POST | .../:fid/generate-urd | Tao URD |
| POST | .../:fid/generate-usecases | Tao Use Cases |
| POST | .../:fid/generate-ui | Tao UI Wireframe |
| POST | .../:fid/generate-sequence | Tao Sequence Diagrams |
| POST | .../:fid/generate-srs | Tao SRS |
| POST | .../:fid/documents/:docType/publish | Day tai lieu len Confluence |
Publish Endpoint
POST /api/projects/:id/features/:fid/documents/:docType/publish
Trong do :docType la mot trong: brd, urd, usecases, ui, sequence, srs.
// Tao trang moi
{ "createNew": true, "spaceKey": "BA", "parentPageId": "123" }
// Cap nhat trang co san (URL)
{ "confluenceUrl": "https://wiki.example.com/pages/viewpage.action?pageId=456" }
// Cap nhat trang co san (Page ID)
{ "confluencePageId": "456" }
Confluence API
| Method | Endpoint | Mo ta |
|---|---|---|
| GET | /api/confluence/test | Test ket noi Confluence |
| GET | /api/confluence/spaces | Danh sach spaces |
| GET | /api/confluence/content/:pageId | Lay noi dung trang |
| PUT | /api/confluence/content/:pageId | Cap nhat trang |
| POST | /api/confluence/content | Tao trang moi |
| POST | /api/confluence/search | Tim kiem trang |
Lenh chay
| Lenh | Mo ta |
|---|---|
npm run web | Chay web server (production) |
npm run dev:web | Chay web server voi auto-reload |
npm start | Chay CLI mode |
npm run chat | Chay chat mode |
npm test | Chay test |
npm run info | Hien thi thong tin he thong |
Luu tru du lieu
Du lieu duoc luu duoi dang JSON files tai src/storage/sessions/. Moi project la mot file JSON chua tat ca features, artifacts va conversation history.
SessionManager.js.
SSE Streaming
He thong ho tro Server-Sent Events (SSE) cho real-time streaming tu AI:
// Server-side (server.js)
function setupSSE(res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'X-Accel-Buffering': 'no',
});
}
function sendSSE(res, data) {
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
// Cau hinh stream trong agents.config.js
ai: { stream: true }
Cac endpoint ho tro SSE: /chat, /next-phase, /generate-brd, /generate-urd, /urd/chat.
Khi stream=true trong config, server tra ve SSE events voi cac type:
stream_start- Bat dau streamingtext_delta- Moi phan text moi ({"type":"text_delta","text":"..."})message_complete- Hoan thanh, tra ve full response dataerror- Loi xay ra
// Frontend - Xu ly SSE stream
const response = await fetch(url, { method: 'POST', body: JSON.stringify(data) });
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
// Parse SSE lines
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith('data: ')) {
const event = JSON.parse(line.slice(6));
if (event.type === 'text_delta') {
// Append text to UI
} else if (event.type === 'message_complete') {
// Handle complete response
}
}
}
}