Stop Talking About Prompt Engineering: The Real Fun Is Making AI Live Inside Your Chat App
How to build an AI chatbot that connects to a large language model and replies automatically in your chat app—explained from architecture to implementation. You'll understand the three-layer structure of "message protocol adapter + bot logic layer + model capability layer," learn how to choose a message integration approach, design sessions and context, spin everything up with container orchestration, and get practical guidance on permission boundaries, content safety, and cost control. Follow along and you'll have your own AI chat assistant.
1. Start Here: What Are You Actually Building?
Many attempts to “connect AI to a chat app” get abandoned halfway because they skip problem definition. Before you write a single line of code, answer these three questions in one sentence each:
- Who is it for? Just you, a small team, or hundreds of group members? This directly determines how complex your architecture needs to be.
- What task does it solve? Answering FAQs, retrieving and summarizing information, or taking actions (querying data, generating reports, triggering reminders)?
- Where are the boundaries? Which topics can it answer, which must it refuse, and which operations require human confirmation?
If you don’t answer these first, no framework choice will save you from endless rework. A common mistake is treating it as a “chat toy,” slapping a model on top and shipping it—then watching it answer unrelated questions, flood the group with duplicate messages, or leak information it shouldn’t. Treat it as a small online service for a specific user group, and your mindset will be much healthier.
2. Architecture Breakdown: Three Layers, Three Jobs
No matter which tools you pick, this kind of system abstracts down to three layers. Understand them and you can assemble your own stack instead of being locked into someone else’s.
2.1 Message Adapter Layer: Let the Bot See and Speak
Chat platforms don’t push messages directly to your program. You need a protocol adapter in between. Its job is fixed: log in to the platform as a specific account, convert incoming messages into a unified internal event format, and send your replies back through the platform’s API.
There are usually two ways to build this layer:
- Official bot channels provided by the platform: stable and compliant, but capabilities and entry points are limited by platform rules.
- Unofficial desktop/client-side channels: more flexible and able to join regular groups, but you take on account risk and stability costs.
From an engineering perspective, treat this layer as a replaceable adapter. Your business code should only depend on a unified “receive message / send message” interface, so swapping the underlying implementation doesn’t affect anything above it. This is the single most important factor for long-term maintainability.
2.2 Bot Logic Layer: Sessions, Context, and Capability Orchestration
This layer surrounds the “brain.” It turns a raw message into a meaningful interaction. At minimum, it needs to handle:
- Trigger detection: @mentions, specific prefixes, or responding to every DM—your trigger strategy directly affects the group chat experience.
- Session isolation: each group, each user, and each topic should have its own context. Otherwise you’ll end up telling user A’s private information to user B.
- Context management: don’t stuff all history into the model. Organize it in tiers—“recent N rounds + key summary + long-term memory.” Longer context means higher cost, slower responses, and more chances for the model to go off track.
- Capability orchestration: when to answer directly, when to call retrieval, when to call a tool (weather, database, notifications)—you need a simple decision flow.
- Rate limiting and deduplication: in group chats, multiple messages arriving at once is normal. Queue them, merge them, and apply frequency controls to avoid spam.
2.3 Model Capability Layer: Plug In the Intelligence
This layer does the actual language understanding and generation. Three things matter from an engineering standpoint:
- API format: most model services expose HTTP APIs compatible with mainstream calling styles, so migration costs are low. Wrap model calls in a replaceable client.
- Parameter tuning: temperature controls randomness, max output length controls cost and latency, and the system prompt defines personality and boundaries. These three parameters often matter more than switching models.
- Fallback strategy: when the model times out, gets rate-limited, or goes down, you need a fallback reply—not silence.
3. Why Containerization + Declarative Orchestration
The problems with manually installing environments are well known: dependency conflicts, version drift, and having to redo everything on a new machine. Containers turn your “environment” into a versioned artifact.
Going a step further, describing your entire service topology and dependencies in a declarative config file (like a Compose-style YAML) gives you very concrete benefits:
# Example: declarative config for the bot service topologyservices:adapter: # message adapter layerimage: your-adapter:1.0restart: unless-stoppedenvironment:- ACCOUNT_TOKEN=${ACCOUNT_TOKEN}volumes:- ./data/adapter:/databot-core: # bot logic layerimage: your-bot-core:1.0restart: unless-stoppeddepends_on:- adapter- redisenvironment:- MODEL_BASE_URL=${MODEL_BASE_URL}- MODEL_API_KEY=${MODEL_API_KEY}- MAX_CONTEXT_ROUNDS=8- RATE_LIMIT_PER_MIN=20redis: # session context and rate-limit countersimage: redis:7-alpinerestart: unless-stoppedvolumes:- ./data/redis:/data
Here’s what this config buys you:
- Spin up with one command, tear down with one command—your test and production environments stay consistent.
- Config separate from code: secrets and model parameters live in environment variables, never in your repo.
- Dependency order and restart policy are handled by the orchestrator, so crashed processes come back automatically.
- Volume persistence: session state survives container rebuilds.
For most individual or small-team use cases, single-machine orchestration is enough. Only when concurrency and availability requirements grow should you consider scaling the stateless bot logic layer horizontally, moving session storage to an external cache or database, and adding a load balancer. Don’t over-engineer this path in advance.
4. Implementation Steps: From Zero to Conversation
Here’s a general implementation order that doesn’t depend on any specific project. Each step can be verified independently.
Step 1: Get the “message loop” working first—don’t touch the model yet.
Goal: minimal pipeline—program logs in → receives a message → echoes it back. If this works, your adapter, network, and auth are all fine. Many failed projects skip this step and later can’t tell whether the problem is the model or the connection.
Step 2: Plug in the model, do single-turn Q&A.
Wrap the model call in a function that takes a prompt and returns text. First test it from the command line to confirm the model works, then wire it into the message pipeline. Don’t add context yet—just verify the input-output path.
Step 3: Add sessions and context.
Introduce a store keyed by “session ID” that records the last N rounds of messages. Set a clear context limit (by rounds or by tokens), and when exceeded, summarize and compress instead of truncating. After this step, the bot starts to feel like it’s “having a conversation” rather than “playing a lottery.”
Step 4: Add trigger strategy and rate limiting.
Make it clear that it only responds when @mentioned or in DMs. In group chats, merge duplicate questions within the same minute, and set a per-user per-minute response cap. This step makes or breaks the group chat experience.
Step 5: Add tool capabilities.
Start with read-only abilities (queries, summaries). Verify stability before adding write operations. All write operations should have permission checks and human confirmation mechanisms.
Step 6: Add observability.
Log request latency, input length, output length, and failure reasons for every call. A bot without logs in production is a black box—when something goes wrong, you’re just guessing.
5. Common Pitfalls
5.1 Unbounded Context Growth
This is the most widespread problem. History piles linearly into the prompt, and after a few rounds cost doubles, responses slow down, and the model’s attention gets diluted. The right approach is tiering: recent raw text + summarized key points from earlier + user-profile-style long-term memory, with a clear limit on each tier.
5.2 Treating “Can Log In” as “Ready to Ship”
Logging in successfully is just the starting line. Account restrictions, dropped sessions, out-of-order messages, duplicate delivery—all of this happens in the real world. Design assuming messages may be duplicated, out of order, or lost, and use idempotency (e.g., a dedup key per message) to keep results consistent.
5.3 Missing Permission Model
The bot exists as a specific account, which means it inherits that account’s visibility. At minimum, define three boundaries: who can use it (allowlist), what it can be asked (topics and data scope), and what it can do (read-only or writable). Writing these down is far more effective than patching things up afterward.
5.4 Prompt Injection and Content Risk
User input is untrusted input. Assume someone will try to trick the bot into ignoring its rules, extracting the system prompt, or leaking internal information. Mitigations include: strictly separating system prompts from user input, filtering sensitive content from outputs, forcing a second confirmation for tool calls that involve real actions, and refusing high-risk topics outright while redirecting.
5.5 Out-of-Control Costs
Costs come from three places: context length, call frequency, and output length. Each has a corresponding control: tiered context compression, per-user and per-group rate limits, and different max-output-length settings for different tasks. Make these parameters configurable instead of hardcoded, so you have room to adjust later.
6. Post-Launch Operations
- Monitoring and alerts: at minimum, monitor process liveness, request success rate, average latency, and model call failure rate. Catch anomalies before your users do.
- Log levels: store debug logs, interaction logs, and audit logs separately. Be careful with interaction logs—mask sensitive data and avoid keeping full conversations in plaintext long-term.
- Gradual rollout and rollback: manage prompt and parameter changes with version control so you can quickly roll back to the last known-good version.
- Regular reviews: track high-frequency questions, questions it can’t answer, and questions it refuses. Feed those insights back into prompts and knowledge scope. A bot is a product of ongoing operations, not a one-time delivery.
7. Wrapping Up
Connecting AI to a chat app isn’t technically hard. The real challenge is knowing your boundaries: when to answer and when not to, when to only read and when to allow writes. Architecturally, stick to “adapter is replaceable, logic layer is stateless, capability layer is degradable.” Operationally, stick to “logs, monitoring, rollback.” Do that and your system will run stably for the long haul.
If you already have a working model API and a machine that can run containers, you can get a minimum viable version running in an afternoon. Spend the rest of your time polishing context strategy and permission boundaries—those two things determine whether it’s a “useful assistant” or “the group chat’s biggest headache.”
