The Rise of AI Agents: Building IM-Native Agents in Practice
This article explores how to turn AI agents into always-on services that live natively inside instant messaging tools. It breaks the architecture into five layers—access, session, orchestration, capability, and governance—and explains the engineering practices each one requires: idempotent message handling, event tiering and rate limiting, asynchronous progress updates, context engineering with layered memory and token budgets, a plan-execute-validate orchestration loop, least-privilege tool governance, model routing and caching for cost control, and security and compliance constraints specific to chat environments. It closes with a three-phase rollout path from usable to operable. Readers will get a vendor-neutral blueprint for moving agents from demos to daily production tools.
The Rise of AI Agents: Building IM-Native Agents in Practice
From “Toy” to “Infrastructure”: A Shift in Agent Form Factor
The agent space has heated up quickly. Public leaderboard data shows a category of general-purpose agents climbing fast in global invocation rankings, leading in niches such as coding and command-line assistants, with monthly invocation volume reaching the trillion-token scale. It is widely regarded as one of the fastest-growing agent form factors. This article discusses no specific product or vendor. Instead, it abstracts the phenomenon into a clear technical question: when agent invocation volume grows exponentially, how do you turn it into infrastructure that is natively embedded in instant messaging tools and directly usable by ordinary users?
The question has three dimensions:
- A shift in the interaction entry point: from standalone web consoles and command-line interfaces to the IM conversations users already open every day;
- Servicification of the runtime: from one-off scripts to long-running, stateful, concurrent, observable online services;
- An expansion of capability boundaries: from plain text Q&A to an execution entity that can call tools, read and write enterprise systems, and proactively push results.
“Native IM support” does not mean treating a chat window as an input box. It requires the agent to align with the messaging platform across four dimensions: conversation semantics, identity, message ordering, and permission boundaries. This is the starting point for all the designs that follow.
Overall Architecture: Five Layers and Clear Responsibility Boundaries
A messaging-native agent built to run for the long term is best split into the following five layers, with each pair communicating through explicit contracts to avoid capability coupling.
| Layer | Core Responsibility | Key Design Points |
|---|---|---|
| Access | Conversation protocol adaptation, message deduplication, event dispatch | Idempotency, retries, rate limiting |
| Session | Session state, context window, multi-turn attribution | Decoupling session ID from user ID |
| Orchestration | Task planning, tool selection, multi-step execution | Plan-execute-validate loop |
| Capability | Toolset, retrieval, code execution sandbox | Least privilege, rollback |
| Governance | Logs, metrics, cost, audit | End-to-end tracing and quotas |
The key benefit of layering: the access layer absorbs differences between messaging platforms, the capability layer absorbs differences between business systems, and the orchestration layer becomes the only place where decisions are made. When you switch messaging platforms or add an enterprise system, changes stay contained within a single layer.
Access Layer: Turning Conversation Events into a Reliable Request Stream
IM platforms typically push messages via event callbacks or long-lived connections. Engineering must handle three problems.
1. Message idempotency. Platform redelivery, network jitter, and multi-instance deployments can all cause the same message to be processed more than once. The fix is to build a stable deduplication key:
# Build an idempotency key from platform + conversation + message ID, stored in a TTL cachededup_key = f"{platform}:{conversation_id}:{message_id}"if not cache.set(dedup_key, 1, ttl=600, nx=True):return # Already processed, drop it
2. Event tiering and rate limiting. Not every message needs the full reasoning pipeline. Events should be split into three tiers—“commands” (explicit instructions, low latency), “Q&A” (needs retrieval), and “tasks” (long-running, must be asynchronous)—each with its own concurrency quota and timeout, so long tasks do not drag down short Q&A.
3. Asynchrony and progress reporting. Task requests should return an acknowledgment immediately, then stream progress back through the message channel in batches, for example “requirement parsed → retrieving → generating → done.” This matches user expectations in a chat setting and naturally solves connection keep-alive for long-running tasks.
Session Layer: Context Engineering Sets the Ceiling on Experience
The biggest difference between chat and command-line scenarios is that conversations are fragmented, span multiple days, and mix multiple people. Context engineering therefore becomes the core challenge.
- Attribution: in a group chat, several people may ask questions at once, so you must first determine “who is saying this to whom,” or context will bleed across threads. A common approach is intent and addressee detection before deciding whether to inherit history.
- Layered memory: split context into three tiers—“raw text within the window,” “rolling summary,” and “long-term facts.” Keep the most recent turns verbatim; compress older history into a summary; extract stable information such as user preferences and project conventions into long-term facts, stored separately and injected on demand.
- Budget control: set a token budget for context. Prioritize system instructions and long-term facts, then the latest user request, then historical summaries. When the budget is exceeded, trim by layer rather than truncating at random.
Context budget (example allocation)├── System instructions and role constraints ~10%├── Long-term facts (user/project) ~15%├── Rolling summary ~25%└── Recent raw-text window ~50%
Orchestration Layer: From “Chatting” to “Getting Things Done”
An agent’s value lies in execution. The orchestration layer should use a plan-execute-validate loop rather than generating an answer in one shot.
- Plan: decompose the user request into verifiable sub-steps, explicitly tagging the tool and preconditions each step depends on;
- Execute: invoke capability-layer tools step by step, with each step producing a structured result rather than natural language;
- Validate: run schema and business-rule checks on tool output; on failure, retry or switch paths;
- Converge: generate the user-facing natural language reply only after every sub-step passes validation.
A skeletal orchestration outline:
def run(task):plan = planner.decompose(task) # Output a structured list of stepsctx = memory.load(task.conversation_id)for step in plan:result = tools.invoke(step.tool, step.args, ctx=ctx)if not validator.check(step, result):result = fallback(step, result) # Retry / degrade / switch toolctx = memory.append(ctx, step, result)return composer.answer(plan, ctx) # Unified convergent output
For coding and command-line agents, two additional mechanisms are needed: sandboxed execution and rollback of changes. All write operations run first in an isolated environment and produce a diff for the user to confirm before it is applied, preventing accidental modification of production files.
Capability Layer and Tool Governance: Least Privilege Is the Baseline
Tools are an agent’s hands and feet, and also its risk surface. Governance comes down to four principles:
- Allowlist admission: registering a tool requires declaring its purpose, input/output schema, permission scope, and timeout;
- Least privilege: separate reads from writes, default to read-only, and require explicit authorization and a second confirmation for writes;
- Observability: log a summary of inputs, latency, and return codes for every call, with sensitive fields masked;
- Circuit breaking: when a single tool’s error rate crosses a threshold, trip the breaker automatically and let the orchestration layer switch to a degraded path.
When enterprise knowledge retrieval is needed, the common pipeline is “document parsing → chunking → vectorization → hybrid retrieval → reranking.” When artifacts need to be generated, write the result to object storage and return it to the conversation as a link or attachment, avoiding large blocks of content polluting the chat window.
Cost, Performance, and Observability
Trillion-token invocation scale means cost governance is not optional. Practical measures include:
- Tiered model routing: use smaller models for simple intent detection and format conversion, and larger models for complex reasoning and code generation, with the orchestration layer routing by task difficulty;
- Cache reuse: apply semantic caching to frequent repeated questions and result caching to retrieval output, significantly reducing repeated computation;
- Batching and asynchrony: merge non-real-time tasks into batches to raise throughput;
- End-to-end metrics: use “session ID + step ID” as the primary key to correlate logs, metrics, and traces; monitor three core indicators—time to first token, task success rate, and cost per session—and configure alerting and quota ceilings.
Security and Compliance: Constraints Specific to Messaging
Messaging tools are naturally an entry point for enterprise information flow, so security design must come first:
- Identity and authorization alignment: an agent’s visibility in a group chat and the resources it can operate should inherit the initiating user’s permissions rather than hold superuser privileges;
- Data minimization: inject only the information required to complete the task into context, and support per-user deletion of long-term memory;
- Content safety: filter both input and output, detecting and blocking prompt injection and privilege-escalation instructions;
- Audit trail: retain audit records for all write operations and sensitive reads, with traceability.
Suggested Rollout Path
- Phase 1 (usable): connect the access and session layers, deliver single-turn Q&A and basic commands, and validate idempotency and rate limiting;
- Phase 2 (pleasant to use): complete the orchestration layer and tool allowlist, introduce sandboxing and diff confirmation, and cover high-frequency scenarios such as coding and operations;
- Phase 3 (operable): refine layered memory, model routing, cost quotas, and end-to-end observability into a measurable, governable online service.
To carry the capabilities above, you can typically reuse general-purpose cloud categories: a container platform to host the agent runtime and sandbox, object storage for artifacts and knowledge documents, a message queue for asynchronous tasks and progress reporting, and logging plus monitoring and alerting for observability. Baidu AI Cloud offers corresponding capabilities in these general infrastructure categories and can serve as one option for the foundation of such a system.
Conclusion
The move from an invocation-volume contest on leaderboards to a form factor natively embedded in everyday messaging tools is fundamentally an engineering exam. What is being tested is not model parameter count but combined capability in access reliability, context engineering, tool governance, and cost control. Get five things solid—layered architecture, idempotent access, a planning loop, least privilege, and end-to-end observability—and an agent can move from demo to production and become a daily tool teams actually want to open.
