Building a Practical Chatbot with a Message Gateway and Large Language Models

    This article provides a practical guide to integrating a large language model (LLM) into existing chat platforms. It outlines a three-layer architecture that separates chat platform connectivity, event normalization, and core business logic to ensure stability and maintainability. The guide covers key aspects such as containerized deployment, model API encapsulation, session management, plugin-based extensibility, and essential security considerations, offering a blueprint for developing production-ready LLM-powered chatbots.

    Why Integrate a Large Language Model into a Chat Platform

    The capabilities of large language models are typically accessed through API calls. However, most users interact within messaging apps, group chats, or internal collaboration tools, rather than in an API console. A common challenge for teams is creating a stable, controllable connection between existing chat channels and a large language model.

    This challenge can be broken down into three parts:

    1. Message Source: The methods for account login, message sending/receiving, and group management are determined by the chat platform’s access interface.
    2. Message Processing: Received text requires filtering, context assembly, model invocation, and result formatting.
    3. Extensibility: When adding new commands, knowledge base retrieval, or content moderation, the system should support new functionalities without rewriting its core logic.

    Addressing these three aspects separately results in a system that is easier to maintain than a single, monolithic script. The architecture discussed below is built around this principle.

    Overall Architecture: A Three-Layer Design

    A functional chatbot typically consists of an access layer, a protocol bridging layer, and a business logic layer. Each layer has a distinct responsibility and communicates with others through pre-defined data structures.

    The Access Layer

    The access layer establishes the connection with the chat platform. Methods for integration can vary significantly between platforms; some offer official bot APIs, while others may only permit interaction through client or web protocols. The responsibilities of this layer include:

    • Maintaining the connection and handling heartbeats, with automatic reconnection after a disconnect.
    • Receiving raw events and logging them.
    • Converting message-sending requests into the format required by the target platform.

    This layer is often the most prone to issues due to changes in platform policies, protocol versions, or network conditions. Therefore, it is recommended to build it as an independent service, allowing it to be restarted or upgraded separately without affecting the business logic layer.

    The Protocol Bridging Layer

    Event structures differ across platforms. If business logic were to parse each format directly, the codebase would quickly become complex. The role of the protocol bridging layer is to translate events from various platforms into a unified internal model, for example:

    1. {
    2. "channel": "group",
    3. "channel_id": "123456",
    4. "sender_id": "u_8848",
    5. "text": "Please summarize today's meeting notes",
    6. "mentioned_bot": true,
    7. "timestamp": 1764000000
    8. }

    This unified model offers two main benefits. First, business code only needs to handle a single structure, and adding a new platform simply requires creating a new adapter. Second, logging, auditing, and rate limiting can be implemented based on the unified fields without needing custom rules for each platform.

    The Business Logic Layer

    The business logic layer is the core of the chatbot and typically contains the following modules:

    • Trigger Judgement: Responds directly to private messages and only replies in group chats when mentioned or when a command matches, preventing spam.
    • Session Management: Maintains conversation history by user or group, setting a maximum limit to prevent unbounded context growth.
    • Model Invocation: Encapsulates request parameters, timeout handling, and retry logic uniformly.
    • Plugin Scheduling: Dispatches requests to appropriate functional modules based on commands or keywords.

    Pre-Deployment Checklist

    Environment Requirements

    Before deployment, ensure the following are in place:

    • A server or local host that can run continuously; at least 2 CPU cores and 2 GB of RAM are recommended.
    • A container engine is installed, and its version supports the chosen images.
    • Network access to the model’s API endpoint.
    • A valid API key for the large language model.

    Accounts and Compliance

    When integrating with a chat platform, review the platform’s developer terms of service first. Some platforms prohibit the use of unofficial client protocols, and violations can lead to account restrictions. For enterprise use cases, prioritizing the platform’s official bot integration method and restricting account permissions to the minimum necessary is considered best practice.

    Choosing a Model Service

    Most domestic and international large model services offer APIs similar to the standard chat completion format. For example, when using an LLM service like Baidu AI Cloud, it is necessary to confirm the API endpoint, authentication method, and model name, always referring to the official documentation for the most accurate details. If the API format differs, adaptation should occur within the invocation layer, not by modifying business logic.

    Containerized Deployment

    Containerization ensures a reproducible environment. The access service and the core bot application run in separate containers, communicating over an internal network, with only necessary ports exposed externally. Below is a generic orchestration example (replace the image names with your actual images):

    1. services:
    2. gateway:
    3. image: <message-access-service-image>
    4. restart: unless-stopped
    5. volumes:
    6. - ./gateway/data:/data
    7. networks:
    8. - botnet
    9. bot-core:
    10. image: <bot-core-image>
    11. restart: unless-stopped
    12. env_file:
    13. - .env
    14. depends_on:
    15. - gateway
    16. networks:
    17. - botnet
    18. networks:
    19. botnet: {}

    The startup process is as follows:

    1. Create a .env file in the project directory with the model service URL and API key.
    2. Run the container orchestrator command to start all services in the background.
    3. Verify in the logs that the access service is logged in and the core service is connected to the gateway.

    It is recommended to add the .env file to the version control ignore list to prevent key leakage.

    Integrating the Model: A Call Encapsulation Example

    The business logic layer uses a unified function to call the model. The following Python example reads configuration from environment variables and handles timeouts and errors:

    1. import os
    2. import httpx
    3. LLM_BASE_URL = os.environ["LLM_BASE_URL"]
    4. LLM_API_KEY = os.environ["LLM_API_KEY"]
    5. LLM_MODEL = os.environ.get("LLM_MODEL", "your-model-name")
    6. def ask_llm(history: list[dict], user_text: str, timeout: float = 30.0) -> str:
    7. messages = history + [{"role": "user", "content": user_text}]
    8. headers = {"Authorization": f"Bearer {LLM_API_KEY}"}
    9. payload = {"model": LLM_MODEL, "messages": messages}
    10. with httpx.Client(timeout=timeout) as client:
    11. resp = client.post(
    12. f"{LLM_BASE_URL}/chat/completions",
    13. json=payload,
    14. headers=headers,
    15. )
    16. resp.raise_for_status()
    17. data = resp.json()
    18. return data["choices"][0]["message"]["content"]

    There are three key points in this code:

    • API keys are read only from environment variables, never hardcoded.
    • A timeout is mandatory; otherwise, a slow model response could occupy worker threads indefinitely.
    • On failure, an exception should be raised, allowing the upper layer to decide whether to retry, provide a fallback response, or prompt the user to try again later.

    Message Processing Flow and Context Management

    From message ingress to reply, a message typically goes through the following steps:

    1. The access layer receives the event and converts it into the unified model.
    2. The trigger judgement module checks if a response is needed.
    3. The session module retrieves the history for the user or group.
    4. The plugin scheduler determines if a command is matched.
    5. If no command is matched, the model is called to generate a reply.
    6. The reply and current conversation turn are saved to history, and the reply is sent back through the access layer.

    Trigger Judgement

    Responding to every message in a group chat can be noisy and costly. A common practice is to respond only to messages that contain a specific mention, a command prefix, or a defined trigger. Here is an example of a trigger judgement function:

    1. def should_respond(event: dict, bot_prefix: str = "/ai") -> bool:
    2. if event["channel"] == "private":
    3. return True
    4. if event.get("mentioned_bot"):
    5. return True
    6. return event["text"].startswith(bot_prefix)

    Context Truncation

    The longer the conversation history, the higher the token usage and latency for each request. A common approach is to retain only the most recent turns. If the history exceeds a limit, an LLM can be used to summarize older parts and use that summary instead. The truncation policy should be configured in settings, not hardcoded.

    1. MAX_TURNS = 10
    2. def trim_history(history: list[dict]) -> list[dict]:
    3. max_messages = MAX_TURNS * 2
    4. return history[-max_messages:] if len(history) > max_messages else history

    Plugin-Based Extensibility

    As feature requirements grow (e.g., weather queries, document retrieval, scheduled reminders, content moderation), adding each feature to the main flow increases maintenance burden. A plugin-based design addresses this by defining a unified interface.

    A minimal plugin interface consists of three parts:

    • Name and Trigger Command: Used to match user intent.
    • Handler Function: Accepts the unified model object and returns a string or null.
    • Priority: Determines execution order when multiple plugins are triggered.
    1. PLUGINS = {}
    2. def register(command: str):
    3. def decorator(func):
    4. PLUGINS[command] = func
    5. return func
    6. return decorator
    7. @register("/time")
    8. def cmd_time(event: dict) -> str:
    9. from datetime import datetime
    10. return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    Plugins should be stateless or store state in external storage to avoid inconsistencies across instances. A plugin failure should only impact itself, not cause the entire bot to stop responding.

    Security and Operational Requirements

    Secret Management

    API keys should be injected via environment variables, a dedicated secrets manager, or container security features. Logs must be sanitized for keys and private user information. Rotate keys regularly and invalidate them immediately if a leak is suspected.

    Input and Output Filtering

    A bot receives text from arbitrary users and outputs model-generated content. It is recommended to limit message length on input and check outputs for sensitive or non-compliant content. For public-facing scenarios, consider integrating a content moderation service to filter high-risk queries.

    Rate Limiting and Cost Control

    Set frequency caps for each user or group—for example, a maximum number of requests per minute. Additionally, set a daily budget alert to notify administrators when API usage exceeds a threshold. These measures prevent malicious abuse and unexpected cost overruns.

    Logging and Monitoring

    It is recommended to track key metrics: message volume, model call latency, failure count, and error types. Integrate these metrics with a standard monitoring and alerting system to receive notifications when latency exceeds a threshold or error rates increase.

    Troubleshooting Common Issues

    Symptom Possible Cause Troubleshooting Steps
    The bot is unresponsive Access service is not logged in or the connection is lost Check the access service logs to confirm the connection status.
    No reply in group chats Trigger conditions are not met Check the mention marker and command prefix configuration.
    Authentication errors API key is incorrect or expired Verify the key in the .env file and check its status in the model service console.
    Response timeout Network issue or high model load Test connectivity between the server and the model API; increase the timeout appropriately.
    Confused or incorrect replies Conversation history is not correctly isolated Check if the session key is properly scoped by user or group.

    For effective troubleshooting, inspect the system layer by layer in the direction of data flow: first check if the access layer receives the message, then verify if the trigger judgement passes, and finally confirm the model call succeeds. This approach quickly identifies the failing component.

    Conclusion

    The core principle for building a chatbot integrated with a large language model is a clear separation of responsibilities. The access layer manages connections and message transport, the bridging layer normalizes events, and the business layer handles trigger logic, session management, model invocation, and plugin scheduling. Containerized deployment ensures a reproducible environment, centralized configuration and secure secret management maintain safety, and monitoring and rate limiting guarantee sustainable operation.

    With this design, switching chat platforms or model providers becomes a matter of replacing the corresponding adapter or configuration code, while the core business logic remains stable.