How to Build a Practical AI Agent in Two Hours

    This guide presents a hands-on method for building a useful AI agent from scratch. It explains how to define success criteria, decompose complex tasks, coordinate approved tools, manage state, handle failures, add safety controls, and evaluate execution traces. A minimal Python runtime and a quarterly business report example show how to turn agent concepts into a testable implementation.

    How to Build a Practical AI Agent in Two Hours

    1. Start with the Right Question: Where Does an Agent Create Value?

    Traditional software is passive. A UI event or explicit command triggers a predefined workflow. If required parameters are missing, the system stops and asks a person.

    An AI agent takes a goal as its input and fills in some of the gaps itself. It interprets intent, breaks the goal into steps, selects tools, examines intermediate results, adjusts the plan when necessary, and continues until it produces a deliverable or clearly explains why it failed.

    The value is not simply “calling a large language model one more time.” The real value is turning an uncertain task into an execution trace that can be inspected and audited.

    Typical benefits fall into three categories.

    Complex Task Decomposition

    A request such as “prepare a quarterly business report” should be broken into concrete steps:

    1. Confirm reporting definitions.
    2. Retrieve the source data.
    3. Calculate quarter-over-quarter and year-over-year changes.
    4. Generate charts.
    5. Write conclusions and risk notes.

    These steps should run in dependency order rather than asking the model to generate an entire report in one pass.

    Dynamic Tool Coordination

    Different subgoals require different tools:

    • Query external status through an API.
    • Calculate metrics with code or a batch process.
    • Store intermediate results in object storage or a database.
    • Send notifications through a messaging or email gateway.

    The agent should select a tool based on the current subgoal instead of hard-coding every operation into one script.

    Adaptive Strategies

    When data is missing, an API times out, or results contradict each other, the agent should retry, degrade gracefully, reformulate the request, or ask a human for clarification. It should not place incorrect numbers in the final report.

    2. A Two-Hour Learning Path

    0–20 Minutes: Define the Boundaries

    Write down:

    • The user’s goal.
    • The tools the agent is allowed to use.
    • Actions that are prohibited.
    • The success criteria.

    For example, the expected output might be:

    • A Markdown business brief.
    • One trend chart file.
    • A description of the data sources.

    Without explicit success criteria, it is impossible to determine whether the agent is completing the task or simply making up a plausible answer.

    20–50 Minutes: Build a Task Graph, Not a Collection of Prompts

    Represent the goal as a directed sequence of steps. Each step should define:

    • Its inputs.
    • Its outputs.
    • Its failure conditions.

    Draw the workflow on paper or in comments first. Then ask the model to plan within this structure. A task graph is easier to test and control than a large prompt that attempts to describe the entire process.

    50–90 Minutes: Implement the Smallest Runtime

    A minimal agent loop is enough:

    1. Observe the current state.
    2. Select the next action.
    3. Call a tool.
    4. Write the observation back to the state.
    5. Decide whether the task is complete.

    Start with two or three tools. Do not connect a dozen systems before the basic execution loop works.

    90–120 Minutes: Test Three Realistic Cases

    Use at least three scenarios:

    1. All required information is available.
    2. Important information is missing.
    3. A tool fails.

    Record the execution traces and add guardrails and logging based on what you observe. You have learned the method only when failures can be reproduced and analyzed—not when a single demonstration succeeds.

    3. The Core Runtime: State, Planning, Action, and Observation

    An agent turn can be described with four elements.

    State

    The state contains:

    • The goal.
    • Confirmed facts.
    • Remaining tasks.
    • Tool results.
    • Budgets such as maximum steps, latency, and tool-call limits.

    Planning

    Based on the current state, the planner produces the next action. That action must belong to an approved set of operations.

    The plan may be a structured decision generated by a model, with deterministic rules used as a fallback.

    Action

    The action executes a real tool. Tools should expose clear, function-like boundaries:

    • Validate inputs.
    • Enforce timeouts.
    • Mark operations as idempotent or retryable where appropriate.
    • Return structured error codes.

    Observation

    Write either the successful result or a concise error summary back into the state. Do not blindly place large raw responses into the context. Summarize them while preserving traceability, including:

    • Query parameters.
    • Time range.
    • Number of records.
    • Other identifiers needed to reproduce the result.

    The following educational skeleton is not tied to any specific vendor API:

    1. from dataclasses import dataclass, field
    2. @dataclass
    3. class State:
    4. goal: str
    5. facts: dict = field(default_factory=dict)
    6. todo: list = field(default_factory=list)
    7. trace: list = field(default_factory=list)
    8. step: int = 0
    9. max_steps: int = 8
    10. def plan(state: State) -> dict:
    11. # Return {"action": "tool_name"|"finish"|"ask_user", "args": {...}, "reason": "..."}
    12. ...
    13. def act(decision: dict) -> dict:
    14. # Dispatch through an allowlist; prohibit arbitrary code or arbitrary network addresses
    15. ...
    16. def run(goal: str) -> State:
    17. state = State(goal=goal, todo=["clarify_scope", "fetch", "compute", "render", "compose"])
    18. while state.step < state.max_steps:
    19. decision = plan(state)
    20. state.trace.append({"plan": decision})
    21. if decision["action"] == "finish":
    22. break
    23. if decision["action"] == "ask_user":
    24. state.facts["need_human"] = decision["args"]
    25. break
    26. obs = act(decision)
    27. state.facts.setdefault("observations", []).append(obs)
    28. state.step += 1
    29. return state

    The important design principles are:

    • Keep planning separate from execution.
    • Use an action allowlist.
    • Enforce a maximum step count.
    • Stop explicitly when human input is required instead of asking the model to continue indefinitely.

    4. Turn the Quarterly Report into an Executable Specification

    Do not leave the example at the level of a slogan. Define a specification for the goal.

    Scope Confirmation

    By default, use the most recently completed quarter. Track sales and order volume, comparing them with both the previous quarter and the same quarter in the previous year.

    If the user has already specified a different scope, follow the user’s definition and write it into facts.

    Data Retrieval

    Use read-only queries. Return:

    • Row count.
    • Time coverage.
    • Null-value ratio.

    If the proportion of missing values is too high, do not calculate a growth rate directly. Instead, flag the data-quality issue in the report.

    Calculation

    Calculate growth rates and other metrics with deterministic code. Do not ask the model to perform arithmetic mentally. The model should interpret and explain the code output, not replace it.

    Visualization

    Use a general-purpose charting library to generate visuals from the tabular data. Store the resulting file in object storage or a local working directory. The report should reference the file path and chart title.

    Report Composition

    Use a fixed structure:

    1. Conclusions.
    2. Reporting definitions.
    3. Key figures.
    4. Trend analysis.
    5. Risks and items requiring verification.

    Every important number must be traceable to a specific observation.

    Tool Failure Handling

    If a query times out, retry a limited number of times. If it still fails, deliver:

    • The reason the report is incomplete.
    • The partial results that were successfully obtained.

    Never invent a table or fabricate a metric.

    This specification covers the three core agent capabilities: decomposition, tool coordination, and strategy adjustment under failure. It also makes every step testable.

    5. Prompts and Constraints: Make the Model a Dispatcher, Not a Database

    The system instructions should clearly define:

    • The agent’s role.
    • The success criteria.
    • Prohibited actions.
    • The requirement not to invent numbers that were not observed.
    • The requirement not to call actions outside the allowlist.
    • The requirement not to output secrets.

    In each turn, provide only a compressed state:

    • The goal.
    • Confirmed reporting definitions.
    • Recent observation summaries.
    • Remaining step budget.

    Including the entire history consumes context and increases the risk of fabrication.

    Require the planner to return a fixed structure containing:

    • Action name.
    • Parameters.
    • Completion condition.

    If parsing fails, retry once or fall back to asking the user for confirmation. Do not drive tools with unconstrained prose.

    Tool descriptions should focus on capabilities:

    • Name.
    • Purpose.
    • Parameter meanings.
    • Return fields.
    • Typical errors.

    Avoid filling prompts with irrelevant implementation details or brand narratives.

    6. Engineering the Agent: Without Observability, There Is No Reliable Agent

    Logging

    For every step, record:

    • The reason for the decision.
    • Tool name.
    • Execution time.
    • Result summary.
    • Whether a safety guardrail was triggered.

    This makes it possible to understand why the agent selected a particular path.

    Evaluation

    Prepare a fixed test set and check:

    • Whether the task was completed.
    • Whether numbers match tool outputs.
    • Whether the agent exceeded its permissions.
    • Whether it stayed within the step budget.

    During regression testing, measurable correctness is more important than whether the agent merely appears more intelligent.

    Security

    Use:

    • Least-privilege accounts.
    • Read-only access whenever possible.
    • Redaction of sensitive fields.
    • Output-side filtering.

    An agent amplifies the permissions it has; it does not automatically improve the judgment behind those permissions.

    Cost and Latency

    Limit:

    • Maximum steps.
    • Maximum response length for each tool call.
    • Unnecessary model-generated work.

    If a rule or SQL query can complete a task reliably, do not ask the model to generate the result.

    Human-in-the-Loop Controls

    High-impact actions—such as sending external messages, writing to a production database, or changing configuration—should normally produce a draft first. Require human approval before execution.

    For deployment, standard cloud capabilities are sufficient for the major components:

    • Model service.
    • Task queue.
    • Object storage.
    • Logs.
    • Monitoring and alerts.

    Run long tasks asynchronously, send execution traces to logs, and route failures to alerts. If you use a cloud platform such as Baidu AI Cloud, treat the agent as a regular application that requires permissions, quotas, and auditing. Do not assume that the model itself provides compliance boundaries.

    7. Common Failure Modes and Fixes

    Trying to Generate the Final Long Document in One Step

    Fix: Use a multi-step state machine. Make the output of each step inspectable.

    Failing to Write Tool Results Back to State

    The model will continue guessing in the next turn.

    Fix: Always write a concise observation summary back into the state.

    Treating Errors as Successful Results

    For example, an empty API response should not lead to a report claiming 20% growth.

    Fix: Treat empty or invalid results as explicit branches in the workflow.

    Producing an Unexecutable Plan

    An action name may not exist in the allowlist.

    Fix: Validate the parsed plan. If it is invalid, re-plan or ask the user for clarification.

    Having No Termination Condition

    The agent may repeat the same action indefinitely.

    Fix: Add:

    • A maximum step count.
    • Repeated-action detection.
    • A clear condition for determining whether the goal has been satisfied.

    8. The Minimum Deliverable After Two Hours

    At the end of the exercise, you should have four artifacts:

    1. A one-page task specification.
    2. A description of the allowlisted tools.
    3. An execution loop with a maximum step count.
    4. Three sample traces covering success, missing information, and tool failure.

    Use these artifacts as the baseline for later additions such as memory, multi-agent roles, or more detailed evaluation. Do not begin by accumulating frameworks before the basic execution path is testable.

    The core methodology can be summarized in one sentence:

    Constrain autonomy with explicit goals, enable action through allowlisted tools, ensure correctness through observations rather than eloquence, and control risk with budgets and human approval.

    If you can write Python, you can build a first useful AI agent in two hours—and place future improvements on an execution trace that can be tested, reproduced, and audited.