Overview
An AI agent is a system where an LLM decides what to do next in pursuit of a goal. A chatbot answers one message at a time. An agent takes a goal such as "find the three cheapest flights and put them in a spreadsheet", then loops through thinking, calling tools, observing the results, and deciding the next step until the goal is met or it gives up.
An agent has four parts: a model that reasons, tools it can call (APIs, search, code execution, databases), memory of what has happened so far, and a control loop with limits. The engineering challenge is less about intelligence and more about reliability: bounding cost and steps, validating tool inputs, handling failures, asking a human before risky actions, and tracing every decision.
You give an assistant a goal, a phone (tools), and a notebook (memory). They decide who to call, write down what they learn, adjust the plan, and report back. A good manager also sets rules such as "ask me before spending more than 100 dollars", which is the guardrail layer of an agent.
When to use it
- Tasks that need several steps whose order is not known in advance.
- Workflows that combine reading information and taking actions across systems.
- When a fixed pipeline cannot cover the variety of user requests.
Where it shows up in interviews
Recognize it when: the user gives an outcome rather than a single question.
- Design an AI agent
- Design AI Agent Platform
Recognize it when: the agent can change real data or spend money.
- Design an AI customer-support system
- Design a multi-agent system
Where it is used in real software
Read a repository, edit files, run tests, and iterate until the tests pass.
Look up an order, check the refund policy, and issue a refund within set limits, escalating otherwise.
Plan searches, read sources, and compile a cited report.
Key terms
- Tool
- A function the agent can call, described by a name, purpose, and input schema.
- Agent loop
- The repeated cycle of reason, act, observe until done.
- Memory
- Short-term conversation state plus optional long-term stored facts.
- Guardrail
- A rule or check that limits what the agent may do.
- Human in the loop
- Requiring human approval before certain actions.
How it works, step by step
- 1Receive a goal
The user states an outcome, along with context such as their identity and permissions.
- 2Reason about the next step
The model reviews the goal, memory, and available tools, then picks an action.
- 3Call a tool
The runtime validates the arguments and executes the tool with the user's permissions.
- 4Observe and update memory
The tool result is added to the conversation so the model can use it.
- 5Repeat or finish
Loop until the model returns a final answer, a step limit is hit, or a human must approve.
STEP 1Goal: "Refund order 4821 if it qualifies."
Chatbot vs workflow vs agent
Three ways to handle "Refund my order 4821".
| Approach | Who decides the steps | Handles unusual cases |
|---|---|---|
| Chatbot | Nobody and it only replies | No |
| Fixed workflow | Developer in code | Only the ones coded |
| Agent | LLM within limits | Yes, by choosing tools dynamically |
NOWApproach: Chatbot | Who decides the steps: Nobody and it only replies | Handles unusual cases: No
Use a fixed workflow when steps are known; use an agent when requests vary widely.
Implementation
import OpenAI from "openai";const openai = new OpenAI(); const tools = { getOrder: async ({ id }: { id: string }) => orders.find(id), issueRefund: async ({ id, amount }: { id: string; amount: number }) => { if (amount > 200) return { status: "needs_human_approval" }; // guardrail return payments.refund(id, amount); },}; const toolSpecs = [ { type: "function" as const, function: { name: "getOrder", description: "Look up an order", parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, { type: "function" as const, function: { name: "issueRefund", description: "Refund an order", parameters: { type: "object", properties: { id: { type: "string" }, amount: { type: "number" } }, required: ["id", "amount"] } } },]; export async function runAgent(goal: string, maxSteps = 6) { const messages: OpenAI.ChatCompletionMessageParam[] = [ { role: "system", content: "You are a support agent. Use tools. Follow refund policy." }, { role: "user", content: goal }, ]; for (let step = 0; step < maxSteps; step++) { const res = await openai.chat.completions.create({ model: "gpt-4o-mini", messages, tools: toolSpecs }); const msg = res.choices[0].message; messages.push(msg); if (!msg.tool_calls?.length) return msg.content; // final answer for (const call of msg.tool_calls) { const fn = tools[call.function.name as keyof typeof tools]; const result = await fn(JSON.parse(call.function.arguments)); messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) }); } } return "Stopped: step limit reached.";}Complexity and performance
Typical tasks take 2 to 10 steps.
Each call resends the conversation so far.
Trade-offs
More autonomy handles more cases but increases risk. Limit tools, add approval for irreversible actions, and scope permissions to the user.
Deterministic workflows are cheaper and testable. Agents handle variety at the cost of predictability.
Variants and related techniques
Interleave written reasoning with tool calls.
Write a full plan first, then execute steps, re-planning on failure.
Several specialized agents collaborate, such as a planner, a researcher, and a reviewer.
Common mistakes
- Giving the agent broad credentials.
Fix: Run tools with the requesting user's permissions and least privilege.
- No step, token, or time limits.
Fix: Cap all three and return a clear partial result when a cap is hit.
- Trusting tool output blindly.
Fix: Treat retrieved text as untrusted input because it may contain prompt injection.
Interview questions
What is the difference between a chatbot and an AI agent?
A chatbot produces a reply to each message. An agent pursues a goal across multiple steps, choosing and calling tools, observing results, and deciding what to do next until the goal is complete.
How do you make an agent safe to take real actions?
Least-privilege tools scoped to the user, validated tool arguments, limits on steps and spending, human approval for irreversible actions, prompt-injection defenses on tool outputs, and full tracing for audit.
Practice problems
| Problem | Difficulty | What it trains |
|---|---|---|
| Build a two-tool agent with a step limit | Easy | The agent loop. |
| Design a support agent that can issue refunds safely | Hard | Guardrails and approvals. |