What is an AI agent?
An AI agent is an LLM-powered system that can reason, plan, and take actions - calling tools, browsing the web, running code, or reading files to accomplish a goal autonomously.
AILLMAgents
Overview
A basic LLM takes text in and returns text out - one call, done. An AI agent wraps that LLM in a loop: reason about what to do, take an action (call a tool, search the web, run code), observe the result, reason again, take another action - repeating until the goal is achieved. Agents enable autonomous multi-step tasks that a single prompt cannot complete.
Key Points
- •The core loop: **Plan → Act → Observe → Repeat**. The model reasons about what to do next, executes a tool, sees the result, and repeats.
- •Agents use **tools** (functions the model can call): web search, code execution, file reading, API calls, database queries.
- •Common agent patterns: **ReAct** (Reason + Act), **Plan-and-Execute**, **Reflexion** (self-critique).
- •Agents are non-deterministic - the same input can take a different path. This makes them powerful and unpredictable.
- •Reliability decreases with task complexity - each action step has a chance of failure that compounds.
- •Human-in-the-loop (HITL): for consequential actions (send email, delete file, place order), require human approval before execution.
Examples
Minimal ReAct agent from scratch
typescriptconst tools = {
search: async (query: string) => await webSearch(query),
calculate: (expr: string) => eval(expr).toString(), // simplified
readFile: async (path: string) => await fs.readFile(path, 'utf8'),
};
const SYSTEM = `You are a helpful agent. You have access to these tools:
- search(query): search the web
- calculate(expr): evaluate a math expression
- readFile(path): read a local file
To use a tool, output exactly:
TOOL: toolName
INPUT: the input to the tool
When you have the final answer, output:
ANSWER: your final answer`;
async function runAgent(userGoal: string, maxSteps = 10): Promise<string> {
const messages = [
{ role: 'system' as const, content: SYSTEM },
{ role: 'user' as const, content: userGoal },
];
for (let step = 0; step < maxSteps; step++) {
const response = await client.chat.completions.create({
model: 'gpt-4o', temperature: 0, messages,
});
const text = response.choices[0].message.content ?? '';
messages.push({ role: 'assistant', content: text });
if (text.includes('ANSWER:')) {
return text.split('ANSWER:')[1].trim(); // done
}
const toolMatch = text.match(/TOOL: (\w+)\nINPUT: (.+)/s);
if (toolMatch) {
const [, toolName, input] = toolMatch;
const result = await tools[toolName as keyof typeof tools](input.trim());
messages.push({ role: 'user', content: `OBSERVATION: ${result}` });
}
}
throw new Error('Agent exceeded max steps');
}OpenAI function calling for structured tool use
typescriptconst tools = [
{
type: 'function' as const,
function: {
name: 'get_weather',
description: 'Get current weather for a city',
parameters: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' },
units: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['city'],
},
},
},
];
const response = await client.chat.completions.create({
model: 'gpt-4o',
tools,
messages: [{ role: 'user', content: 'Is it warm enough for a BBQ in Berlin today?' }],
});
const msg = response.choices[0].message;
if (msg.tool_calls) {
const call = msg.tool_calls[0];
const args = JSON.parse(call.function.arguments); // { city: 'Berlin', units: 'celsius' }
const weather = await getWeather(args.city, args.units);
// Send tool result back to the model
const final = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'Is it warm enough for a BBQ in Berlin today?' },
msg, // the assistant's tool_call message
{
role: 'tool',
tool_call_id: call.id,
content: JSON.stringify(weather),
},
],
});
console.log(final.choices[0].message.content);
}Pro Tip
Design agents for narrow, well-scoped tasks. Broad goals ("be my personal assistant") lead to unreliable agents; narrow goals ("search the web for today's AAPL stock price and format it as JSON") work well. Always set a max-steps limit, log every action and observation, and default to requiring human approval for irreversible actions like sending emails or modifying files.