AI Agent Fundamentals

Everything you need to reason about agents from first principles — before any framework gets involved.

What is an AI agent?

An AI agent is a system in which a language model decides the control flow: it chooses which action to take next (call a tool, ask a question, answer, hand off), observes the result, and repeats until the goal is met. That loop is what separates an agent from a single LLM call or a fixed pipeline.

LevelWho decides the next step?Example
Single LLM callNobody — one shotSummarise this email
Chain / workflowThe developer (hard-coded)Extract → translate → classify
RouterLLM picks one branchSend the query to billing or tech-support prompt
Agent (tool loop)LLM, repeatedlyLook up order → check policy → issue refund → reply
Multi-agentSeveral LLMs coordinateSupervisor delegates to researcher + writer + reviewer
Rule of thumbUse the simplest level that solves the problem. Workflows are cheaper, faster and more predictable. Reach for an agent when the number or order of steps genuinely can't be known in advance.

Anatomy of an agent

The agent loop, without a framework

Write this once by hand. Every framework — LangGraph, CrewAI, the OpenAI Agents SDK, the Claude Agent SDK — is a more robust version of these ~40 lines.

import json
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

def get_weather(city: str) -> str:
    return json.dumps({"city": city, "temp_c": 21, "sky": "clear"})

TOOLS = [{
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
}]
REGISTRY = {"get_weather": get_weather}

def run(user_msg: str, max_steps: int = 8) -> str:
    messages = [{"role": "user", "content": user_msg}]
    for _ in range(max_steps):                      # guardrail: bounded loop
        resp = client.messages.create(
            model="claude-sonnet-5-5", max_tokens=1024,
            tools=TOOLS, messages=messages,
        )
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":          # model is done
            return "".join(b.text for b in resp.content if b.type == "text")

        results = []
        for block in resp.content:
            if block.type == "tool_use":
                out = REGISTRY[block.name](**block.input)   # act
                results.append({"type": "tool_result",
                                "tool_use_id": block.id, "content": out})
        messages.append({"role": "user", "content": results})  # observe
    return "Stopped: step limit reached."

print(run("Should I bring an umbrella in Paris today?"))

Notice the three ingredients: reason (model call), act (execute tool), observe (append result) — repeated with a hard stop.

Tool calling in depth

The model never executes anything. It emits a structured request (name + JSON arguments); your code validates and runs it, then returns the result as a message.

Designing good tools

MCP — Model Context Protocol

MCP is an open protocol for exposing tools, resources and prompts to any compatible agent through a standard client/server interface (stdio or HTTP). Instead of writing a bespoke integration per framework, you run an MCP server once (e.g. GitHub, Postgres, Slack) and any MCP-capable agent can use it. LangGraph consumes MCP tools via the langchain-mcp-adapters package.

Reasoning & planning patterns

PatternHow it worksGood for
ReActInterleave Thought → Action → Observation until done.General tool use; the default.
Plan-and-ExecutePlanner writes a step list; executor runs steps; optional re-plan.Long tasks; cheaper executor models.
Reflection / Self-critiqueGenerate → critique → revise loop.Writing, code, quality-sensitive output.
RoutingClassify input and send to a specialised prompt/agent.Support desks, triage.
ParallelisationFan-out independent sub-tasks, then aggregate (map-reduce).Research, multi-document analysis.
Evaluator–OptimizerOne LLM proposes, another grades against criteria.Translation, search refinement.

Modern models also expose built-in extended thinking / reasoning modes. These improve multi-step planning inside a single call, but you still need the outer loop for acting in the world.

Memory

Managing the context window

RAG and agentic RAG

Retrieval-Augmented Generation grounds the model in your data: chunk documents → embed → store in a vector DB → at query time retrieve the top-k similar chunks → put them in the prompt.

Agentic RAG exposes retrieval as a tool. The agent decides whether to search, rewrites the query, grades retrieved documents for relevance, and searches again if needed. This handles multi-hop questions that one-shot RAG can't.

Quality levers
  • Chunking strategy (size, overlap, structure-aware splitting)
  • Hybrid search (BM25 keyword + vector) and a reranker
  • Metadata filters (tenant, date, product)
  • Query rewriting / decomposition
  • Citations in the answer so users can verify

Multi-agent systems

ArchitectureDescriptionTrade-off
SupervisorA coordinator LLM routes work to specialist agents and composes the result.Clear control; supervisor can bottleneck.
HierarchicalSupervisors of supervisors.Scales to big tasks; more latency/cost.
Network / swarmAgents hand off to each other directly.Flexible; harder to debug.
Agent-as-toolA sub-agent is wrapped and called like a tool.Simple, encapsulated context.

Why split into multiple agents? Focused prompts, smaller toolsets per agent, isolated context windows, independent testing, and the option to use different models per role. Why not? Every hop adds latency, tokens and failure modes. Start with one agent.

Guardrails & safety

Evaluation & observability

Framework landscape

FrameworkStyleNotes
LangGraphLow-level graph / state machineExplicit control flow, checkpointing, HITL, streaming. Our focus.
LangChainComponents & high-level agentModel/tool integrations; its agents run on LangGraph.
Claude Agent SDKAgent harnessSame harness as Claude Code: tools, MCP, subagents, file system.
OpenAI Agents SDKLightweight agents + handoffsGuardrails and tracing built in.
Google ADKAgent Development KitIntegrates with Vertex AI Agent Engine.
CrewAI / AutoGenRole-based multi-agentFast prototypes of agent teams.
LlamaIndexData/RAG-centricStrong document ingestion and retrieval.
Interview angleBe ready to explain the agent loop on a whiteboard, justify agent vs. workflow for a given use case, and list concrete guardrails. See the Q&A bank.