How Group Chat Bots Work: A Practical Guide to Knowledge Base Q&A with RAG

    This article explains how to build a group chat bot backed by a knowledge base. It breaks the system into four layers—access, understanding, retrieval and generation, and governance—and walks through login state maintenance, message polling with exponential backoff, @-mention detection, context completion, document parsing and chunking, BM25 indexing, prompt constraints for trustworthy answers, multi-group permission mapping, observability, and common pitfalls such as stale indexes and over-fragmented chunks. Readers will find working Python snippets and configuration examples they can adapt to their own chat platforms.

    1. The Problem: Scattered Knowledge and Repeated Work

    In most organizations, group chats are both where collaboration happens and where knowledge is first produced. Technical discussion groups generate a large volume of messages every day, product support groups keep repeating similar questions, and operations and support staff spend a lot of time on copy-and-paste replies. The real bottleneck is not that “nobody knows the answer,” but that answers are buried in chat history as fragments, with no structured accumulation, no retrieval entry point, and no reuse mechanism.

    General-purpose large language models have strong language understanding and generation capabilities, but they do not inherently know the product details, project documents, or historical conclusions inside a specific organization. To make a model answer domain-specific questions, you must connect an external knowledge base and inject relevant content into the context through retrieval. This is the basic idea of retrieval-augmented generation (RAG). A group chat bot sits at a natural entry point: users do not need to install a new client, they only need to @ the bot in the group to start a question-and-answer session.

    2. Overall Architecture: A Four-Layer Breakdown

    A usable group chat knowledge base bot can usually be split into four layers:

    1. Access layer: maintains a long connection or polling channel with the instant messaging system, handles login state, message pulling, and event dispatch.
    2. Understanding layer: handles session and user identification, @-mention intent detection, question cleaning, and context completion.
    3. Retrieval and generation layer: handles document parsing, chunking, indexing, recall, reranking, and model generation.
    4. Governance layer: handles group-to-knowledge-base mapping, permissions, rate limiting, logging, monitoring, and auditing.

    The benefit of this layering is separation of concerns: the access layer only deals with protocols and connections, the retrieval layer only deals with corpus and recall, the generation layer only deals with prompts and model calls, and the governance layer constrains all stages horizontally.

    3. Access Layer: Login State, Message Polling, and Event Dispatch

    The first step for a group chat bot is to “enter the conversation space.” Two common patterns are used in engineering: long-connection push and scheduled polling pull. Polling is simple to implement and fault-tolerant, making it suitable for prototypes and small-to-medium scale scenarios; long connections offer better real-time performance but require handling heartbeats, reconnections, and backpressure.

    The core parameter of polling mode is the interval. Too short an interval wastes resources and may trigger risk controls; too long an interval hurts response experience. In practice, it is recommended to use a configurable interval with exponential backoff:

    1. import time
    2. def poll_loop(fetch, handle, base=2.0, cap=60.0):
    3. delay = base
    4. while True:
    5. try:
    6. msgs = fetch()
    7. for m in msgs:
    8. handle(m)
    9. delay = base
    10. except Exception:
    11. time.sleep(delay)
    12. delay = min(delay * 2, cap)

    Maintaining login state requires attention to exception branches such as session expiration, device going offline, and CAPTCHA challenges, and exposing the state to an operations dashboard. Message handling must be idempotent: the same message may be delivered repeatedly after a reconnection, so it is recommended to use “session ID + message ID” as the deduplication key, combined with a local cache or an external key-value store to achieve idempotent consumption.

    4. Understanding Layer: @ Detection, Context, and Intent

    The biggest difference between group chat and direct chat is more noise and faster context switching. The bot needs to answer three questions: is this message directed at me, what is the user really asking, and does it need the preceding context.

    @ detection is relatively straightforward: check whether the bot identifier exists in the message entities. Question cleaning includes removing extra whitespace, emoji, and quote blocks while preserving code snippets and links. For context completion, a “sliding window + topic segmentation” approach is recommended: use the most recent few turns as the window, and reset the window when an obvious topic switch occurs (such as a long time gap or the appearance of new topic words).

    1. [User] This API returns 401, what should I do?
    2. [Bot] Please confirm whether the credentials have expired.
    3. [User] What about after refreshing?

    The second sentence omits the subject, so information from the previous turn needs to be merged into the query to form a standalone, retrievable question. This step has a large impact on recall quality but is often overlooked.

    5. Retrieval Layer: Document Parsing, Chunking, and BM25 Indexing

    Knowledge base quality determines the upper limit of answer quality. The engineering pipeline is: upload document → parse text → clean → chunk → build index → persist to disk.

    Common approaches for handling formats:

    • TXT: read directly, with attention to encoding detection.
    • DOCX: extract by paragraphs and heading levels, preserving structure information.
    • PDF: distinguish text-based from scanned documents; scanned ones require optical character recognition, which is more costly.

    The recommended chunking strategy is “structure first, length as fallback”: first split along natural boundaries such as headings and paragraphs, then split over-long blocks with a fixed-length sliding window while keeping overlap, to avoid semantics being hard-truncated. Each text block should carry metadata: source document, section path, version number, and update time.

    For recall, BM25 is a mature and lightweight solution that achieves decent literal matching without a vector database. Its idea is: higher term frequency means higher relevance, but gains diminish as term frequency grows; the longer the document, the more the matching weight is penalized; rarer terms carry higher weight. A sample implementation:

    1. import math
    2. from collections import Counter
    3. class BM25:
    4. def __init__(self, docs, k1=1.5, b=0.75):
    5. self.docs = docs
    6. self.k1, self.b = k1, b
    7. self.tf = [Counter(d.split()) for d in docs]
    8. self.len = [len(d.split()) for d in docs]
    9. self.avg = sum(self.len) / max(1, len(docs))
    10. df = Counter()
    11. for tf in self.tf:
    12. df.update(tf.keys())
    13. self.idf = {t: math.log(1 + (len(docs) - n + 0.5) / (n + 0.5)) for t, n in df.items()}
    14. def score(self, q, i):
    15. s, tf, dl = 0.0, self.tf[i], self.len[i]
    16. for t in q.split():
    17. if t not in tf:
    18. continue
    19. f = tf[t]
    20. s += self.idf.get(t, 0) * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * dl / self.avg))
    21. return s

    Engineering considerations also include: Chinese text needs word segmentation first; synonyms and abbreviations affect recall, so a domain glossary can be maintained; building section-level indexes for very long documents can significantly improve location accuracy.

    6. Generation Layer: Prompt Constraints and Trustworthy Answers

    Once candidate blocks are retrieved, do not stuff all content into the model. The recommended flow is: recall TopN → lightweight rerank → truncate to the context budget → assemble the prompt → call the model → post-process.

    The prompt should make four things explicit: answer only based on the given material; clearly say you do not know when the material is insufficient; provide citation sources; control output length and format. Example:

    1. You are an enterprise knowledge base assistant. Answer only based on the [Material]; when the material is insufficient, reply "No supporting evidence was found in the knowledge base."
    2. Output: conclusion + evidence summary + source title.
    3. [Material] {{chunks}}
    4. [Question] {{question}}

    Post-processing includes sensitive information filtering, backfilling links and document names, and truncating overly long answers. If the business has high requirements for timeliness and accuracy, a “citation check” can be added: verify whether key entities in the answer appear in the recalled blocks, and if not, downgrade to prompting the user to supply more material.

    7. Governance Layer: Multi-Group Mapping, Permissions, and Observability

    A real deployment must answer “who can ask, which base they ask, and how many times they have asked.” It is recommended to configure a knowledge base ID per group, so different groups match different document sets; set visibility scope for documents to avoid unauthorized retrieval; set frequency limits per group and per user to prevent message flooding and resource abuse.

    Observability should cover at least: login status, bot running status, number of documents, number of text blocks, recent errors, call latency, and failure rate. Logs should be structured output for easy search and alerting:

    1. {"ts":"2025-01-01T10:00:00Z","group":"A","user":"u1","qlen":18,"hit":3,"ms":820,"ok":true}

    Model-side configuration (such as model name, keys, and polling interval) should be managed through a configuration center or environment variables to avoid hardcoding; keys must be masked when displayed and only allowed to be overwritten.

    8. Common Pitfalls and Optimization Directions

    • Indexing without updating: the index is not rebuilt after documents change, causing outdated answers. It is recommended to rebuild incrementally by version number.
    • Chunks too small or too large: small chunks lose context, large chunks dilute relevance. It is recommended to use 300–800 characters with overlap.
    • Ignoring multi-turn: questions with omitted subjects fail recall. Do query rewriting before retrieval.
    • No fallback phrasing: the model fabricates answers. Enforce “no evidence, no answer.”
    • Lack of canary release: a new prompt goes live for everyone at once. It is recommended to roll out by group and compare hit rate with human feedback.

    9. Conclusion

    The essence of a group chat bot is to do four things solidly: entry, retrieval, generation, and governance. The access layer ensures stable reach, the understanding layer ensures questions are retrievable, the retrieval layer ensures evidence is traceable, and the governance layer ensures the system is controllable. To further reduce operations costs, you can leverage general cloud capabilities, such as object storage for documents, message queues for peak shaving, container platforms for hosting services, and logging and monitoring alerting systems for stability. Following the structure above, a reusable in-group intelligent Q&A system can continuously deliver value in real business scenarios.