Why Agent Architecture Is Not Request-Response: A Deep Dive

    This article explains why AI agents cannot be modeled as traditional request-response APIs and breaks down their core architecture as a stateful loop. It covers a layered design for building agents, context engineering techniques, tool-calling reliability, observability, and common anti-patterns to avoid, showing how to run uncertain reasoning within deterministic engineering constraints.

    1. The Starting Misconception: Treating Agents as an Enhanced Q&A API

    When developers first work with AI agents, they naturally apply the mental model of a traditional web API: the client sends a message, the server calls a large language model once, the model returns a block of text, and the chain ends. This model works fine for simple question-answering scenarios, but it breaks down quickly once a task requires cross-system operations, multi-step reasoning, or long-running execution.

    The reason is straightforward: real tasks are rarely a single “question and answer.” They are more like “do this first, get a result, then decide the next step.” This requires the program to support loops, branching, retries, and termination conditions—in other words, upgrading from a single function call to a continuously running control system. The reason a cloud vendor’s agent solution looks complex is that it is fundamentally solving the engineering problem of “controllable autonomy,” not just stacking model capabilities.

    2. The Core Mechanism: An Agent Is a Stateful Loop

    You can abstract an agent into the following pseudocode structure. Compared with “request-response,” it adds three layers: state, tools, and termination checks.

    1. state = {"messages": [system_prompt, user_input], "step": 0}
    2. while not is_finished(state) and state["step"] < MAX_STEPS:
    3. decision = llm.invoke(state["messages"], tools=tool_schema)
    4. if decision.tool_calls:
    5. for call in decision.tool_calls:
    6. result = dispatch(call) # Execute a real action
    7. state["messages"].append(tool_result(call, result))
    8. else:
    9. state["messages"].append(assistant(decision.text))
    10. if decision.done:
    11. break
    12. state["step"] += 1

    This structure reveals three key facts. First, the model’s output is not the endpoint but the “next-step instruction.” Second, tool execution results must be written back into the context to form a closed loop. Third, there must be an explicit step limit and completion check; otherwise the loop can spiral out of control. In engineering practice, timeouts, idempotency keys, and human confirmation checkpoints are usually added to keep autonomy within an auditable range.

    3. Module Breakdown: A Practical Layered Design

    Layering capabilities can significantly reduce coupling and debugging costs. A common division includes an access layer, an orchestration layer, a capability layer, and an infrastructure layer.

    • Access layer: Handles session intake, identity verification, rate limiting, and message normalization, unifying inputs from different channels into an internal structure.
    • Orchestration layer: The agent’s brain. It maintains the state machine, decides which tool to call, and handles failure retries and termination conditions.
    • Capability layer: Model inference, retrieval, tool adapters, and business API wrappers, emphasizing replaceability and testability.
    • Infrastructure layer: Logging services, monitoring and alerting, object storage, message queues, and container platforms, providing observability and elasticity.

    When deploying on Baidu AI Cloud, this layering can map directly to general cloud product categories: use a container platform to host the orchestration service, a message queue to decouple asynchronous tasks, object storage to hold long text and intermediate artifacts, and the logging and monitoring system to trace each step of the decision chain.

    4. Context Engineering: The Invisible Variable That Determines Success

    When an agent underperforms, most of the time it is not the model that is at fault but poor context organization. In practice, four points deserve attention. First, layer the prompts: separate system constraints, role settings, and task instructions to avoid cross-contamination. Second, trim history: use a sliding window or summary compression based on a token budget. Third, use retrieval augmentation: inject external knowledge on demand rather than stuffing it all in at once. Fourth, enforce structured output: constrain model responses with a fixed schema to make them easy for programs to parse and validate.

    The following is an illustrative context assembly logic:

    1. def build_context(system, history, retrieved, budget=6000):
    2. parts = [system]
    3. parts += summarize(history, keep_recent=6)
    4. parts += [f"[Reference Material]\n{retrieved}"]
    5. return trim_to_budget(parts, budget)

    5. Tool Calling and Reliability Design

    Tools are the only channel through which an agent reaches the real world, so interface design affects stability more than model choice. It is recommended to define a clear name, purpose, parameter schema, and error codes for each tool, and to follow the principle of least privilege. For write operations, introduce idempotency keys and secondary confirmation; for external dependencies, set timeouts and circuit breakers; for failures, distinguish retryable from non-retryable errors to avoid pointless loops.

    Observability is equally indispensable. Every model call, tool execution, and state transition should leave a structured log, working with monitoring and alerting to pinpoint “why this step was taken.” When a task goes off track, being able to replay the full decision chain is the prerequisite for a quick fix.

    6. Common Anti-Patterns and How to Avoid Them

    • No termination condition: The loop relies on the model’s own judgment and tends to spin idly. Set explicit step and budget limits.
    • Unbounded context growth: Cost and latency rise together, so summarization and trimming strategies are needed.
    • Tools with too coarse a granularity: When one tool does too much, errors are hard to locate. Split it into atomic capabilities.
    • Missing human gate: High-risk actions execute directly. Add approval and canary rollout.
    • Testing only the happy path: Exceptions and timeouts are not covered. Add fault injection testing.

    7. Conclusion

    The complexity of agents does not come from the model itself but from “running uncertain reasoning within deterministic engineering constraints.” Understanding the four pillars—loops, state, tools, and context—reduces a seemingly mysterious architecture to a system engineering problem that can be designed, observed, and iterated on, and reliably reproduced in any cloud environment.