Skip to main content
LearnMLAcademy
Intermediate10 min read

Build an AI Agent with Tools & Memory

Implement a fully autonomous AI agent with tool execution and memory state, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

1. Project Goal

Apply the existing Agentic AI lessons by building a bounded local support agent that can inspect an order, use short-term state, retrieve an approved durable preference and stop safely when evidence or required input is missing.

2. What You Will Build

A narrow goal and trusted instruction contract
A typed read-only order tool with argument validation
Current-run state plus a separate durable-memory example
Successful and abstention traces with step, latency and cost budgets

3. Skills / Prerequisites

Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.

4. Dataset or Inputs

The synthetic domain contains one local order and one approved customer preference. No paid model or external tool is required. The deterministic decision function stands in for a model so the architecture, validation and traces remain reproducible.

Understand every project input

Understand every project input
ComponentExampleResponsibility
GoalAnswer order-status questionDefines success boundary
InstructionsUse approved tools; never invent statusTrusted policy
Tool schemaget_order(order_id: integer)Validates proposed action
Stategoal, step, observations, traceTemporary execution record
Memorycustomer_7 prefers concise answersApproved cross-session fact
Stop rulessuccess, missing input, no evidence, 5 stepsBound cost and risk

5. Architecture / Workflow

Assemble goal, instructions and relevant memory into the current context.

Let the decision layer propose an answer, clarification, tool call or abstention.

Validate the tool name and arguments in trusted code before execution.

Record the observation, update state and stop on success, safe failure or budget exhaustion.

Project figure

A bounded support agent operates inside an application shell

Who chooses the next action, and who enforces limits?

Goal + instructions
Model decision
Validated tool
Observation
Stop / continue
Trusted shell: tool allowlist • max 5 steps • approval • audit trace
The model proposes an answer, tool call or abstention. Trusted code validates tool arguments, enforces the step budget, records state and stops the run.

6. Environment / Dependencies

  • Python 3.10+ standard library
  • Local dictionaries for orders and memory
  • No paid LLM required for the runnable trace
  • Optional model adapter only after deterministic tests pass

7. Data or Input Understanding

State answers 'where is this run now?' and normally ends with the run. Persistent memory answers 'what approved information may help a later run?' and needs write, update and delete policy.

A tool schema describes valid arguments but does not grant permission. Trusted application code still checks identity, authorization, business policy and side effects.

8. Baseline / Simplest Working Approach

Start with ordinary code that handles one known question. Then add a model-directed decision only if natural-language variation makes fixed routing insufficient.

The simplest agent baseline must pass three tests: supported success, missing required input and unsupported/no-evidence abstention.

Project figure

Tools, state and memory serve different jobs

What is temporary, what persists, and what may change the outside world?

Current state
goal, step, observations; ends with run
Durable memory
approved preference; persists across runs
Tools
validated reads/writes to external systems
Context builder selects only relevant state, memory and tool results for the next decision.
State tracks the current run; durable memory stores approved facts for later retrieval; tools read or change external systems through validated schemas.

Worked Example: Calculate one bounded run's latency and cost

Given: A successful run uses two model decisions at 0.6 seconds and $0.004 each, plus one tool call at 0.3 seconds and $0.002.

  1. 1Model latency = 2 × 0.6 = 1.2 seconds.
  2. 2Total latency = 1.2 + 0.3 = 1.5 seconds because the steps are sequential.
  3. 3Model cost = 2 × $0.004 = $0.008.
  4. 4Total cost = $0.008 + $0.002 = $0.010.

Interpretation: The run succeeds in three charged operations. A retry would increase both totals, which is why step and cost ceilings are operational controls.

9. Step-by-Step Implementation

Step 1: Run the complete local agent

The function validates order_id, records every decision and returns controlled statuses. It does not claim to be a language model.

Run the complete local agentRUNNABLE CODE
ORDERS = {1042: {"status": "shipped", "eta": "Friday"}}
MEMORY = {"customer_7": {"tone": "concise"}}  # approved durable preference
MAX_STEPS = 5

def get_order(order_id: int):
    if not isinstance(order_id, int):
        raise ValueError("order_id must be an integer")
    return ORDERS.get(order_id)

def run_support_agent(goal: str, order_id: int | None):
    state = {"goal": goal, "step": 0, "observations": [], "trace": []}
    for step in range(1, MAX_STEPS + 1):
        state["step"] = step
        if order_id is None:
            state["trace"].append("abstain: missing order id")
            return {"status": "needs_input", **state}
        state["trace"].append(f"tool get_order({order_id})")
        order = get_order(order_id)
        if not order:
            state["trace"].append("abstain: order not found")
            return {"status": "not_found", **state}
        state["observations"].append(order)
        state["trace"].append("answer from verified observation")
        return {"status": "success", "answer": order, **state}
    return {"status": "budget_exhausted", **state}
Representative expected output: Order 1042 returns success; missing order_id returns needs_input; unknown order returns not_found.

Step 2: Define the model boundary

If an LLM is later added, it may propose only one of these actions. Application code validates the proposal and owns execution.

Define the model boundaryCONCEPTUAL PSEUDOCODE
Action = Answer(text) | GetOrder(order_id) | AskForOrderId() | Abstain(reason)
while state.step < MAX_STEPS:
    proposal = model.choose(allowed_actions, context)
    action = validate(proposal, user_permissions)
    observation = execute(action)
    state = record(state, action, observation)

Step 3: Persist memory deliberately

Write only an approved stable preference, with provenance and deletion support. Do not store the entire conversation automatically.

Persist memory deliberatelyOPTIONAL PRODUCTION EXTENSION
memory_store.upsert(
  subject="customer_7", key="response_tone", value="concise",
  source="user-approved setting", expires_at=None
)

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
ScenarioTraceFinal status
Known order 1042validate → get_order → observe → answersuccess
No order IDcheck input → ask/abstainneeds_input
Unknown order 9999get_order → empty observation → abstainnot_found
Repeated no progresssteps reach 5budget_exhausted

11. Evaluation

Score task success, correct tool choice, argument validity, evidence-grounded answer, safe abstention, step count, latency and cost. Inspect the full trajectory, not only the final sentence.

Create adversarial tests for malformed IDs, tool injection, stale memory, denied permissions, tool timeout and repeated no-progress loops.

Project figure

A trajectory makes success and safe abstention inspectable

What evidence should an evaluator see after the run?

Successful trace

  1. 1. plan: inspect order
  2. 2. tool: get_order(1042)
  3. 3. observe: shipped
  4. 4. answer with evidence

Safe abstention trace

  1. 1. plan: search approved docs
  2. 2. tool: no supporting result
  3. 3. verify: insufficient evidence
  4. 4. abstain and escalate
The successful trace finds an order and answers with evidence. The unsupported request exhausts neither permissions nor budget: it stops with a clear abstention.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
Invented order statusAnswered without observationRequire evidence before answer
Wrong tool argumentSchema/validation missingReject before execution and request correction
Stale preferenceMemory lacks provenance/updateVersion and allow user correction/deletion
Infinite loopNo progress/stop ruleStep, time and cost budgets with escalation

13. Improve the Project

Add a second read-only tool only after tests distinguish when it is needed.
Replace the deterministic chooser with a provider adapter while retaining action validation.
Add checkpointing for tasks that may pause for human approval.
Build a regression set from successful, abstention and recovery traces.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
PermissionsAuthorize every tool at execution time
DurabilityCheckpoint state before waits or consequential actions
ObservabilityTrace IDs, tool inputs/results, tokens, latency, cost and status
RecoveryIdempotency, timeout classification, retries and human escalation

15. Summary / Key Takeaways

  • An agent project begins with a bounded goal, allowed actions and explicit success and stop conditions.
  • The model may propose a tool call, but trusted code validates permissions, policy and typed arguments.
  • Short-term state records the current trajectory; persistent memory stores only approved facts for future runs.
  • A step budget limits loops, latency and cost and ends in a controlled escalation or abstention.
  • A successful trace must show which observation supports the answer.
  • Safe failure is a required outcome when input, evidence, authority or progress is missing.
  • Production agents need trajectory evaluation, durable checkpoints, idempotency, observability and rollback—not merely a stronger prompt.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Build an AI Agent with Tools & Memory"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What is the difference between agent state and durable memory?
Question 2 of 5numerical/formula
Two model calls take 0.6 s each and one sequential tool call takes 0.3 s. What is total latency?
Question 3 of 5application/scenario
The model proposes get_order(order_id='abc'). What should trusted code do?
Question 4 of 5debugging/diagnostic
An agent repeats the same search without new evidence. Which control is most relevant?
Question 5 of 5interpretation
Why is an abstention trace a successful test case?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the difference between agent state and durable memory?▼

Correct Answer: State tracks the current run; memory stores approved information for possible later runs

State represents current execution progress. Durable memory persists selected facts under explicit write and retrieval policies.

2Two model calls take 0.6 s each and one sequential tool call takes 0.3 s. What is total latency?▼

Correct Answer: 1.5 s

Sequential latency adds: 0.6 + 0.6 + 0.3 = 1.5 seconds.

3The model proposes get_order(order_id='abc'). What should trusted code do?▼

Correct Answer: Reject the invalid argument and request correction or input

The schema requires an integer. Validation must occur before tool execution, independent of model confidence.

4An agent repeats the same search without new evidence. Which control is most relevant?▼

Correct Answer: No-progress and step-budget stopping rules

Progress checks and finite budgets stop loops that add cost and risk without moving toward success.

5Why is an abstention trace a successful test case?▼

Correct Answer: It shows the system stops safely when evidence or authority is missing

Safe refusal or escalation is required behavior when the system cannot support an answer or action.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next