- Published on
Day 49: UI, Monitoring, Evaluation Report
- Authors

- Name
- Trần Mạnh Thắng
- @TranManhThang96
Mục Tiêu
Sau bài này, capstone của bạn cần có bề mặt demo và bằng chứng đo lường:
- UI chat đơn giản gọi
/queryhoặc/chat. - Hiển thị answer, citations, source metadata, latency, token/cost và trace ID.
- Thu feedback thumbs up/down gắn với
trace_id. - Có monitoring/report cho latency, cost, retrieval, citation, error và guardrail.
- Chạy golden evaluation trên pipeline hiện tại.
- Viết
evaluation_report.mdcó metrics, lỗi chính, trade-off và release decision. - Trả lời được: UI/monitoring/eval này dùng production được chưa, còn thiếu gì.
TL;DR
Day 49 biến backend/API của Day 48 thành capstone có thể demo và review. UI không cần phức tạp, nhưng phải cho thấy answer có citation, source nào được dùng, request chậm ở đâu, tốn bao nhiêu token/cost và user có hài lòng không. Evaluation report là bằng chứng rằng RAG system được đo lường nghiêm túc, không chỉ "chat thử thấy đúng".
1. UI Scope Cho Capstone
UI capstone nên chứng minh workflow production, không cần thành full enterprise portal.
Màn hình tối thiểu:
| View | Mục đích |
|---|---|
| Chat | User hỏi đáp với assistant |
| Citations | Xem source/page/section/chunk được dùng |
| Trace detail | Debug latency, token, cost, retrieval |
| Feedback | Thu thumbs up/down và reason |
| Eval summary | Xem metrics từ golden run |
Reviewer cần thấy:
- Câu hỏi đầu vào.
- Câu trả lời cuối cùng.
- Citation có thể đối chiếu.
- Trace ID để debug.
- Latency từng stage.
- Token/cost estimate.
- Kết quả eval gắn với version.
- No-answer/refusal behavior.
Không cần:
- Landing page marketing.
- Auth enterprise đầy đủ.
- UI quá nhiều animation.
- Dashboard realtime phức tạp.
2. Chat UI Contract
Request:
{
"question": "Nhân viên được nghỉ phép năm bao nhiêu ngày?",
"tenant_id": "demo",
"user_id": "reviewer",
"roles": ["employee"],
"conversation_id": "demo-session-001"
}
Response:
{
"answer": "Nhân viên full-time được nghỉ 12 ngày phép năm theo chính sách HR. [S1]",
"citations": [
{
"source_id": "S1",
"doc_id": "hr_policy_001",
"title": "Chính sách nhân sự",
"page": 4,
"section": "Nghỉ phép năm",
"chunk_id": "hr_policy_001:v1:0007",
"score": 0.87
}
],
"trace_id": "trace_20260510_001",
"latency_ms": {
"retrieve": 52,
"rerank": 176,
"generate": 1240,
"total": 1530
},
"usage": {
"input_tokens": 1180,
"output_tokens": 96,
"estimated_cost_usd": 0.0021
}
}
UI nên hiển thị:
- Answer ở khu vực chính.
- Citation cards bên dưới hoặc bên phải.
- Trace ID nhỏ nhưng copy được.
- Latency total và stage breakdown.
- Token/cost estimate.
- Warning nếu answer là fallback/no-answer.
- Feedback controls sau mỗi answer.
- Error state khi index chưa ready, provider timeout hoặc citation invalid.
3. Citation Experience
Citation không phải trang trí. Nó là guardrail chống hallucination và là cơ chế tạo trust.
Mỗi citation nên có:
| Field | Lý do |
|---|---|
source_id | Map với marker [S1] trong answer |
doc_id | Đối chiếu document |
title | User đọc được |
page | Tìm lại trong PDF |
section | Hiểu ngữ cảnh |
chunk_id | Debug retrieval/eval |
score | Debug ranking |
document_version | Audit stale docs |
UI behavior gợi ý:
- Click citation để mở source excerpt.
- Highlight exact chunk text nếu có.
- Nếu citation invalid, UI hiển thị warning thay vì im lặng.
- Nếu no-answer, không hiển thị citation giả.
- Nếu document có version mới, hiển thị
document_version.
4. Feedback Loop
Endpoint:
POST /feedback
Payload:
{
"trace_id": "trace_20260510_001",
"conversation_id": "demo-session-001",
"rating": "down",
"reason": "wrong_source",
"comment": "Câu trả lời đúng nhưng citation không phải policy mới nhất."
}
Reason categories:
helpful.wrong_answer.wrong_source.missing_citation.incomplete.too_slow.no_answer_wrong.policy_violation.
Feedback phải gắn với trace_id. Nếu chỉ lưu thumbs down mà không có trace, bạn không biết fail do retrieval, reranker, prompt hay LLM.
5. Monitoring Metrics
Metrics tối thiểu:
| Nhóm | Metric | Ý nghĩa |
|---|---|---|
| Latency | p50/p95 total latency | UX và capacity |
| Latency | retrieve/rerank/generate latency | Biết chậm ở đâu |
| Cost | input/output tokens | Kiểm soát token budget |
| Cost | cost/request | Ước tính vận hành |
| Retrieval | empty retrieval rate | Indexing/query issue |
| Retrieval | top_k/rerank_top_k/context_top_k | Debug config |
| Citation | citation correctness/failure rate | Chống cite sai |
| Quality | thumbs down rate | User signal |
| Reliability | timeout/error rate | Production health |
| Security | ACL denial/leak count | Data protection |
| Guardrails | refusal/schema/PII rate | Safety monitoring |
Structured log mẫu:
{
"timestamp": "2026-05-10T10:30:00Z",
"trace_id": "trace_20260510_001",
"tenant_id": "demo",
"user_id_hash": "sha256:...",
"question_hash": "sha256:...",
"model": "llm-default",
"embedding_model": "embedding-v1",
"prompt_version": "rag_prompt_v3",
"index_version": "enterprise_docs_v1",
"retrieval": {
"bm25_top_k": 50,
"vector_top_k": 50,
"rerank_top_k": 20,
"context_top_k": 6,
"empty": false
},
"latency_ms": {
"retrieve": 52,
"rerank": 176,
"generate": 1240,
"total": 1530
},
"usage": {
"input_tokens": 1180,
"output_tokens": 96,
"estimated_cost_usd": 0.0021
},
"citation": {
"count": 1,
"valid": true
},
"status": "success"
}
Không log raw question nếu có PII. Dùng hash hoặc redacted text.
6. Dashboard Hoặc Report?
Với capstone, bạn có thể chọn report tĩnh thay vì dashboard phức tạp.
| Option | Ưu điểm | Trade-off | Khi dùng |
|---|---|---|---|
| Markdown report | Nhanh, dễ review trên GitHub | Không realtime | Portfolio |
| JSON/CSV report | Dễ parse và chart | Ít thân thiện | CI artifact |
| Streamlit/Next.js dashboard | Demo tốt | Tốn thời gian UI | Nếu đã có backend ổn |
| Grafana/Prometheus | Production-like | Setup nặng | Khi học observability sâu |
Best solution cho Day 49:
- UI chat tối giản.
- Trace panel trong UI hoặc JSON report.
evaluation_report.mdcommit vào repo.- Metrics summary có chart/table đủ đọc.
7. Evaluation Report
Report cần trả lời:
- Eval chạy trên version nào?
- Có bao nhiêu cases?
- Metrics hiện tại so với threshold thế nào?
- Failures chính thuộc layer nào?
- Release decision là gì?
- Limitations là gì?
Release decision:
| Decision | Khi nào |
|---|---|
PASS | Đạt threshold, không có critical failure |
CONDITIONAL PASS | Có issue nhỏ, có mitigation/canary |
FAIL | ACL/security/citation/format critical fail hoặc quality dưới ngưỡng |
Template ngắn:
# Evaluation Report
Date:
Git SHA:
Eval set version:
Prompt version:
Index version:
Model:
## Summary
| Metric | Current | Threshold | Status |
|---|---:|---:|---|
## Failures By Layer
| Layer | Cases | Example | Fix |
|---|---:|---|---|
## Release Decision
Decision:
Reason:
Mitigation:
8. UI Implementation Notes
Pseudo state model:
type Citation = {
source_id: string;
doc_id: string;
title?: string;
page?: number;
section?: string;
chunk_id: string;
score?: number;
};
type QueryResponse = {
answer: string;
citations: Citation[];
trace_id: string;
latency_ms: Record<string, number>;
usage: {
input_tokens: number;
output_tokens: number;
estimated_cost_usd: number;
};
};
Fetch wrapper:
async function askQuestion(question: string): Promise<QueryResponse> {
const response = await fetch("/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
question,
tenant_id: "demo",
user_id: "reviewer",
roles: ["employee"],
conversation_id: "demo-session-001"
})
});
if (!response.ok) {
throw new Error(`Query failed: ${response.status}`);
}
return response.json();
}
UX states cần có:
- Empty state.
- Loading state.
- Success with citations.
- No-answer/refusal.
- Error with trace ID nếu có.
- Feedback submitted.
9. Performance Và Product Trade-Off
| Quyết định | Lợi ích | Trade-off |
|---|---|---|
| Hiển thị full trace cho reviewer | Debug tốt | Có thể lộ internal info |
| Ẩn raw prompt/output | An toàn | Debug khó hơn |
| Feedback reason bắt buộc | Data tốt | Friction cao |
| Cost hiển thị per request | Minh bạch | Có thể gây nhiễu với end user |
| Eval chart trong UI | Demo tốt | Tốn thời gian |
| Markdown report | Nhanh | Không realtime |
Best solution:
- Portfolio UI: hiển thị answer/citations/trace/latency/cost ở mức reviewer.
- Production UI: ẩn internal trace khỏi end user, chỉ admin/debug role xem.
- Monitoring dashboard: dùng redacted logs và aggregate metrics.
10. Dùng Được Trong Production Không?
Có, nếu UI chỉ là bề mặt trên một backend đã có guardrails, auth, logging và monitoring đúng.
Điều kiện tối thiểu:
- UI không hiển thị dữ liệu ngoài quyền user.
- Citation/source excerpt cũng phải enforce ACL.
- Feedback có trace ID và không lưu PII raw.
- Trace detail chỉ cho admin/support role.
- Monitoring có alert cho error, latency, cost, citation failure, empty retrieval và thumbs down.
- Evaluation report được tạo định kỳ và trước release.
- Có release decision và rollback plan.
Không nên claim production-ready nếu:
- UI chỉ hiển thị answer mà không có citation.
- Không có trace ID.
- Không có feedback loop.
- Không có eval report.
- Monitoring chỉ là log raw không redact.
- Citation panel có thể leak source user không được quyền xem.
Checklist Cuối Bài
- UI gọi được
/query. - Hiển thị answer, citations, trace ID, latency và cost.
- Có feedback thumbs up/down gắn trace.
- Có structured logs đã redact.
- Có metrics summary.
- Có golden eval run mới nhất.
- Có
evaluation_report.md. - Có release decision.
Tài liệu
1. UI Review Checklist
| Item | Required | Evidence |
|---|---|---|
| Chat input | Yes | Can submit Vietnamese question |
| Answer rendering | Yes | Shows grounded answer |
| Citation cards | Yes | doc/page/section/chunk visible |
| Source excerpt | Recommended | Click citation or side panel |
| Trace ID | Yes | Copyable |
| Latency breakdown | Yes | retrieve/rerank/generate/total |
| Token/cost | Yes | usage block |
| Feedback | Yes | rating + reason + trace_id |
| Error state | Yes | timeout/index not ready/citation invalid |
| ACL behavior | Yes | No source leak in citation panel |
2. Feedback Schema
{
"trace_id": "trace_20260510_001",
"conversation_id": "demo-session-001",
"rating": "up|down",
"reason": "helpful|wrong_answer|wrong_source|missing_citation|incomplete|too_slow|no_answer_wrong|policy_violation",
"comment": "optional redacted text"
}
Validation:
trace_idrequired.ratingenum.reasonrequired fordown.commentmax length, redact PII.
3. Monitoring Metrics Catalog
| Metric | Type | Tags |
|---|---|---|
rag_request_count | counter | tenant, status |
rag_total_latency_ms | histogram | tenant, model, prompt_version |
rag_retrieve_latency_ms | histogram | retriever |
rag_rerank_latency_ms | histogram | reranker |
rag_generate_latency_ms | histogram | model |
rag_input_tokens | histogram | model |
rag_output_tokens | histogram | model |
rag_estimated_cost_usd | histogram | model |
rag_empty_retrieval_rate | gauge | index_version |
rag_citation_failure_count | counter | prompt_version |
rag_schema_failure_count | counter | model |
rag_guardrail_refusal_count | counter | reason |
rag_feedback_down_count | counter | reason |
4. Evaluation Report Template
# Evaluation Report
Date:
Author:
Git SHA:
Eval set version:
Corpus version:
Index version:
Prompt version:
LLM model:
Embedding model:
Reranker:
## Executive Summary
Decision: PASS / CONDITIONAL PASS / FAIL
## Metrics
| Metric | Current | Previous | Threshold | Status |
|---|---:|---:|---:|---|
| Recall@5 | | | | |
| MRR@10 | | | | |
| Citation correctness | | | | |
| Format pass rate | | | | |
| No-answer accuracy | | | | |
| Prompt injection block rate | | | | |
| ACL leak count | | | | |
| p95 latency ms | | | | |
| Avg cost/request | | | | |
## Results By Tag
| Tag | Cases | Pass rate | Main issue |
|---|---:|---:|---|
## Failure Analysis
| Case ID | Layer | Expected | Actual | Fix |
|---|---|---|---|---|
## Release Notes
## Risks And Limitations
## Next Actions
5. Release Decision Rules
PASS:
- No ACL/security critical failure.
- Citation correctness đạt threshold.
- Format pass rate đạt threshold.
- No-answer behavior đạt threshold.
- Latency/cost trong budget.
CONDITIONAL PASS:
- Non-critical regression có owner.
- Có canary và rollback.
- Known issue không ảnh hưởng security/data leak.
FAIL:
- Any ACL leak.
- Prompt injection critical case pass-through.
- Citation failure cao.
- Format response làm client hỏng.
- p95 latency/cost vượt xa budget mà không có mitigation.
6. Demo Flow 3 Phút
- Hỏi câu normal về HR policy.
- Click citation, chỉ ra doc/page/section/chunk.
- Mở trace detail, chỉ latency/token/cost.
- Submit feedback
downvới reasonwrong_sourcehoặcup. - Hỏi câu ngoài tài liệu để thấy no-answer.
- Mở evaluation report và release decision.
7. Data Privacy Notes
- Không hiển thị raw logs cho end user.
- Không log raw question nếu có PII.
- Hash
user_idvàquestion. - Redact comment feedback.
- Trace detail cần role admin/support.
- Source excerpt phải qua ACL giống query.
Bài tập
Mục Tiêu
Bạn sẽ tạo UI demo và report chứng minh capstone có thể review:
- Chat UI gọi backend.
- Citation panel.
- Trace/usage panel.
- Feedback form.
- Monitoring summary.
evaluation_report.md.
Bài Tập 1: Chat UI Minimum
Tạo màn hình chat với các state:
- Empty.
- Loading.
- Success.
- No-answer/refusal.
- Error.
Response phải render:
answer.citations.trace_id.latency_ms.total.usage.estimated_cost_usd.
Acceptance criteria:
- Submit câu hỏi tiếng Việt được.
- Disable submit khi loading.
- Error không làm mất câu hỏi cũ.
- Trace ID copy được.
Bài Tập 2: Citation Panel
Mỗi citation card hiển thị:
source_id.titlehoặcdoc_id.page.section.chunk_id.scorenếu có.
Nếu API trả source_excerpt, hiển thị excerpt nhưng không quá dài. Nếu không có excerpt, vẫn hiển thị metadata.
Bài Tập 3: Feedback Form
Payload:
{
"trace_id": "trace_20260510_001",
"conversation_id": "demo-session-001",
"rating": "down",
"reason": "wrong_source",
"comment": "Citation trỏ nhầm tài liệu."
}
Acceptance criteria:
- Không cho gửi feedback nếu thiếu
trace_id. downbắt buộc chọn reason.- Comment giới hạn độ dài.
- Sau khi submit, UI hiển thị trạng thái đã ghi nhận.
Bài Tập 4: Trace Summary
Tạo panel:
| Field | UI |
|---|---|
trace_id | Copyable text |
latency_ms.retrieve | Stage row |
latency_ms.rerank | Stage row |
latency_ms.generate | Stage row |
latency_ms.total | Highlight |
usage.input_tokens | Number |
usage.output_tokens | Number |
usage.estimated_cost_usd | Currency |
Không hiển thị system prompt hoặc raw context cho end user.
Bài Tập 5: Monitoring Summary
Tạo monitoring_summary.md hoặc dashboard page với:
# Monitoring Summary
Period:
Request count:
p50 latency:
p95 latency:
Average cost/request:
Empty retrieval rate:
Citation failure rate:
Schema failure rate:
Thumbs down rate:
Top failure reasons:
Nếu chưa có real traffic, dùng eval run + demo traces và ghi rõ là sample.
Bài Tập 6: Evaluation Report
Tạo evaluation_report.md theo template trong document.md.
Bắt buộc có:
- Date.
- Git SHA hoặc local version.
- Eval set version.
- Prompt version.
- Index version.
- Metrics table.
- Results by tag.
- Top failures.
- Release decision.
- Limitations.
- Next actions.
Bài Tập 7: Release Decision
Chọn một trong ba:
PASS.CONDITIONAL PASS.FAIL.
Viết lý do theo evidence, không viết cảm tính.
Ví dụ:
Decision: CONDITIONAL PASS
Reason:
- Recall@5 đạt 0.86, vượt threshold 0.80.
- Citation correctness đạt 0.96, vượt threshold 0.95.
- Tag `multi-hop` chỉ đạt 0.70, thấp hơn kỳ vọng.
Mitigation:
- Canary chỉ dùng cho HR FAQ.
- Không bật cho legal/finance.
- Cải thiện chunking cho multi-hop trước release tiếp theo.
Checklist Nộp Bài
- UI hỏi đáp chạy được.
- Citation panel hiển thị source metadata.
- Trace/usage panel hiển thị latency/token/cost.
- Feedback gắn với trace ID.
- Có monitoring summary.
- Có evaluation report.
- Có release decision dựa trên metrics.
- Có ghi rõ limitations.