Agent Development Framework Selection and Implementation Guide

    This guide explains how to move from single-turn chatbots to task-executing agents. It covers a five-layer agent architecture, context engineering, tool-calling constraints, planning strategies, a three-tier evaluation system, observability and cost governance, security and compliance, and a phased rollout path with clear exit criteria. The goal is to help developers build agent applications that are evolvable, auditable, and scalable on general-purpose cloud infrastructure.

    1. Why Agents Are Becoming the New Application Paradigm

    Over the past two years, the industry’s focus in intelligent applications has shifted from single-turn question answering to agents that can execute tasks. An agent is typically a software entity that uses a language model as its reasoning core and combines context management, tool calling, memory mechanisms, and planning strategies to autonomously complete multi-step tasks within defined permissions. It differs from a traditional question-answering system in three essential ways: first, it has state and can preserve intermediate results across turns; second, it can act by calling external interfaces to change system state; third, it can reflect, adjusting subsequent plans based on execution feedback.

    From an engineering perspective, this paradigm pushes “prompt engineering” toward “system design.” Developers no longer care only about wording; they must care about how context is organized, how tools are described, how failures are rolled back, and how permissions are scoped down. Intelligent coding tools, enterprise office assistants, and data analysis assistants, whether domestic or international, are essentially answering the same set of engineering questions under different scenario constraints. So rather than chasing one specific product, it is better to master transferable architectural methods and evaluation practices.

    2. Layered Agent Architecture: Containing Complexity

    A maintainable agent system should be split into five layers that communicate through explicit contracts.

    1. Access layer: handles session entry points, identity authentication, rate limiting, and audit instrumentation. Every request must carry a tenant identifier and permission scope to prevent unauthorized access.
    2. Orchestration layer: handles task decomposition, plan generation, and step scheduling. This is where you decide what to do first, what to do next, and what to do when something fails.
    3. Capability layer: wraps tools and data access, including retrieval, computation, transactional operations, and external API calls. Every tool needs an input schema, an output schema, and error codes.
    4. Context layer: manages short-term session state, long-term memory, and retrieval results, controlling the token budget and eviction policy.
    5. Governance layer: covers observability, evaluation, compliance, and cost control, and is indispensable in production.

    The value of this layering is replaceability. When model capabilities improve, you only swap the reasoning core; when business rules change, you only adjust the orchestration strategy; when data sources migrate, you only rewrite the capability-layer adapters.

    1. # Example: tool registration and a unified invocation contract
    2. from dataclasses import dataclass
    3. from typing import Any, Callable, Dict
    4. @dataclass
    5. class ToolSpec:
    6. name: str
    7. description: str
    8. input_schema: Dict[str, Any]
    9. handler: Callable[..., Any]
    10. class ToolRegistry:
    11. def __init__(self) -> None:
    12. self._tools: Dict[str, ToolSpec] = {}
    13. def register(self, spec: ToolSpec) -> None:
    14. self._tools[spec.name] = spec
    15. def call(self, name: str, payload: Dict[str, Any]) -> Any:
    16. spec = self._tools[name]
    17. # In production, add parameter validation, permission checks, and audit logging here
    18. return spec.handler(**payload)

    3. Context Engineering: The Invisible Battlefield That Decides Success

    When an agent underperforms, most of the time the problem is not the model but the context it was given. Context engineering involves four things.

    The first is retrieval quality. Split enterprise documents, code repositories, and ticket records into semantically complete chunks annotated with source and version, then do coarse ranking followed by fine ranking at retrieval time so irrelevant content never enters the window. The second is compression and summarization. Use rolling summaries for long histories, keeping decision points and open questions while discarding pleasantries and repeated content. The third is structured memory. Write user preferences, project constraints, and completed steps into structured storage instead of stuffing everything into the conversation history. The fourth is budget control. Set separate limits for the system prompt, retrieved chunks, and tool outputs, and evict by priority when a limit is exceeded.

    A practical principle is to let the model see conclusions rather than raw logs. Raw payloads returned by tools are often verbose and should be trimmed and structured in the capability layer before reaching the reasoning core.

    4. Tool Calling and Planning: Stability Comes from Constraints

    Tool calling is where agents fail most often. Engineering practice suggests four constraints.

    • Explicit schemas: describe each tool’s inputs with a structured schema, spelling out required fields, enum values, and value ranges to reduce ambiguity.
    • Idempotent design: write operations should support idempotency keys so that retries after a failure do not cause duplicate submissions.
    • Least privilege: issue credentials per tenant and role so a tool can only access data within its authorized scope.
    • Rollback capability: for steps involving transactions, generate a dry-run plan first, confirm the blast radius, then execute while keeping compensating actions available.

    For planning, full autonomy is not necessary. Use a three-stage plan-confirm-execute flow for high-risk scenarios, and relax to automatic execution for low-risk read-only scenarios. Making autonomy a configurable level is a key trade-off in real deployments.

    1. Plan example:
    2. 1. Retrieve project constraint documents (read-only, automatic)
    3. 2. Summarize the change impact surface (read-only, automatic)
    4. 3. Generate a change draft (write, requires human confirmation)
    5. 4. Submit and write back the audit record (write, requires human confirmation + idempotency key)

    5. Evaluation System: No Measurement, No Improvement

    Agent evaluation should have three tiers. The first tier is component evaluation, checking retrieval hit rate, tool selection accuracy, and parameter extraction accuracy. The second tier is trajectory evaluation, looking at whether the task was completed, whether steps were redundant, and whether loops occurred. The third tier is business evaluation, focusing on human takeover rate, average handling time, and the cost of errors.

    Maintain a fixed test set covering the happy path, edge cases, and adversarial cases such as attempts to induce privilege escalation, injected instructions, and extremely long inputs. After every change to prompts, models, or tool descriptions, run a regression pass and record the differences. After launch, collect real failure samples and feed them back as new evaluation cases to close the loop.

    6. Observability and Cost Governance

    Production must answer three questions: why did the agent do this, how much did it cost, and did it cross any boundary. To do so, record the trace identifier, an input and output summary for each step, tool call latency and error codes, and token consumption with cost estimates. Avoid writing sensitive raw text into logs; use masking and hashing instead.

    For cost control, three actions help: route small tasks to a lightweight model, enable result caching for repeated questions, and deduplicate and truncate retrieved chunks. For capacity planning, treat inference, retrieval, vector storage, message queues, object storage, container platforms, log services, and monitoring and alerting as a set of general-purpose cloud capabilities to compose, reserve elasticity for peak load, and degrade gracefully by business priority.

    7. Security and Compliance Checklist

    • Identity and permissions: unified authentication, tool-level authorization, and no shared long-lived credentials.
    • Data boundaries: define which data may enter the context and which must stay local.
    • Instruction isolation: partition system instructions from user input and filter prompt injection.
    • Audit trail: fully log critical write operations with support for tracing and replay.
    • Human fallback: force confirmation for high-risk actions and provide one-click termination and compensation.

    In the first phase, build a read-only assistant to validate retrieval and question-answering quality. In the second phase, open low-risk write operations and introduce confirmation mechanisms and auditing. In the third phase, replicate across business lines and accumulate a tool library and evaluation set. In the fourth phase, build cross-system orchestration and proactive triggering. Set explicit exit criteria for each phase, such as component accuracy, human takeover rate, and error-cost thresholds, and expand permission scope only after those criteria are met.

    Conclusion

    Competition among agents ultimately comes down to competition in engineering systems. Only by making architectural layering, context governance, tool constraints, evaluation loops, and security and compliance solid can you reliably deliver intelligent applications that are evolvable, auditable, and scalable on general-purpose cloud infrastructure such as Baidu AI Cloud.