Building an Intelligent Agent Architecture for Chat Applications: Ears, Brain, and Hands

    Assembling a "perception-decision-execution" loop within a chat entry point is critical for building practical intelligent agents. This article explores the "ears, brain, and hands" architecture for integrating smart agents into chat applications, covering message adaptation, multimodal perception, intent recognition, task planning, sandboxed execution, and closed-loop governance. By focusing on state management, access control, exception handling, and observability, readers will learn how to design an operable, auditable, and scalable agent system that can reliably listen, think, and execute user requests.

    Building an intelligent agent is not just about picking a specific product; it is about assembling a “perception-decision-execution” closed loop within an instant messaging entry point. When a user sends a text, image, or voice message in a chat window, the system must be able to listen, think, execute, and return the result reliably. A useful analogy is to view the system as having ears, a brain, and hands: the ears receive and standardize input, the brain handles understanding, planning, and constraints, and the hands invoke tools, execute tasks, and provide feedback. What truly determines engineering quality is the state management, access control, exception handling, and observability across these three components.

    1. Overall Architecture: From Chat Message to Task Loop

    A deployable chat agent typically consists of an access layer, understanding layer, planning layer, execution layer, and governance layer. The access layer interfaces with instant messaging platforms via event callbacks or persistent connections, handling authentication, deduplication, idempotency, and session routing. The understanding layer converts inputs like text, images, voice, and files into a unified event model, extracting intent, entities, and context. The planning layer generates task steps using Large Language Models (LLMs), rule engines, and knowledge retrieval. The execution layer completes operations via tool invocation, workflows, or automation scripts. The governance layer manages permissions, auditing, rate limiting, logging, metrics, and alerting. The chat window is just the entry point; the task queues, state machines, sandbox execution, and human fallback behind it are the prerequisites that allow the “hands” to reach out.

    2. The Ears: Message Adaptation and Multimodal Perception

    The “ears” do not merely receive messages; they transform heterogeneous inputs into computable events. First, channel adaptation is required: different chat entries have varying event formats, retry mechanisms, signature verification, and message types. The access layer should provide a unified abstraction to output standard events, such as session ID, user ID, message type, content reference, timestamp, and idempotency key. Second, multimodal processing is necessary: text undergoes cleaning and language identification, images undergo optical character recognition (OCR) or image understanding, voice is transcribed, and files are parsed and indexed. All raw content should be stored in object storage, with only references kept in the event to avoid oversized message payloads. The access layer must also handle duplicate deliveries, out-of-order messages, and timeout retries. It is recommended to use idempotency keys for deduplication and session state machines to ensure ordering. Example pseudocode:

    1. def on_event(raw_event):
    2. verify_signature(raw_event)
    3. event = normalize(raw_event)
    4. if seen(event.idempotency_key):
    5. return ack()
    6. store_raw_content(event)
    7. enqueue(event.session_id, event)
    8. return ack()

    The key principle here is “acknowledge first, process later.” Chat platforms usually demand rapid responses, so time-consuming tasks should enter a message queue for asynchronous execution, avoiding timeouts that trigger duplicate pushes. Session context must distinguish between short-term conversational state and long-term memory: short-term state holds current task slots, clarification questions, and pending actions; long-term memory stores user preferences, authorization scopes, and historical task summaries, with appropriate expiration and desensitization policies.

    3. The Brain: Intent Recognition, Task Planning, and Constraints

    The “brain” is responsible for turning user expressions into executable plans. The first step is intent recognition and slot filling: determining whether the user wants to query, process, remind, summarize, or control a device, and extracting parameters like time, object, and scope. For high-risk requests or missing parameters, the system should proactively clarify rather than guess and execute. The second step is planning: simple tasks follow rule-based routing, while complex tasks are handled by LLMs generating steps. However, the output format must be constrained by structured outputs, detailing step type, tool name, parameters, preconditions, and failure strategies. The third step is knowledge and memory augmentation: injecting enterprise knowledge, operation manuals, and historical tickets into the context via Retrieval-Augmented Generation (RAG) to reduce hallucinations. The fourth step is safety constraints: checking for privilege escalation, sensitive data exposure, or the need for human approval during the planning phase.

    A practical principle is that “the model is responsible for understanding and suggesting, while the policy is responsible for approving and rejecting.” Do not leave permission judgments to the model’s free will; instead, a policy engine should uniformly verify them before tool invocation. Pseudocode:

    1. def think(event, ctx):
    2. intent = understand(event, ctx)
    3. if intent.missing_slots:
    4. return clarify(intent)
    5. plan = make_plan(intent, ctx)
    6. plan = policy.filter_steps(plan)
    7. return plan

    4. The Hands: Tool Invocation, Sandbox Execution, and Feedback

    The “hands” are where the agent generates real value, but also where the highest risks lie. Tools should be encapsulated with clear contracts: input parameters, output structure, permission scope, timeout, idempotency requirements, and failure semantics. During execution, prioritize sandboxed or restricted runtime environments; direct command string concatenation and execution must be prohibited. External system calls should enforce rate limits, timeouts, and retry ceilings. For write operations, support dry-run, confirmation, and rollback: generate a change preview, submit only after user or admin confirmation, and record operation logs and result snapshots upon submission. Long tasks enter a task queue and asynchronously notify the user via the chat window upon completion. Example:

    1. def execute(plan, ctx):
    2. for step in plan.steps:
    3. if not policy.allow(step, ctx.user):
    4. return request_approval(step)
    5. result = sandbox_call(step.tool, step.params, timeout=step.timeout)
    6. ctx = update_state(ctx, step, result)
    7. if result.status == "pending":
    8. enqueue_followup(step)
    9. return compose_reply(ctx)

    5. Closed-Loop Governance: State, Observability, and Security

    A chat agent is not a single Q&A round but a multi-turn state progression. It is recommended to use a session state machine to describe states like “pending clarification,” “pending confirmation,” “executing,” “completed,” “failed,” and “canceled,” generating a tracking ID for each task. Logs should record events, plans, tool calls, time consumed, and result summaries, with sensitive fields desensitized. Metrics should focus on success rate, average time consumed, clarification rate, human takeover rate, and tool error rate. Alerts should cover queue backlog, timeouts, permission denial exceptions, and content security hits. In terms of security, adhere to least privilege, tenant isolation, data minimization, content security review, and audit trails. High-risk actions involving funds, deletion, or publishing must introduce human approval and secondary confirmation.

    6. Deployment and Implementation Recommendations

    Engineering implementation can start with low-risk, high-frequency, and well-bounded scenarios, such as information queries, meeting minutes generation, ticket summarization, and internal knowledge Q&A, before gradually expanding to write operations. Tool contracts should be versioned. Planning prompts and evaluation sets should be maintained together, validated with replay sets before changes. During deployment, you can leverage general-purpose capabilities provided by Baidu AI Cloud, such as container platforms, message queues, object storage, logging services, and monitoring alerts, though the business logic should remain infrastructure-neutral. Finally, set up a “human fallback” entry for the agent: when confidence is low, permissions are insufficient, or consecutive failures occur, escalate to human processing and feed failed samples back into the evaluation and optimization pipeline. This way, the “ears + brain + hands” architecture becomes not just a demo concept, but an operable, auditable, and scalable intelligent agent solution for chat entries.