| 📊 View Lecture Slides | Full-screen presentation with navigation |
Session 10: Introduction to AI Agents
| Session Duration: 2 Hours | Block: 3 — Agents, Evaluation & Deployment |
Context Note: Today’s lab focuses on building a sequential (chained) agent—a system that makes several generateContent calls where each output is passed into the next prompt. It does not dynamically observe tools or branch logic yet. That advanced functionality (Function Calling and ReAct) is covered in Session 11.
Session clock
| Minutes | Mode | Focus |
|---|---|---|
| 0–50 | Lecture | Theoretical Foundation & Concepts |
| 50–110 | Core lab | Build a Chained Agent in Node |
| 110–120 | Checkpoint | Pair share / show artifact |
Note: Stretch work starts only after the Core checkpoint is completed.
Learning Objectives
By the end of this session, students will be able to:
- Distinguish a reactive chatbot application from a goal-oriented, multi-step agentic workflow.
- Describe the theoretical agent loop: Perceive → Plan → Act → Observe → Repeat.
- Delegate a complex, multi-step task to an AI via chained LLM calls in JavaScript, rather than relying on single-shot prompts.
- Identify the operational risks of AI autonomy and apply necessary safeguards (human-in-the-loop, verification).
Part 1: Theoretical Foundation — From Chatbots to Agents
1.1 What Makes a System “Agentic”?
Up until this point, we have built Reactive Systems. A user types a message, the server processes it (perhaps fetching RAG context), the LLM answers, and the transaction is complete. One input equals one output.
An Agentic System (or an AI Agent) shifts the paradigm. Instead of answering a single prompt, an agent is given a Goal and operates across multiple steps to achieve it.
- Chatbot (Reactive): “Write a JavaScript function that parses this JSON.” → Returns one function.
- Agent (Goal-Oriented): “Turn this JSON sample into a product requirements list, a database model, and a QA test plan.” → The system automatically breaks this down into three sequential tasks, feeding the results of task 1 into task 2, and so on.
Agents bridge the gap between simple content generation and autonomous digital work.
1.2 The Agent Loop (Theory)
Fully autonomous agents (which we will build toward) operate on a cognitive loop, heavily inspired by human decision-making and control theory:
PERCEIVE → PLAN → ACT → OBSERVE → REPEAT (until goal met)
- Perceive: What is the user’s goal? What data do I have?
- Plan: Break the goal into discrete steps. (e.g., 1. Extract requirements, 2. Design DB).
- Act: Execute the first step. (In today’s lab, “Act” simply means calling the LLM API to generate text).
- Observe: Look at the result of the action. Was it successful?
- Repeat: Move to step 2, armed with the context of step 1.
1.3 Types of Agent Actions
When an agent reaches the “Act” phase, what can it actually do?
- Code / Text Generation (Today’s focus): Writing a report, synthesizing data.
- Tool Calling (Session 11): Triggering an external API (e.g., getting weather data, charging a credit card).
- File Operations: Reading/writing files to your local hard drive.
- Sub-agent Delegation: A “Manager Agent” spawns a “Researcher Agent” to find information, waits for the result, and then spawns a “Writer Agent” to draft the report.
1.4 Safeguards and the Risks of Autonomy
The more autonomy you give a system, the higher the risk of compounding errors. If step 1 hallucinates, step 2 will build upon that hallucination, and by step 4, the output is useless garbage.
Core Safeguards:
- Human-in-the-loop (HITL): Require a human to click “Approve” before the agent executes an irreversible action (like sending an email or dropping a database).
- Artifact Verification: Log every intermediate step. Do not just look at the final output.
- Scope Limitation: Strictly limit what the agent has access to via IAM roles or restricted APIs.
Part 2: Practical Labs — Delegate a Multi-Step Task
Lab 10.1 — Task Decomposition (Core)
Before writing code, pick a complex, multi-step task related to your web product. Example Scenario: “From this raw user story JSON, produce a product requirements list, sketch a REST API design, and write a test plan.”
On paper or in a blank Markdown file, write down the 4 distinct steps you would take as a human to accomplish this.
Lab 10.2 — Implement Sequential Prompting (Core)
We will build a simple Node script that executes these steps sequentially, passing the memory of the previous step into the next step.
You can use the provided kit skeleton or implement this simplified runAgentTask function:
import { GoogleGenAI } from '@google/genai';
// Assuming aiClient is initialized...
async function runAgentTask(ai, goal) {
const steps = [];
// The 'context' variable acts as the agent's memory payload
let context = `Goal: ${goal}\n\n`;
// Step 1: PLAN
console.log('Agent is planning...');
const plan = await askAi(
ai,
`${context}List 4 specific steps to achieve this goal. Number them 1 to 4.`
);
steps.push({ step: 'PLAN', output: plan });
context += `Plan:\n${plan}\n\n`; // Append the plan to memory
// Step 2: EXECUTE (A simplified loop)
for (let stepNum = 1; stepNum <= 4; stepNum++) {
console.log(`Agent is executing step ${stepNum}...`);
const output = await askAi(
ai,
`${context}Execute step ${stepNum} only. Produce complete output for this specific step.`
);
steps.push({ step: `EXECUTE_${stepNum}`, output });
context += `Step ${stepNum} output:\n${output}\n\n`; // Append output to memory
}
// Step 3: SYNTHESIZE
console.log('Agent is synthesizing final deliverable...');
const final = await askAi(
ai,
`${context}Combine all step outputs into one final, highly professional deliverable. Remove redundant text.`
);
steps.push({ step: 'SYNTHESISE', output: final });
return { steps, finalOutput: final };
}
Note: This specific for loop always runs exactly four times. This is a teaching simplification (a chained agent) to demonstrate state accumulation. It is not a true dynamic observe/stop loop.
Lab 10.3 — Verify the Agent’s Work (Core)
Run your script via the terminal:
npm run agent-task -- "From this user story JSON, produce requirements, a REST sketch, and a test plan: { user: 'admin', action: 'delete_account' }"
The Verification Task: Do not just read the final output. Read the console logs for every intermediate step.
- Did the agent stick to the plan?
- Check one factual claim made in step 2.
- Did the context get too long and confuse the model by step 4?
Document your findings in a new file in your vault: 03-Project/Agent-Notes.md.
Stretch Goal: Add a programmatic “Stop Instruction.” Modify the code so that after the PLAN step, it checks if the plan has fewer than 4 steps, and if so, it adjusts the for loop dynamically.
Key Takeaways
- Agents pursue goals across multiple steps; chatbots answer single turns.
- In this session, we built a chained LLM system, where the output of API call $N$ is appended to the context of API call $N+1$.
- State management (passing the growing
contextstring) is the fundamental mechanic of basic agent memory. - Next session, we will upgrade from chained text generation to allowing the model to request the execution of external tools.
Further Reading & Resources
- The ReAct Paper (Yao et al., 2022): Read the foundational paper on Reasoning and Acting in LLMs to understand what we are building toward next session.


