Building a WeChat Group Chatbot with RAG: A Practical Guide to Knowledge Base Q&A
This article walks through building a group chat Q&A assistant that answers domain-specific questions using Retrieval-Augmented Generation (RAG). It explains why general-purpose LLMs fail on private business knowledge, then breaks down the full implementation: a five-layer architecture, message ingestion and session handling, @-mention command parsing, document parsing and chunking, a BM25 keyword index that avoids a vector database, prompt design and answer constraints, multi-group knowledge base isolation, and observability. The goal is a low-cost, deployable pipeline that teams can iterate on using real question logs.
1. The Starting Problem: Why the Bot “Doesn’t Understand the Business”
Many teams have run into the same scenario: you @ a Q&A bot in a group chat, but it only returns generic answers. The reason is simple — a general-purpose LLM does not contain your company’s private information. It doesn’t know what your team’s project docs say, doesn’t know the conclusions confirmed in a discussion three weeks ago, and doesn’t know why a certain API field was deprecated. A model’s capability boundary is defined by its training data, and private knowledge is naturally excluded.
So to make a bot answer domain-specific questions, you need to attach a knowledge base that is searchable, updatable, and permission-isolated. This is the core idea of Retrieval-Augmented Generation (RAG): first retrieve relevant snippets from your own material, then pass those snippets to the LLM as context to generate an answer.
This article targets a “in-group knowledge base Q&A assistant” and breaks down the full implementation path: document upload and parsing, chunking and indexing, group message ingestion, @-trigger and reply, group-to-knowledge-base binding, parameter configuration, and runtime monitoring.
2. Overall Architecture: Five Layers
A usable group chatbot system can usually be divided into five layers:
- Access layer: maintains a long connection or callback channel with the IM service, sending and receiving messages;
- Message processing layer: filtering, deduplication, @-command recognition, and session context maintenance;
- Knowledge layer: document parsing, text chunking, and inverted index construction and updates;
- Generation layer: assembling prompts and calling the LLM API to produce answers;
- Operations layer: configuration management, status display, logging, and alerting.
The benefit of layering is that replacing any one layer doesn’t affect the others. For example, switching the retrieval algorithm from keyword search to hybrid retrieval requires no changes to the access layer code.
3. Message Ingestion and Session Keeping
The first step for a group bot is to “log in” and stay online. There are two common engineering approaches: one is the callback (Webhook) mode, where the platform pushes messages to your own service; the other is the polling mode, where the service pulls new messages on a timer. The former has better real-time performance; the latter is simpler to implement and has low requirements on the public network environment. The polling interval is usually made configurable (e.g., 1–5 seconds) to balance real-time performance and resource usage.
The login state is the most fragile part. You need to handle QR code status display, re-login on session expiry, and duplicate message consumption caused by repeated logins. The engineering recommendation is to generate a unique identifier for each message and keep a short-term deduplication cache:
seen = set() # in production, replace with a TTL-based cachedef handle(msg):if msg.id in seen:returnseen.add(msg.id)route(msg)
After the group list is fetched, you need to provide a “listening switch”: only enabled groups enter the processing flow, and messages from other groups are dropped directly. This saves compute and avoids wrong answers.
4. Command Recognition and Context Management
Group chat is a high-noise environment. The trigger condition must be strict: respond only when a message starts with @bot and the group is enabled. To avoid irrelevant answers, three cases must be handled:
- Empty question: nothing after the @, return a usage hint;
- Multi-turn follow-up: keep the most recent few rounds of Q&A as context, truncating beyond the window;
- Concurrent questions: lock or queue per group to prevent context cross-contamination within the same group.
5. Document Parsing and Chunking: The Entry to the Knowledge Base
Supported formats usually cover PDF, DOCX, and TXT. Parsing focuses differ: PDF needs to handle multi-column layouts, headers and footers, and scanned files (scanned files require OCR to extract text); DOCX needs to restore structure by heading levels; TXT needs attention to encoding detection.
The chunking strategy directly determines retrieval quality. It’s recommended to split by semantic structure rather than by a fixed character count:
document -> split into blocks by heading/paragraph -> 300–800 characters per block, 50–100 characters overlap -> record source and position
Blocks that are too large bring more noise and waste context; blocks that are too small are semantically incomplete. Keeping “source filename + section + index” metadata both enables traceable citations and makes subsequent incremental updates and deletions easier.
6. Retrieval Approach: A Keyword Index Without a Vector Database
A key tradeoff in the original is not introducing a vector database, instead using BM25-style keyword retrieval. This choice has clear justification in the Chinese technical documentation scenario: documents contain many proper nouns, error codes, function names, and abbreviations, and this exact-match need is precisely the strength of an inverted index; at the same time, it removes the vectorization service and extra storage components, significantly reducing deployment cost.
The core idea of BM25 is to add inverse document frequency (IDF) and length normalization on top of term frequency (TF), giving higher weight to terms that are “common in this document but rare globally.” In engineering, tokenization quality sets the ceiling, and you need to maintain a custom dictionary that adds product names, abbreviations, and internal terminology.
If semantic generalization requirements increase later, you can adopt hybrid retrieval: keyword recall + vector recall, then fuse with a unified ranking (e.g., weighted sum or a reranking model). This is a smooth evolution and doesn’t require heavy components from the start.
7. The Generation Step: Prompts and Answer Constraints
After retrieving the Top-K (default 3) snippets, assemble the prompt. There are three key constraints:
- Answer only based on the provided material, and clearly say “no relevant record found” when the material is insufficient;
- Mark citation sources in the output so group members can verify;
- Limit answer length and format to avoid flooding the chat.
An illustrative prompt structure:
You are the team knowledge base assistant. Answer only based on the following material; do not fabricate.Material:[1] Source A ...[2] Source B ...Question: {question}Requirement: give the conclusion first, then the basis and source numbers; if there is no relevant content, state directly that nothing was found.
The model side usually offers two capability tiers: a general conversational type and a type with reasoning steps. The former responds fast and costs less, suitable for everyday Q&A; the latter suits multi-condition troubleshooting questions. Making the model name a configurable item makes it easy to switch by scenario and replace later.
8. Multi-Group Isolation and Knowledge Base Binding
Different groups have different knowledge boundaries: the dev group reads API docs, the support group reads the FAQ, and the training group reads operation manuals. So each group should be able to independently bind a document collection, and retrieval should happen only within that collection. In the data model, a three-level “knowledge base — document — text block” structure is recommended, with a group config table recording the mapping between group identifier and knowledge base identifier. Unconfigured groups use the default library or don’t respond.
9. Observability and Operations
After going live, you must be able to see the running state. The dashboard should show at least: account online status, bot running status, document count, text block count, today’s request volume and failure rate. On the logging side, record request ID, hit snippet numbers, elapsed time, and error stack traces, making it easier to locate whether an “inaccurate answer” is a retrieval problem or a generation problem.
The engineering checklist also includes: sensitive config such as keys goes through environment variables or a secret manager, never in plaintext; uploaded files undergo type and size validation; the index supports incremental rebuilds; and high-frequency questions are cached to reduce repeated call costs.
10. Conclusion
The essence of a group bot is a pipeline of “message ingestion — command parsing — knowledge retrieval — model generation — result return.” The difficulty lies not in any single point of technology, but in retrieval quality and engineering details. Getting the pipeline working with a keyword index first, then iterating on chunking strategy and the dictionary based on real question logs, is the lowest-cost and fastest path to results.
