šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

AI Agents

Learn how to build autonomous loops using the ReAct framework, implement self-correcting reasoning chains, and manage multi-tool orchestration.

⚔ Total XP: 0|šŸ’» ai XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core AI logic.

Quick Quiz //

What is the primary danger of ignoring this AI concept?


šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

Listen up. If you're building modern applications, understanding AI Agents is non-negotiable. This is where simple logic turns into intelligent behavior.

1What Makes a Chatbot an 'Agent'?

A plain chatbot answers one prompt and stops. An AI Agent is a system built around an LLM that can decide, on its own, which tools to call, in what order, and when it has gathered enough information to stop and answer.

The key architectural difference is the loop: instead of one request/response pair, an agent runs the model repeatedly, feeding each tool's output back in as new context, until the model itself signals it is done.

āœ•
—
+
// Example
console.log("Running AI concept...");
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

2The ReAct Framework: Reason, Act, Observe

ReAct interleaves two phases on every turn: the model first writes out its reasoning ("I need the user's order status"), then emits an action (a tool call), and finally receives an observation (the tool's real result) before reasoning again.

Making the model verbalize its thought before acting measurably reduces wrong tool calls, because it forces the LLM to commit to an explicit plan instead of jumping straight to an action based on a shakier internal guess.

āœ•
—
+
// The ReAct Loop:
// THOUGHT: I need to find the user's order status.
// ACTION: call get_order_details(id: '123')
// OBSERVATION: Status is 'Shipped'.
// THOUGHT: I should inform the user.
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

3Chaining Tools and Recovering from Failure

A single function-calling request only ever executes one tool per turn. An agent goes further: it can chain several tool calls back to back, using the result of one call to decide the arguments for the next.

Because the tool's output (including errors) is fed straight back into the conversation, the model can see that Tool A failed and reason its way to trying Tool B instead, without any special-cased retry logic written by the developer.

āœ•
—
+
// Autonomous Recovery:
// 1. Try Tool A -> Fails
// 2. LLM reasons: 'Tool A failed, I will try Tool B.'
// 3. Try Tool B -> Success!
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

4The Agent Loop in Code

Concretely, an agent is a while loop: call the model, check whether it returned tool_calls or a plain final answer, execute any requested tools, push their results back onto the messages array, and repeat until a final answer arrives.

This loop is the entire mechanism — there is no separate 'agent runtime' beyond this repeated generate-then-execute cycle, which is why frameworks like LangGraph or the OpenAI Agents SDK are, underneath, thin wrappers around exactly this pattern.

āœ•
—
+
while (!finalAnswer) {
  const response = await ai.generate(messages);
  if (response.tool_calls) {
    const results = await executeTools(response.tool_calls);
    messages.push(...results);
  } else {
    finalAnswer = response.content;
  }
}
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

5Multi-Modal Agents

Nothing in the agent loop requires the tools to be text-only. The same reasoning-action cycle can call a vision model to describe an image, a text-to-speech tool to speak a reply, or a browser-automation tool to click a button.

Each modality is exposed to the model as just another tool with a JSON schema, so adding vision or voice to an existing agent is a matter of registering a new tool, not rewriting the loop itself.

āœ•
—
+

Status: Fully Autonomous

localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

6Short-Term vs. Long-Term Memory

Short-term memory is simply the running messages array for the current session — it disappears once the conversation ends. Long-term memory needs to survive across sessions, which is why agents typically pair it with a vector database: facts are embedded and stored once, then retrieved by semantic similarity whenever a later session needs them.

Conflating the two is a common design mistake: stuffing everything into the short-term history makes every request more expensive and eventually overflows the context window, while genuinely durable facts belong in the retrieval layer instead.

āœ•
—
+
const agentMemory = {
  history: [],
  knowledgeBase: vectorDb
};
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

7Multi-Agent Systems

A multi-agent system splits a task across several agents that each hold a narrower system prompt and a smaller toolset — for example a 'Coder' agent that only writes code and a 'Reviewer' agent that only critiques it, with the reviewer's feedback looped back to the coder.

This specialization tends to outperform one giant generalist agent on complex tasks, at the cost of extra orchestration: something has to decide which agent runs next and how to hand context between them.

āœ•
—
+
// Multi-Agent Swarm
const coder = createAgent('Coder');
const reviewer = createAgent('Reviewer');
const result = await reviewer.review(await coder.write(task));
localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

8Putting It All Together

At this point you have every building block an autonomous agent needs: a reasoning loop (ReAct), a way to act (tool/function calling), a way to recover from failure (re-planning), and a way to remember (short- and long-term memory).

The remaining work in a real system is mostly guardrails — iteration limits, cost tracking, and logging — which is exactly what the next lesson on AI Production patterns covers.

āœ•
—
+

Agency: Established

localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

9Next: Taking Agents to Production

Building an agent loop that works in a demo is the easy part. Running it safely for real users means capping how many iterations it can take, tracking token spend per session, and monitoring for infinite reasoning loops before they drain your API budget.

That operational layer — production patterns for agentic systems — is exactly where the next lesson picks up.

āœ•
—
+

Production Next

localhost:3000
Browser Preview
Execution Context
AI logic processed successfully.

10Step-by-Step Breakdown

An 'AI Agent' is more than a chatbot. It's an autonomous system that can plan, reason, and use tools to achieve a complex goal.

Agents follow the 'ReAct' framework: They Reason (think about what to do) and then Act (use a tool), then observe the result.

Unlike simple function calling, agents can chain multiple tools together. If one tool fails, the agent can 're-plan' and try a different approach.

Checkpoint: What does the 'ReAct' framework stand for in the context of AI Agents?

  • →React.js Frontend Framework
  • →Reasoning and Acting

To build an agent, you need a 'while' loop in your code that continues until the LLM decides it has reached the 'Final Answer'.

Agents can be 'Multi-Modal', using Vision to see images, Voice to speak, and Tools to act, all in a single autonomous flow.

Checkpoint: What is the main risk of an uncontrolled agent loop?

  • →Poor UI design
  • →Infinite loops that drain your API budget (always set a max iteration limit!)

Memory is critical for agents. 'Short-term' memory is the current chat history, while 'Long-term' memory often uses a Vector DB (RAG).

Multi-agent systems involve several specialized AI agents talking to each other. One agent might write code, while another reviews it.

Checkpoint: What is 'Chain of Thought' (CoT) in agentic reasoning?

  • →A way to make the model answer faster
  • →Encouraging the model to explain its reasoning steps before acting

Agency mastered! You are now capable of building self-sufficient AI systems that solve complex problems.

Next, we'll learn how to take these agents to production with 'AI Production' patterns.

Route a Real Agent Tool Call. Finish routing a user query to the right tool, the first step of an agent's ReAct loop.

Level Up šŸš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Surface Agent Actions as Live Regions

When an agent chat UI shows a tool being called ('Searching orders...', 'Booking flight...'), wrap that status text in an aria-live="polite" region so screen reader users get the same real-time feedback sighted users see from a spinner or progress indicator.

<div aria-live="polite">{currentToolStatus}</div>

SEO Implications

  • 1

    Agent Output Is Runtime-Generated, Not Crawlable

    The actual text an agent produces is generated per-user, per-session at request time and typically never touches a static, indexable route — what matters for SEO is that the documentation/tutorial page explaining the agent's architecture (this page) is itself server-rendered with real, unique prose, not that the agent's live output gets indexed.

Best Practices

Always Cap Iterations

Every agent loop needs a hard MAX_ITERATIONS ceiling (typically 5-10) independent of the model's own judgment, because a model that gets stuck reasoning in circles will otherwise keep calling the API until the process is killed or the budget is exhausted.

Log Every Tool Call and Observation

Persist the full sequence of thoughts, actions, and observations for each run, not just the final answer — when an agent produces a wrong result, the log is the only way to see which tool call or misread observation caused the derailment.

Frequent Bugs

THE BUG

The agent loop never terminates because the model keeps calling tools instead of returning a final answer.

THE FIX

Enforce a maximum iteration count in your application code (not just in the prompt) and force a plain-text final answer once the limit is hit, regardless of what the model requests next.

Real-World Examples

A Customer-Support Triage Agent

A support agent receives 'Where is my order #4521?', reasons that it needs order data, calls a get_order_status(id) tool, observes 'Shipped, arriving Thursday', and only then writes a final natural-language reply to the customer — all inside one uninterrupted loop.

while (!done) {
  const res = await llm.generate(messages);
  if (res.tool_calls) messages.push(...(await runTools(res.tool_calls)));
  else { done = true; reply = res.content; }
}

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Data Leakage

# Wrong scaler.fit(X) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) # Correct scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test)

The Solution //

Never use data from the validation or test sets to train your model. This includes fitting scalers or imputers on the entire dataset before splitting.

The Error //

Overfitting on small datasets

// Solution: Use techniques like Dropout, L2 Regularization, or Early Stopping to prevent the model from overfitting the training data.

The Solution //

Training a complex model (like a deep neural network) on a very small dataset usually leads to memorization instead of generalization. Use simpler models or apply strong regularization.

Lesson Glossary

[01]Agent

An AI system that uses an LLM to autonomously plan and execute actions.

Code Preview
Autonomous

[02]ReAct

Reasoning and Acting: Interleaving thoughts and actions to solve tasks.

Code Preview
Framework

[03]Chain of Thought

Generating reasoning steps before arriving at a final answer.

Code Preview
CoT

[04]Observation

The data returned to an agent after it executes a tool.

Code Preview
Feedback

[05]Multi-Agent System

A system where multiple AI agents collaborate on a task.

Code Preview
Swarm

[06]Final Answer

The signal that the model has completed the assigned task.

Code Preview
Exit

Continue Learning