How to Build a WeChat Group Chatbot with a Knowledge Base: Architecture and Implementation

    This article explains how to build a knowledge-base assistant that can be mentioned in a WeChat group. It covers a four-layer architecture (access, orchestration, knowledge, and generation), login-state handling and message callbacks, trigger detection, keyword retrieval with BM25 instead of a vector database, prompt constraints for trustworthy answers, multi-group isolation, and engineering practices for security, cost, and operations. Readers will find code snippets, a scoring formula, and a practical rollout checklist. To avoid tying the design to specific products, third-party capabilities are described in neutral terms.

    1. The Starting Problem: Why a General Model Cannot Answer “Internal” Questions

    A large language model’s general capability comes from public corpora. It does not know a particular team’s product details or internal project documents, and it will not automatically remember a conclusion a group reached last week. Connecting the model directly to a group usually produces text that reads fluently but is factually wrong. To solve domain-specific question answering, the model must receive trusted context before it answers—and that is the reason a knowledge base exists.

    This article discusses how to build a “knowledge-base assistant that can be @-mentioned” in a WeChat group. To avoid coupling the design to any specific product, third-party capabilities are described in neutral terms throughout, such as “a large model service” or “an instant messaging protocol implementation.”

    2. Overall Architecture: Four Layers with Separated Responsibilities

    A usable group chatbot typically consists of four layers, decoupled from one another through explicit data contracts.

    1. Access layer: maintains a long connection or session with the WeChat side, sends and receives messages, and keeps the login state alive.
    2. Orchestration layer: handles message filtering, trigger-word recognition, conversation context management, rate limiting, and deduplication.
    3. Knowledge layer: handles document parsing, chunking, index construction, and retrieval.
    4. Generation layer: assembles prompts, calls the model, post-processes output, and formats replies.

    A schematic layout and call flow:

    1. group message -> access layer (login state/callback) -> orchestration layer (filtering/@ detection/rate limiting)
    2. |-- knowledge layer (parse -> chunk -> index -> retrieve)
    3. |-- generation layer (prompt -> model -> post-processing)
    4. -> write reply into the group conversation

    3. Access Layer: Login State, Message Callbacks, and Stability

    The WeChat personal account side offers no official third-party group chatbot interface. A common approach is to reuse a desktop protocol implementation, establish the login state by scanning a QR code, and then push messages to a local service via callbacks. Three points need engineering attention:

    • Login state expires easily: implement QR-code re-login, reconnection after disconnects, and heartbeat detection, and expose the state to monitoring.
    • Message formats vary: text, images, files, quoted replies, and system notices (such as joining the group or recalling a message) must be handled by category; only text and parseable files enter the Q&A pipeline.
    • Idempotent processing: the same message may be pushed repeatedly after a reconnect, so deduplicate by a unique message identifier to avoid answering twice.

    If WeCom (Enterprise WeChat) is used instead, official apps and a callback mechanism are available, and the integration is more standardized. The orchestration and knowledge layer designs in this article apply equally.

    4. Orchestration Layer: Deciding Whether a Message Is Aimed at the Bot

    Trigger detection should use an “explicit @ plus optional prefix” strategy to avoid flooding the group with unintended answers.

    1. def should_answer(msg, robot_name, cfg):
    2. if msg.type != "text":
    3. return False
    4. if msg.is_system or msg.sender == robot_name:
    5. return False
    6. if not cfg.group_enabled(msg.group_id):
    7. return False
    8. text = msg.text.strip()
    9. if robot_name not in text:
    10. return False
    11. question = text.replace(robot_name, "", 1).strip()
    12. return len(question) >= cfg.min_question_len

    Beyond trigger detection, the orchestration layer also handles:

    • Group-level configuration: which groups are enabled, which knowledge domain each group is bound to, and the maximum context length per Q&A turn.
    • Rate limiting and quotas: token-bucket limiting per group and per user, so frequent @-mentions do not overwhelm downstream model calls.
    • Conversation context: keep only the most recent few turns and truncate beyond that window, controlling prompt size and cost.

    5. Knowledge Layer: Retrieval Without a Vector Database

    One valuable judgment in the original approach is that internal document Q&A relies mainly on exact term matching, and keyword retrieval is often more stable and cheaper than semantic retrieval. Here a classic ranking function such as BM25 is used, together with Chinese word segmentation and a stop-word list, to complete recall.

    The processing pipeline is as follows:

    1. Parsing: extract PDF, DOCX, and TXT into plain text, preserving locating information such as heading hierarchy and page numbers.
    2. Cleaning: remove headers and footers, repeated whitespace, and garbled characters, and fix words broken by line wraps.
    3. Chunking: split at semantic boundaries, with 300–600 characters recommended per chunk and 10%–20% overlap between chunks, so answers are not cut off.
    4. Indexing: after segmentation, build an inverted index and record term frequency and document length for scoring.
    5. Retrieval: segment the question, take the top-K chunks, deduplicate and normalize by length, and assemble them into the prompt.

    The core scoring idea of BM25 can be simplified as:

    1. score(q, d) = Σ idf(t) * ( tf(t,d) * (k1+1) ) /
    2. ( tf(t,d) + k1*(1 - b + b*|d|/avgdl) )

    Here idf measures how rare a term is, tf is the number of times the term appears in the chunk, |d| is the chunk length, avgdl is the average chunk length, and k1 and b are tuning parameters. Its advantages are that it requires no training and no GPU, and incremental updates are cheap—rebuilding the index after a document change takes only seconds.

    Practical advice: maintain a separate index for each knowledge domain, and support a “document version number + effective time” scheme, making it easy to trace which version of the material a given answer was based on.

    6. Generation Layer: Prompt Constraints and Trustworthy Answers

    After retrieval, the prompt should require the model to “answer only from the given material” and to cite sources.

    1. You are an enterprise internal knowledge-base assistant.
    2. Answer only using the content in [Sources]; if the material is insufficient, state clearly that "no relevant record was found."
    3. Keep answers concise, and mark the cited chunk numbers at the end.
    4. [Sources]
    5. [1] ...
    6. [2] ...
    7. [Question] {question}

    Further steps to improve trustworthiness:

    • Citation echo: paste the matched document names and sections back into the group message so members can verify them.
    • Refusal policy: when similarity or the BM25 score falls below a threshold, refuse to answer instead of letting the model improvise.
    • Sensitive-content filtering: detect prompt injection on the input (such as “ignore the instructions above”), and enforce compliance and length limits on the output.
    • Model routing: send simple factual queries to a lightweight model and reasoning-heavy queries to a reasoning model, balancing latency and cost.

    7. Multi-Group Isolation and Knowledge Domain Design

    Different groups care about different document sets, so a “group -> knowledge domain” mapping table is needed. The recommended approach is logical isolation rather than physical duplication: one index service distinguishes knowledge domains by namespace, and retrieval must carry the current group’s namespace parameter, preventing unauthorized recall.

    1. -- Bind groups to knowledge domains
    2. group_binding(group_id PK, kb_namespace, enabled, max_topk, updated_at)
    3. -- Document metadata
    4. document(doc_id PK, kb_namespace, filename, version, chunks, status)

    8. Engineering Essentials: Security, Cost, and Operations

    • Credential management: model service keys and login-state data must be stored encrypted and must never be committed to a code repository.
    • Cost control: cache results for frequent questions, and reuse the answer directly for identical questions within a short window.
    • Observability: log the question, matched chunks, latency, and token usage, and configure a logging service with monitoring and alerting.
    • Graceful degradation: when the model is unavailable, return the retrieved source snippets to guarantee a “partial answer with evidence.”
    • Compliance: confirm the authorization scope before uploading internal material, and keep personal privacy and non-public information out of group replies.

    9. Implementation Checklist

    1. Define knowledge domain boundaries and the first batch of document sources; 2. Get message access working and keep the login state alive; 3. Implement parsing, chunking, and the BM25 index; 4. Write the constrained prompt and refusal logic; 5. Add group-level configuration, rate limiting, and caching; 6. Connect logging, monitoring, and alerting; 7. Run a small-scale canary release, and keep adding documents and tuning parameters based on real questions.

    Following this path, an assistant that lets you “@ it in the group to look up internal material” can run stably. Its core competitiveness lies not in the model itself, but in the product of three factors: the quality of knowledge organization, retrieval accuracy, and engineering reliability.