LearnThatStack Ace your next interview

AI Agents

APIs and frameworks as of September 2026 Checked Sep 2026 4 code snippets

The model

  • An agent is a model in a loop. Each turn it calls a tool, reads the real result and picks the next step. It stops when it answers instead of calling a tool.
  • The model only asks for a tool call. Your code runs it, so validation, permissions and approval gates belong in code, not in the prompt.
  • The API remembers nothing. Your code resends the whole history every turn, and tool output fills the context window fastest.
  • The model picks the path, so steps, cost and latency change from run to run. Bound every loop with a step cap, a token budget and a deadline.
  • Build the simplest thing that works. Try one call, then a fixed workflow, then one agent. Add more agents only for a reason you can name.
Modelpicks the next stepYour codethe loop and checksToolsAPIs, files, searchPersonthe reviewerREASONhistory + toolsACTtool call args + idapprove? if riskyyes or norun it after checksOBSERVEresult or an errortool result same idDONEanswer no tool call
The loop repeats REASON, ACT and OBSERVE until the model answers without a tool call. The model never runs a tool. Your code does, after its checks.

The agent loop

what makes a system an agent

The system prompt

Say what a system prompt setsRole, scope, tool policy, when to stop, output format.
Keep it stable and smallCaching reuses a fixed prefix. Task detail goes in the user turn.

TrapIt steers but enforces nothing. Tool output can argue against it.

The reason-act-observe loop

while True: step = model(messages)reason if not step.tool_calls: return step.textan answer ends it result = run_tool(step.tool_calls)act messages += [step, result]observe
Say what makes the loop agenticThe model picks each step based on real results.
Say what ReAct isA 2022 pattern that grounds each thought in a real tool result.

TipAgents now use native tool calling instead of parsing Thought: text.

Workflow or agent

Tell a workflow from an agentA workflow's steps live in code. An agent picks its own.
Decide if a process needs an agentIs the path fixed? Do the tools exist? What does an error cost?

TipStart deterministic. Add agency only where fixed logic fails.

TrapNo reliable write API means no agent, just a demo.

Tool calling

the model asks, your code runs

One tool call, end to end

Say what tool use isThe model asks for a typed function. Your code runs it.
Say why tools are the foundationThey give fresh reads and real writes. Even memory is a tool.
Count the API calls per tool callTwo. The second resends all turns plus the tool_result.
Match a result to its callSet tool_use_id to the call's id, or the request fails.

TipOpenAI names the pieces tool_calls and role: "tool" messages.

TrapThe model decides and your code executes. Put checks in the handler.

Design the tool set

Write a tool's descriptionWhen to use it, when not to, and how it differs from similar tools.
Define its parametersTyped, with enums, few required fields and no catch-all blob.
Decide how many tools to exposeOne per decision. Past about 15 to 20, the model guesses.
Handle tools that overlapMerge them into one tool with an enum.

TipA tool definition is prompt text. When the model picks wrong, fix the wording.

TrapEvery tool definition goes out on every turn, and each is one more injection target.

MCP servers

Say what MCP isAn open standard for tools and data. M×N integrations become M+N.
Vet a third-party serverRead the source, pin a version, scope its token, alert on changes.

TipMCP standardizes discovery and transport. Tools are still function calls.

TrapTool descriptions are prompt text. A server can poison them, or change them after you approve.

Planning, reflection & RAG

how an agent plans, checks its work and looks things up

ReAct or plan-then-execute

ReAct. Best on unknown ground, like debugging and search.Decide one step at a time
Plan-then-execute. Best for known, independent steps.Write the whole plan up front
betterworse

TipMost production agents plan, execute, and replan on failure.

TrapReAct can drift and loop. Plan-then-execute can follow a stale plan.

Reflection

Say what reflection isThe agent critiques its own output, then revises it.
Know when reflection pays offWhen tests, a compiler or a schema can check the output.

TipCap it at one or two rounds, and stop once the check passes.

TrapWithout an outside check it rarely helps. A model that missed an error often misses it again.

Memory & context

what the model sees on each turn

Agent memory

Say what the model remembersNothing. Memory is text you put back in context.
Name the four kinds of memoryWorking memory, plus episodic, semantic and procedural.
Say what each long-term kind holdsEpisodic holds past runs, semantic holds facts, procedural holds how-tos.
Say what a write policy decidesWhich facts persist, when they commit and how they merge.
Store a fact that's already thereUpdate or supersede the old row. Never blind-append.

TipMost agents start with working memory plus one key-value store of user facts.

TrapThe agent reads its own writes back, so one wrong or injected fact sticks. Gate writes from tool output.

Why context runs out

Say why long runs fill the windowContext is append-only. Every tool result stays in.
Say when quality starts to dropWell before the limit. Models attend poorly to the middle.
Pick the first fixCap tool output. Return slices, IDs or counts.
Define context engineeringChoosing what fills the window on every turn.

TipThen try compaction, notes in files, subagents and retrieval.

Compaction and multi-day runs

Say what compaction doesIt summarizes old turns and keeps the recent ones as is.
Name what compaction must keepThe system prompt, tool schemas, goal, past writes and dead ends.
Run an agent over several daysUpdate a progress file after each step. Each session starts from it.

TipKeep the full transcript on disk behind a read tool.

TrapNever cut between a tool_use and its tool_result.

Subagents

Say what a subagent isA separate agent for one narrow task. Only its result comes back.
Know when to use a subagentWide read-only exploration. Keep writes on the main thread.

TipA search can burn 100k tokens inside it. The parent sees a paragraph.

TrapThe parent can't see what a subagent missed. A vague summary loses it for good.

Multi-agent systems

when to split the work, and how agents pass it on

One agent or many

Define a multi-agent systemSeveral agents, each with its own prompt, tools and window.
Say why teams start with one agentOne trace to debug, a smaller bill, no context lost in handoffs.
Know when many agents winIndependent, read-heavy subtasks with short results.
Recall Anthropic's token numbersMulti-agent research used about 15x a chat's tokens. One agent used 4x.

TipGo multi-agent only for a failure you can name.

TrapSubagents can't see each other's choices, so they duplicate work.

Supervisor or handoff

supervisorworkerworkerworker
supervisorIt sends each worker a brief and merges the results. Workers never talk to each other.
triagerefundsuser
handoffTriage passes the conversation on. Refunds answers, and Triage never resumes.
Describe the supervisor patternOne orchestrator briefs workers and merges their results.
Name where a supervisor breaksLossy briefs, gaps, a flooded context, unchecked results.
Say what an OpenAI SDK handoff isA transfer_to_<agent> call. The new agent owns the rest of the turn.
Pick a handoff or an agent as a toolHand off so one agent owns the rest. Use as_tool to merge results.

TipHave workers return a fixed shape, never a raw transcript.

TrapA worker knows only its brief. Gaps in it produce confident, wrong work.

Workflow patterns

Run known steps in orderPrompt chaining. Each output feeds the next step.
Send each input to a specialistRouting. Classify first, then pass it on.
Fan out and mergeParallelization. Split into sections, or run it several times and vote.
Loop until the output passesEvaluator-optimizer. A generator and a critic take turns.

TipYour code holds the control flow, so you can test and trace it.

TrapPeer networks that pass control freely are hard to trace. Use them last.

Frameworks & SDKs

what each one gives you, and when to skip them

Pick a framework, or none

Resume long runs after a crashLangGraph. A state graph that checkpoints every step.
Demo role-based agents fastCrewAI. You write roles and tasks. The loop is implicit.
Build agents on .NET and AzureMicrosoft Agent Framework, successor to AutoGen and Semantic Kernel.
Know when to skip a frameworkOne loop, a few tools and one model provider.

TipWithout a framework, you write retries, tracing and checkpoints yourself.

TrapMCP and A2A are protocols, not frameworks. Any framework can speak them.

OpenAI and Claude agent SDKs

Name the OpenAI SDK's building blocksAgents, tools, handoffs, guardrails and sessions, run by Runner.
Run an agent with saved historyawait Runner.run(triage, "where is my refund?", session=session)
Say what the Claude Agent SDK addsThe agent loop, file and Bash tools, subagents, hooks and compaction.
Know when to use the raw API insteadFor your own loop or state store, or another language.

TipAn OpenAI handoff swaps the active agent inside one run, with one history and trace.

TrapThe Claude Agent SDK owns the loop. Custom control flow or your own checkpoints fight it.

Failures & recovery

keep a run from looping, repeating or dying

Classic failure modes

Name the classic failure modesGoal drift, doom loops, context rot, silent success, duplicate writes and injection.
Catch silent successRead the real state back. Never trust the agent's report.

TipAt 2% error per step, over half of 40-step runs fail.

TrapSilent success looks green in the logs. Grade the final state, not the transcript.

A failing tool call

Handle bad arguments or a missing recordReturn a tool_result with is_error: true so the model can adjust.
Handle timeouts, 429 and 5xx errorsRetry with backoff in the tool wrapper. The model never sees them.
Write the error messageWhat failed, why, and what to try next.

TipCap attempts per tool, then report the failure honestly.

Stop endless loops

Set hard budgetsMax steps, a deadline and a token cap, enforced outside the model.
Catch a loop that makes no progressHash each tool call with its arguments. On a repeat, nudge the model.
Handle a run that hits its budgetForce a final answer, return the partial work and flag it for a human.

TipLangGraph has recursion_limit. The OpenAI SDK has max_turns.

TrapThe usual cause is a tool that fails softly, with an empty list or a vague error.

Idempotent tools

Say why tools must be idempotentTimeouts, crashes and resumed runs repeat calls. A repeat must not charge twice.
Make a write safe to retrySend an idempotency key. A dedupe store replays the first result.

TrapStore the key durably, or a restart mints a new one and charges again.

Long runs and resumable streams

Survive crashes, deploys and restartsCommit the run's state after every step, so any worker can resume it.
Replay a step safely after a crashSave the model's reply before its tools run. Key writes by tool call id.
Resume a dropped streamNumber every event in a log. The client replays from the last one it saw.

TipTemporal, Restate and LangGraph checkpointers do this for you.

TrapDon't hold one HTTP request open for an hour. Return a run id.

Guardrails & security

limit what a wrong or hijacked run can do

Human approval gates

Define human-in-the-loopThe agent pauses at a tool call and waits for approve, edit or reject.
Know which calls need approvalHard to undo or outward-facing, like payments or deletes.
Enforce the gateIn your executor, not the prompt. A model told to ask can skip it.

TipGate each call. One approval never covers the next step.

TrapGate everything and reviewers approve without reading.

Guardrails

Place guardrails in the loopInput, every tool call, output, and caps across the run.
Pick the check that matters mostThe tool call. Every side effect goes through one.

TipFail closed on writes. A prompt instruction isn't a guardrail.

TrapEvery guardrail is a classifier. Track false positives, or teams switch it off.

Sandbox and credentials

Isolate tool codeA container or microVM with a read-only disk and no network by default.
Keep credentials out of the sandboxA proxy injects a short-lived token into each call.
Decide whose permissions applyThe end user's, not the agent's, or you build a confused deputy.
Give an agent production accessThe agent never holds one. A broker mints a short-lived, scoped token per task.

TipTreat each tool call as a request, not a decision. Log the policy decision too.

TrapA raw SQL or shell tool leaves the blast radius to the prompt. Narrow typed tools put it in the signature.

Prompt injection

Define prompt injectionText the agent reads carries instructions, and the model follows them.
Name the lethal trifectaPrivate data, untrusted content and a way to send data out.
Mitigate prompt injectionBreak one leg with controls outside the model. No prompt wording fixes it.

TipAssume some injections land. Keep the blast radius small.

TrapAn allowlisted domain can still leak data through a query string.

Evals, tracing & cost

prove it works, see why it failed, and cap the bill

Evaluate an agent

Say how agent evals differGrade the end state, not the exact path. A shorter route should pass.
Report reliability honestlyRun each case n times. pass^k needs all k to pass.
Build a test bed that repeatsA frozen sandbox with recorded tool responses and a fixed database.
Use an LLM judgeOnly for open-ended text, calibrated against human labels.

TipTurn sampled production traces into new cases, and gate deploys on them.

TrapA mean score hides an agent that works 3 times in 5.

Agent benchmarks

Measure fixing real GitHub issuesSWE-bench Verified. Hidden tests must pass.
Measure tool use with a simulated usertau-bench. It checks the final database state and policy rules.
Measure function-calling accuracyBFCL, across parallel and multi-step calls.
Measure web and desktop useWebArena for web tasks. OSWorld for a real desktop.

Trappass@1 hides variance, and scores shift with the tools and retries.

Trace an agent in production

Say what a trace holdsOne run, with a span per model call and tool call.
Make traces portableEmit OpenTelemetry GenAI spans. Langfuse and LangSmith can read them.
Pick the online signalsSuccess rate, tool errors, steps and cost per run.

TipA rising step count is the earliest sign of looping, so alert on it.

Cost and latency

Say what drives cost and latencyCost tracks tokens. Latency tracks sequential model calls.
Cut the cost of every turnCache the fixed system-and-tools prefix.
Cut cost and latency togetherSend routine steps to a small model, and cap steps and tokens.

TipStreaming removes no work. It only feels faster.

TrapMeasure per trajectory. A cheap model that needs 3 extra turns costs more.

Computer & browser agents

agents that click and type like a person

Computer-use agents

Say how a computer-use agent worksIt reads a screenshot and clicks or types at pixel coordinates.
Know when to use oneOnly when no API exists. Run it in a sandboxed VM.
Estimate a 40-step task's successAbout 13% at 95% per step. Errors compound.

TipTarget elements from the accessibility tree where you can.

TrapGUI actions aren't idempotent. A blind retry can submit a form twice.

DOM or vision browser agents

A DOM agent reads the HTML. Canvas and iframes break it.Act on the page's elements
A vision agent clicks on pixels. Layout and scroll changes throw it off.Act on screenshots
yesnobreaks

TipMost stacks mix them. The DOM picks the target and a screenshot confirms it.

TrapAny page in your logged-in session can steer it. Use a throwaway profile.

Found this useful? Pass it on.
Pro · $10/mo

This sheet stays free. With Pro, you can:

  • Every answer on this sheet. Read the full answer to all 54 questions it links, not just the 7 free ones.
  • My sheet. The cards you star and the ones you miss in Quiz me, from every sheet, on one page to quiz and print.
  • PDFs. Download this sheet and My sheet, laid out for A4, with every question a link to its answer.
  • The rest of Pro. Every answer in the question library, and 1,000 AI credits a month.