Skip to content
From Docs to Live Data: Inside the DBA Digital Human's Hybrid RAG-Agent Architecture
Operations 19 min read

From Docs to Live Data: Inside the DBA Digital Human's Hybrid RAG-Agent Architecture

The article details the architecture of a DBA Digital Human that combines a RAG knowledge engine for documentation queries with a DBAgent for real-time database diagnostics, routed via a WeCom bot with identity-based access control, SQLite audit logging, and strict read-only safety boundaries.

Xiaolei Talks DB
Xiaolei Talks DB
Xiaolei Talks DB

The team built a DBA Digital Human — an intelligent assistant plus Q&A service for DBAs and developers — accessible through a single Enterprise WeChat (WeCom) bot. The system addresses two recurring question types: knowledge questions (e.g., "How to investigate MySQL slow queries?") answered from existing docs, and on-site questions (e.g., "Is this cluster healthy right now?") requiring live data from monitoring, logging, and operations platforms.

Why a Hybrid Architecture?

A pure RAG knowledge base becomes a chatbot that cannot see the live environment. A pure tool-calling Agent turns every simple question into a costly real-time task and lacks a stable, traceable knowledge foundation. The solution splits capabilities: RAG handles concepts, standards, SOPs, and best practices; DBAgent handles real-time status, metrics, logs, and targeted queries. Both share the same WeCom entry, user identity, security policies, session state, audit trail, and response channel.

Overall Architecture

The system comprises five layers:

WeCom: Unified interaction entry. The bot uses a long-lived WSS connection to WeCom's API, avoiding public callback exposure. WeCom controls which members may use the bot; the bot sends progress messages to reduce wait anxiety.

dba-bot (orchestration gateway): Parses messages, deduplicates via event_id, resolves canonical user IDs, enforces read-only policy (blocks injection, explicit execution requests, non-query intents), and routes between RAG and DBAgent while maintaining separate session contexts for each.

dba-rag (knowledge engine): FastAPI /chat endpoint. Executes embedding, vector + full-text search in MongoDB, applies is_active, access_level, and database-type filters, fuses rankings with RRF, injects safety rules, and generates answers with an internal LLM. Returns answer, Skill references, chapter sources, and conversation ID. DBA role accesses full knowledge (including ops details); developer role accesses only shared content.

DBAgent (real-time engine): Built on Deep Agents and LangGraph. Communicates via A2A JSON-RPC SendStreamingMessage over SSE. Dynamically selects DBA Skills, reads full Skill descriptions, and calls tools: Welkin for instance topology, capacity, slow queries, change records; OCP for OceanBase clusters, tenants, monitoring; Kibana/BDS for logs and alerts; Redis-specific tools for cluster status. Receives real user identity and constrained tool capabilities — not an open database channel. Current WeCom path is read-only and diagnostic; changes require separate approval, confirmation, and audit loops.

SQLite (state & audit): Stores events (dedup, status, policy decisions), wecom_identities (raw WeCom ID → canonical userid cache), threads (per-session hybrid backend context), and audits (identity, policy, reply, errors). Also records stage latencies: identity resolution, policy check, routing, A2A first packet, first answer, task completion, WeCom reply — to pinpoint bottlenecks.

Identity Resolution & Role Mapping

WeCom messages may carry encrypted openuserid or plain userid. dba-bot checks a local cache; on miss, calls WeCom's official API to obtain a stable canonical userid and display name. The raw WeCom ID is used for event audit and entry-session isolation. The canonical userid is passed downstream via header X-Zhihu-User. Users on the DBA list receive the dba RAG scope; others receive developer. Group-chat context is isolated by "group + sender" to prevent privilege leakage. Critically, RAG scope only controls retrieval range — it does not replace downstream platform authorization.

Hybrid Routing: One Entry, Two Capabilities

The router selects backend based on query semantics:

Concepts, principles, standards, SOPs, best practices, risk explanations → RAG.

Real-time keywords ("current", "online", "last hour") or specific cluster/instance/tenant targets → DBAgent.

Short follow-ups ("What about the last hour?") default to previous backend.

Explicit commands /知识 (knowledge) and /查询 (query) let users force a path.

Default fallback is RAG to avoid accidental real-time tool invocation. RAG and DBAgent contexts are stored separately; switching backends never misapplies one side's session ID to the other.

End-to-End Request Flow (11 Steps)

Example: Developer asks in a group: "Query slow SQL for example-cluster in the last hour."

WeCom receives message via authenticated long connection; bot extracts message ID, bot ID, chat type, group ID, sender, text.

Event dedup & session isolation : write event_id; ignore duplicate pushes. 1:1 chats keyed by user; group chats keyed by "bot + group + sender".

Verify real identity : lookup cache, else call WeCom API. If identity unresolved, request stops — no RAG or DBAgent call.

Enforce read-only policy : check empty message, prompt injection, explicit execution intent, non-database requests. "What are scaling risks?" proceeds; "Scale cluster now" is blocked with human-DBA referral.

Send progress message & restore context : reply "Analyzing and selecting data service"; load hybrid session state (RAG conversation ID, A2A context/task, last route).

Determine role : canonical userid in DBA list → RAG uses dba scope; else developer. Real X-Zhihu-User always passed downstream.

Route to RAG or DBAgent : example contains "online", "last hour", "slow SQL", specific cluster → DBAgent. "Common causes of slow queries" → RAG. Ambiguous cases use explicit commands.

Execute backend task : RAG calls /chat (role filter, hybrid retrieval, RRF fusion, answer generation). DBAgent sends A2A streaming request with Bearer token, real user identity, session context; selects slow-query Skill, invokes log/ops-platform tools per Skill constraints, streams results via SSE.

Persist new session state : RAG returns new conversation_id; A2A returns new context/task. Saved separately. Identity or role change resets old context to prevent cross-user/privilege reuse.

Format & reply to WeCom : final answer sanitized (sensitive data masked, length limited), sent as Markdown. RAG replies include deduplicated Skill and chapter sources for verification.

Audit & latency logging : event status → replied; record policy decision, session IDs, reply bytes, per-stage timings. Backend failures return a unified safe error while preserving error type and audit record — no speculative retries.

Why Not a Single Agent?

Dual-engine design matches each question type to its optimal execution path. RAG excels at stable, fast, sourced answers for standards and experience reuse. DBAgent excels at understanding tasks, selecting Skills, calling tools, and observing results for live diagnostics. A single Agent would add planning and tool-call overhead to simple queries, increasing latency; a single RAG could not answer "What's happening now?" The hybrid architecture separates "knowledge" from "action capability" while unifying identity, security, and UX in dba-bot.

Security Boundaries

Eight defense layers:

WeCom platform controls bot-eligible members.

dba-bot parses and verifies real user identity.

Group chat and backend contexts isolated per user.

RAG applies shared / dba_only permission filters at retrieval.

Current WeCom entry enforces read-only policy; explicit execution requests never reach backend.

DBAgent always receives real user identity; downstream platforms enforce their own authorization.

Service addresses restricted by host allowlist; credentials stored in protected environment.

dba-bot retains identity, policy, result, and timing records; DBAgent tool calls traced via its observability pipeline.

Core principle: Roles, prompts, Skills, and Agent frameworks cannot replace backend authorization. Even if automated changes are enabled later, they must pass permission checks, parameter constraints, approval, secondary confirmation, rate limiting, and audit at the tool gateway and target platform.

Current Progress & Next Steps

Closed loop achieved: WeCom → dba-bot → RAG / A2A → DBAgent → WeCom reply. Completed: real WeCom identity resolution, DBA/developer knowledge isolation, hybrid routing, dual-backend sessions, streaming A2A, source attribution, per-node latency stats.

Next phase priorities:

Build a real-question benchmark to continuously evaluate routing accuracy, RAG recall, and answer adoption rate.

Add confidence-based semantic routing on top of deterministic rules, keeping /知识 and /查询 as fallbacks.

Stream DBAgent intermediate results earlier to reduce perceived wait time.

Migrate single-node SQLite state to shared storage for multi-instance deployment.

Complete trusted identity authentication for RAG service.

Implement approval, secondary confirmation, rollback, and full audit for high-risk tools before gradually exploring controlled execution.

Closing Thoughts

The DBA Digital Human's value is not replacing DBAs with a bot avatar, nor letting an LLM make all decisions. It transforms database support workflows: common questions self-served via knowledge bot; live information fetched by Agent under authorization; complex judgments return to human DBAs. Every response carries identity, boundaries, sources, context, and audit. When the knowledge base owns "what to know", DBAgent owns "what's happening now", and dba-bot owns "who may ask, who should handle it, and how to answer safely", the DBA Digital Human evolves from a chat demo into a true daily database intelligent assistant.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

RAGdatabase operationsHybrid RoutingLangGraphDBA Digital HumanRead-Only PolicySQLite AuditWeCom Bot
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.