How Group Chat Bots Work: A Practical Guide to Building a Knowledge Base Q&A System

    This article explains how group chat bots are implemented and how to turn one into a practical knowledge base Q&A system. It covers a five-layer architecture (access, session, knowledge, generation, and operations), the main request flow from document ingestion to answering an @-mention in a group, connection and message-handling details, question extraction and routing, BM25-based retrieval without a vector database, prompt constraints that reduce hallucination, observability and configuration, deployment scaling, and common pitfalls with an acceptance checklist. Readers will learn how scattered chat knowledge can become searchable, reusable organizational knowledge assets.

    1. The Problem: The Answers Exist, but They Can’t Be Reused

    Internal engineering chat groups and product user groups can scroll through dozens to hundreds of messages every day. A typical frustration: a question was already answered six months ago, yet new hires still ask it again, and experienced colleagues end up copy-pasting the same answer over and over. Operations and support staff spend a large part of their day on high-frequency repeats like “how do I use this feature” and “how do I handle this kind of error.”

    The conclusion is not that “nobody knows the answer.” It’s that answers are scattered in fragments across chat messages: there is no single entry point, no way to search them, no way to accumulate them, and no way to reuse them. General-purpose large language models have strong language understanding and generation abilities, but they don’t know a specific organization’s internal documents, product details, or the conclusions of past discussions. To make a model answer domain-specific questions, you must connect it to a knowledge base that belongs to that organization and automate the “ask-retrieve-generate” pipeline.

    The technical topic of this article is exactly this: how group chat bots are implemented, and how to turn one into a deployable knowledge base Q&A system.

    2. Overall Architecture: Five Layers and One Main Flow

    A usable group chat Q&A bot can be abstracted into five layers:

    1. Access layer: Establish a long-lived connection or callback channel with the instant messaging service, continuously receiving group messages and the group list.
    2. Session layer: Detect “was I @-mentioned,” parse out the question text, and bind the group to a knowledge base.
    3. Knowledge layer: Document upload, parsing, chunking, and building a full-text search index.
    4. Generation layer: Assemble the retrieved fragments and the question into a prompt, and call the LLM to generate an answer.
    5. Operations layer: Status display, logging, configuration management, and failure retries.

    The main flow can be summarized as: document ingestion → @-mention in a group → keyword retrieval recalls the Top-K fragments → the LLM answers based on the fragments → the result is sent back to the group. The entire flow requires no group member to install any client; the interaction entry point is simply an @ in the chat box.

    3. Access Layer: How the Bot “Stays” in the Group

    A group chat bot is essentially a client process that stays online long-term. There are two common implementation approaches: one is to receive events via a callback (Webhook) provided by the official platform, where the server passively receives pushes; the other is to pull new messages on a timer via polling. The former offers better real-time performance and lower resource usage; the latter is simpler to implement and more tolerant of network conditions, making it suitable for running on an ordinary office computer.

    Engineering-wise, four points need attention:

    • Long-connection stability: After a disconnect, use exponential backoff for reconnection to avoid frequent retries being rate-limited by the server.
    • Message deduplication: Both polling and callbacks can deliver duplicates, so use a unique message identifier for idempotent handling.
    • Event filtering: Only process group messages and @ events, and ignore messages sent by the bot itself, to prevent the bot from looping on its own questions and answers.
    • Group list synchronization: After login, actively pull the visible group list as the data source for the “listening scope” configuration.

    4. Session Layer: Accurately Extracting the “Question” from a Message

    The session layer does three things: decide whether to respond, extract the question, and route to the correct knowledge base.

    To decide whether to respond, the simplest and most reliable rule is “must be explicitly @-mentioned.” This both avoids disturbing group members and naturally bounds the invocation scope. When extracting the question, strip the @ prefix, extra whitespace, and forwarded quotes while preserving the original meaning. For routing, you need a “group → knowledge base” mapping table, where different groups can be bound to different document sets—for example, an R&D group bound to technical manuals and a user group bound to a product FAQ.

    Illustrative pseudocode:

    1. def on_message(msg):
    2. if msg.is_self or msg.type != "group_text":
    3. return
    4. if not msg.at_me:
    5. return
    6. question = strip_at_and_space(msg.text)
    7. if not question:
    8. return
    9. kb = group_kb_map.get(msg.group_id)
    10. if kb is None:
    11. return
    12. chunks = kb.search(question, top_k=3)
    13. answer = llm.answer(question, chunks)
    14. reply(msg.group_id, answer)

    5. Knowledge Layer: Retrieval Without a Vector Database

    The goal of the knowledge layer is to turn unstructured documents into a set of searchable fragments. The flow is: upload → parse → clean → chunk → build index.

    For format support, PDF, DOCX, and TXT already cover the vast majority of internal materials. The parsing stage must handle noise such as tables, headers and footers, and line-break hyphenation; for chunking, it’s recommended to split along semantic boundaries (headings, paragraphs, list items), keep chunk length on the order of a few hundred characters, and preserve the source file name and position information so answers can include citations.

    For retrieval, you can use a BM25-style full-text search algorithm. Its advantage is that it needs no vector database and no embedding model, has few dependencies, and is lightweight to deploy, performing reliably on internal corpora with clear keywords like “terminology, model numbers, error codes, and feature names.” If the corpus has large differences in semantic expression, you can add semantic recall on top of this for hybrid retrieval, but that increases dependencies and operational cost, so introduce it only as needed.

    A minimal usable index and retrieval example:

    1. class MiniIndex:
    2. def __init__(self):
    3. self.docs = [] # text chunks
    4. self.tf = [] # term frequency tables
    5. self.avg_len = 0
    6. def add(self, text):
    7. tokens = tokenize(text)
    8. self.docs.append(text)
    9. self.tf.append(Counter(tokens))
    10. def search(self, query, top_k=3):
    11. scores = bm25(self.tf, tokenize(query), self.avg_len)
    12. idx = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
    13. return [self.docs[i] for i in idx[:top_k]]

    6. Generation Layer: Making the Model “Answer Only Based on the Materials”

    The key to the generation layer is not how powerful the model is, but whether the prompt constraints are clear. It’s recommended to explicitly require: answer only based on the provided material fragments; when the material is insufficient, directly state “no relevant content was found in the knowledge base” and suggest adding documents; and cite the sources at the end of the answer. This significantly reduces hallucination and makes answers verifiable.

    For parameters, Top-K determines the number of recalled fragments, and a default of 3 is the balance point between effectiveness and length; too many fragments crowd out the context and introduce noise. On the model side, you can choose between a “fast conversational” type and a “deep reasoning” type: the former responds quickly and costs less, suitable for everyday Q&A; the latter suits complex questions requiring multi-step reasoning. On the calling side, implement timeouts, retries, and rate-limit backoff to avoid blocking the message-processing thread during peak times.

    7. Operations Layer: Observability and Configurability Are Both Essential

    A system that can run long-term must be “visible and adjustable.” The dashboard should show: login status, bot running status, number of documents, number of text chunks, recent call latency, and failure counts. Logs need to cover four stages—message reception, retrieval hits, model calls, and result delivery—so you can pinpoint whether “nothing was retrieved” or “the model didn’t answer well.”

    Recommended configuration items include: the model service address and key, model selection, Top-K, callback listening port, polling interval, and the group whitelist. Key-type information should be stored only in local configuration or environment variables, never written to logs.

    8. Deployment and Scaling: From Single Machine to Team-Level

    At the single-machine stage, an ordinary office computer is enough to run it, with the focus on process supervision and auto-start on boot. At the team-level stage, you can split access and retrieval into separate services, deploy them on a container platform, store original documents in object storage, and replace local file viewing with a log service and monitoring alerts; on the retrieval side, you can persist the index and rebuild it periodically. If you later connect multiple groups and multiple knowledge bases, you should manage “group-base-permission” centrally in a configuration center and apply rate limiting to questions to prevent wasted resources from accidental triggers.

    9. Common Pitfalls and an Acceptance Checklist

    • Loop risk: Be sure to filter out the bot’s own messages.
    • Duplicate replies: Use the message identifier for idempotency.
    • Empty retrieval: First check whether chunking is too fine or terminology is being broken apart by tokenization.
    • Overly long answers: Compress the prompt length and limit the output word count.
    • Privacy boundaries: Define which groups can be listened to and which documents can be ingested, and keep audit logs.

    For acceptance, use three sets of test cases: historical high-frequency questions, questions requiring cross-document integration, and questions not present in the knowledge base. The third type must be able to honestly answer “not found,” which is the core metric for judging the system’s trustworthiness.

    In summary, implementing a group chat bot is not mysterious: the access layer ensures it stays online, the session layer ensures questions are “asked accurately,” the knowledge layer ensures answers are “backed by evidence,” the generation layer ensures answers are “stable,” and the operations layer ensures it “runs for the long term.” Build this pipeline solidly, and the experience scattered across group chats will become searchable, reusable organizational knowledge assets.