AI & Data
Build LLM agents that plan, call tools, remember and stay safe — from the raw loop to MCP and frameworks.
A path for developers building agents on top of large language models: model basics and generation controls, the agent loop, prompting, tool design and the Model Context Protocol, memory, common architectures, building by hand or with frameworks, evaluation, observability and security. It assumes you can already build a small backend service. Each subject links official documentation or the original paper.
The subjects follow the roadmap.sh AI Agents roadmap.
An agent is mostly ordinary backend code wrapped around model calls: HTTP handlers, JSON parsing, environment config, queues and a database for state. Be comfortable writing and deploying a small service in Python or TypeScript before adding an LLM to it.
You will install SDKs, run local model servers, read logs and let agents edit code — all from a shell, all under version control. Committing before an agent touches files gives you a cheap undo.
Every hosted model is reached through an HTTP API, and most tools an agent calls are REST endpoints too. Know methods, status codes (especially 429 and 5xx), headers for auth and idempotency, and JSON request bodies.
Large language models are transformers trained to predict the next token, then tuned to follow instructions and use tools. You do not need the maths to build agents, but knowing they generate token by token from a fixed context explains most of their strengths and failure modes.
Text is split into sub-word tokens before the model sees it; limits and prices are counted in tokens, not characters. Non-English text and code often use more tokens per word, and different models use different tokenizers.
The maximum number of tokens — system prompt, history, tool results and the reply — a model can attend to in one call. Long windows are expensive and recall degrades in the middle, so agents must decide what to keep in context.
Sampling parameters shape how the next token is chosen and when generation stops. For agents, low randomness and tight limits usually beat creativity; supported parameters differ by provider and some reasoning models ignore or reject them.
Scales the probability distribution before sampling: near 0 picks the most likely tokens almost every time, higher values flatten it for more variety. Use low values for tool calls and extraction.
Nucleus sampling keeps only the smallest set of tokens whose probabilities add up to p, then samples among them. Adjust either temperature or top-p, not both at once.
Lowers a token's score in proportion to how often it has already appeared, reducing verbatim repetition. Offered by OpenAI-style APIs; too high a value makes output avoid necessary words.
A flat penalty applied once a token has appeared at all, nudging the model towards new topics rather than restating old ones. Rarely needed for agent work.
Generation ends at an end-of-turn token, a custom stop sequence, the token limit or a tool call. Always check the returned stop reason — a reply cut off by the length limit is incomplete JSON waiting to break your parser.
The cap on output tokens per call (max_tokens or max_output_tokens). It bounds cost and latency; reasoning tokens may count against it, so leave headroom for thinking models.
A streamed response arrives as server-sent events, token by token, so users see progress and you can cancel early; an unstreamed one returns the whole message at once and is simpler to handle. Agents usually stream to the user but parse tool calls only after the full block is assembled.
Reasoning models spend extra hidden or summarised "thinking" tokens before answering, which helps with planning, maths and multi-step tool use at the cost of latency and price. Standard models answer directly and are better for fast, simple steps — many agents mix both.
Prompting changes behaviour instantly and costs nothing to iterate; fine-tuning trains weights on examples to lock in a style, format or narrow skill. Exhaust prompting, examples and retrieval first — fine-tuning cannot add fresh knowledge reliably and must be redone for new base models.
An embedding model maps text to a vector so that similar meanings land close together; vector search finds the nearest stored vectors to a query using cosine similarity and approximate indexes like HNSW. It powers retrieval, deduplication and semantic memory for agents.
Retrieval-augmented generation fetches relevant documents at query time and puts them in the prompt so answers are grounded in your data. The pipeline is chunk, embed, store, retrieve, optionally rerank, then generate with citations; most quality problems are retrieval problems.
Models whose weights you can download and run yourself — Llama, Mistral, Qwen, Gemma, DeepSeek and others — under licences that vary from permissive to restrictive. They give you privacy, offline use and fine-tuning control, in exchange for hosting work and usually weaker tool use than frontier APIs.
Frontier models such as Claude, GPT and Gemini, available only through vendor APIs. They are usually the strongest at tool use and long tasks and need no infrastructure, but you depend on the vendor's pricing, rate limits, data policies and deprecation schedule.
Hosted models charge per million input and output tokens, with output several times dearer, and cheaper rates for cached input and batch jobs. Agents loop and resend history, so cost grows faster than for chat — estimate per task, not per call.
Cost = input tokens × input rate + output tokens × output rate, plus thinking and tool-result tokens. Prompt caching of a stable system prompt and tool list can cut repeated input cost sharply.
An agent is an LLM running in a loop: read the situation, decide on an action, call a tool, look at the result, and repeat until the goal is met or a limit is hit. Everything else — memory, planning, guardrails — is added around this loop.
Systems where a model decides its own next steps and tool calls instead of following a fixed script. Use them when the path cannot be known in advance; use a simple workflow when it can.
Functions your code exposes to the model with a name, description and JSON Schema for arguments. The model only asks for a call; your code runs it and returns the result as a message.
Everything the agent observes at the start of a turn: the user's request, attached files or images, system state and prior context. Normalise and validate it before it reaches the model.
The model interprets the goal and decides what to do next — answer, ask a clarifying question or call a tool — sometimes writing an explicit plan first for longer tasks.
Your runtime validates the requested arguments against the schema, checks permissions, executes the tool with a timeout and captures output or errors to send back.
The tool result is appended to the conversation and the model judges whether it worked and what to do next. Clear, concise error messages from tools let the model recover instead of looping.
Agents earn their keep where tasks are open-ended, need several tools and can be checked: coding, research, data work and operations. Look for problems with clear success criteria and a human who can review the result.
Agents that read and act on email, calendars, documents and to-do lists. The hard parts are permissions, confirming irreversible actions and resisting instructions hidden in incoming content.
Coding agents read a repository, edit files, run tests and iterate on failures. Tests and type checkers give them a fast, objective feedback signal, which is why this use case works so well.
Agents that write and run SQL or Python in a sandbox, inspect results, and produce charts or summaries. Executing code beats asking the model to do arithmetic in its head.
Agents that browse or fetch pages, extract structured data and follow links. Use a headless browser for dynamic sites, respect robots.txt and rate limits, and treat page text as untrusted input.
Game characters with memory, goals and dialogue driven by an LLM, able to plan daily routines and react to the player. Latency and cost limit how many can run at once.
Designing the instructions, context and examples a model receives so it reliably does the right thing. For agents this covers the system prompt, tool descriptions and how results are formatted — and it is an empirical loop of writing, testing and revising.
State the task, audience, constraints and what a good result looks like. Models follow instructions literally — "summarise in three bullets for an engineer" beats "summarise this".
Explain why a rule exists and include the background the model cannot know: domain facts, the user's situation, relevant documents. Separate context from instructions with tags or headings.
Precise domain vocabulary — "idempotent", "p95 latency", "ISO 8601" — activates the right knowledge and removes ambiguity that plain wording leaves open.
A few diverse input–output examples (few-shot prompting) teach format and edge cases faster than descriptions. Vary them so the model does not copy one example's quirks.
Build a small test set of real inputs with expected outputs, change one thing at a time and rerun it. Without evals, prompt edits that fix one case silently break others.
Ask for exact structure: word limits, JSON matching a schema, Markdown or none. For machine consumption, prefer the API's structured-output or tool-call features over asking nicely for JSON.
Asking the model to work through intermediate steps before the final answer improves accuracy on multi-step problems. With reasoning models this happens natively; with standard models, request step-by-step reasoning in a separate tag you can strip from the output.
Generates several candidate reasoning steps, scores them and searches the resulting tree (breadth- or depth-first), backtracking from dead ends. It helps on puzzles and planning problems at the price of many more model calls.
A tool is a name, a description and an input schema, and the model sees only those. Write the description like documentation for a new colleague: what it does, when to use and not use it, what each argument means, what errors look like, with a short example.
The common tool families an agent uses to see and change the world. Each carries its own risks, so scope permissions per tool rather than per agent.
Returns fresh results with URLs so the agent can answer beyond its training cutoff and cite sources. Provider-hosted search tools exist, or wrap a search API yourself.
Runs model-written code in an isolated sandbox and returns stdout, errors and files. Indispensable for maths and data work; never run it on the host machine.
Lets the agent answer questions from your data via SQL. Use a read-only role, row limits and statement timeouts, or expose narrow parameterised queries rather than free-form SQL.
Wraps internal or third-party HTTP APIs as tools. Keep credentials in your runtime, not the prompt, and return trimmed, relevant fields instead of raw payloads that waste context.
Messaging tools let agents notify people or act for them. Sending is irreversible, so require confirmation or a draft step, and rate-limit to avoid spamming.
Read, write, list and search files — the core of coding agents. Restrict access to an allowed directory, block path traversal and keep work in version control so changes are reviewable.
An open protocol, built on JSON-RPC, that standardises how applications give models access to tools, resources and prompts. Write an integration once as an MCP server and any MCP-capable app — IDEs, desktop assistants, agent frameworks — can use it.
The user-facing application, such as an IDE or chat app, that runs the model, manages connections to servers and decides which tools and data the model may use.
The component inside a host that keeps a one-to-one connection with a single server, negotiates capabilities and relays tool calls and results.
Programs that expose tools (actions), resources (readable data) and prompts (templates) over the protocol, wrapping things like GitHub, a database or the local file system.
Official SDKs in TypeScript, Python and other languages let you declare tools with schemas and handlers in a few lines. Test with the MCP Inspector, keep tool outputs small, and validate every input because the caller is a model.
The host launches the server as a child process and talks over stdio. Simple and private — ideal for file system or local tool access — but each user installs and runs it themselves.
The server runs as a web service using the Streamable HTTP transport, shared by many users. It needs proper authorisation (OAuth 2.1 in the spec), tenant isolation and rate limiting.
Models are stateless between calls, so anything an agent "remembers" is data your code stores and puts back into context. Memory design is about deciding what to keep, where to keep it, and what to retrieve for each step.
The current conversation and scratch state held in the context window for this task. It vanishes when the session ends and must be trimmed as it approaches the window limit.
Information persisted across sessions in a database, vector store or files, and retrieved when relevant. Needs rules for what is worth saving and a way to correct stale facts.
Episodic memory records specific past events ("last Tuesday the deploy failed because…"); semantic memory stores general facts ("the user prefers TypeScript"). Agents use episodes as examples and facts as context.
Memory grows without bound unless managed. Techniques for storing, compressing and forgetting keep context relevant, costs flat and private data from lingering longer than it should.
Store memories as embeddings with metadata and retrieve the most similar ones per step. Postgres with pgvector is often enough; dedicated stores like Qdrant or Chroma add scale and filtering features.
Structured, per-user facts and preferences kept in an ordinary database table or document and injected into the system prompt. Let users view and delete what is stored.
Replace old turns with a running summary, or clear stale tool results, so long sessions fit the window. Summaries lose detail, so keep key facts and decisions explicitly.
Score memories by recency, importance and relevance, decay old ones and delete what is outdated or past its retention period. Forgetting also limits privacy exposure.
Recurring patterns for arranging model calls and tools. Start with the simplest one that works — often a single loop with good tools — and add structure only when you can measure the benefit.
An agent that treats retrieval as a tool: it decides when to search, rewrites queries, reads results and searches again if needed, instead of one fixed retrieve-then-answer pass.
Interleaves a reasoning step, an action and the observation in a loop. It is the pattern behind most tool-calling agents today, now implemented with native tool calls rather than text parsing.
One call writes a step-by-step plan, then cheaper calls or workers execute each step, with re-planning when a step fails. Saves cost on long tasks and makes progress visible.
Tasks represented as a directed acyclic graph of steps with dependencies, so independent steps run in parallel and results flow to later nodes. Graph frameworks like LangGraph model this directly.
Several specialised agents — a researcher, a coder, a reviewer — coordinated by an orchestrator or by passing messages. Useful for broad parallel work, but they multiply cost and make failures harder to trace.
The agent drafts an answer, critiques it against criteria or test results, and revises. Works best with an external signal such as failing tests; pure self-review can confirm its own mistakes.
Building the loop yourself with direct API calls: send messages and tool schemas, parse tool-use blocks, run tools, append results and repeat with a step limit. Handle 429 and 5xx with exponential backoff and jitter. A hundred lines teach you what every framework hides.
Providers let you pass tool schemas with the request and return structured tool calls instead of free text, so you no longer parse JSON out of prose. The shapes differ slightly between vendors, which is why thin abstraction layers exist.
Pass tools with JSON Schema parameters; the model returns function calls with arguments, and you send results back. strict mode guarantees arguments match the schema.
OpenAI's earlier stateful API with assistants, threads and runs managed server-side. It has been deprecated in favour of the Responses API, so learn it only to maintain or migrate existing code.
Declare functionDeclarations in the request; Gemini returns functionCall parts, supports parallel calls and modes that force or forbid calling. The Python SDK can call functions automatically.
Define tools with input_schema; Claude replies with tool_use content blocks and you answer with tool_result blocks. Server tools such as web search and code execution run on Anthropic's side.
Frameworks provide loops, tool abstractions, memory, retrieval and multi-agent orchestration out of the box. They speed up prototypes but add abstraction and churn — understand the manual loop first so you can debug what they do.
A large Python and JavaScript library of model wrappers, tool integrations, retrievers and an agent API. Huge ecosystem; its abstractions change often, so pin versions.
A lower-level library for agents as stateful graphs: nodes, edges, checkpoints and human-in-the-loop interrupts. Good when you need explicit control over flow and durable state.
Focused on connecting models to data: loaders, indexing, retrieval and query engines, plus agent workflows on top. A strong choice for document-heavy RAG agents.
deepset's framework for composable pipelines of components — retrievers, rankers, generators and agents — with an emphasis on production search and RAG.
Multi-agent orchestration around roles, goals and tasks: define a crew of agents and how they hand work to each other, sequentially or under a manager.
Microsoft's framework for multi-agent conversations, where agents exchange messages and can run code; its newer releases use an event-driven, asynchronous core.
A lightweight Python framework for agents with memory, knowledge and tools, plus teams of agents, aiming for fast startup and simple code.
A minimal, file-based way to package a small agent from the smol-ai community. Niche — worth a look for how little scaffolding an agent really needs.
Agents are non-deterministic and fail in long, branching ways, so testing combines classic unit tests for tools, scenario tests for whole flows and scored evaluations over datasets. Rerun evals on every prompt, model or tool change.
Task success rate, steps and tool calls per task, tool error rate, latency, tokens and cost per task, plus groundedness for RAG. Track them per version to catch regressions.
Tools are ordinary functions: test argument validation, error messages, timeouts and edge cases deterministically, with no model involved.
Run the full agent on scripted scenarios with mocked or sandboxed tools and assert on outcomes, not exact wording. Run each case several times, since one pass proves little.
People review samples of real traces, label failures and calibrate automated LLM-as-judge graders. Essential for subjective quality and for finding failure modes you did not think to test.
An evaluation library for RAG and agent pipelines with metrics such as faithfulness, answer relevancy and context precision, plus synthetic test-set generation.
A pytest-style framework for LLM evaluation with ready-made metrics (hallucination, tool correctness, task completion) and LLM-as-judge scoring.
When an agent misbehaves you need the full trace: every prompt, model response, tool call, result, token count and latency, linked as one run. Observability tools collect these traces in development and production.
Log JSON events with a run id, step number, tool name, arguments, outcome and token usage, and wrap each step in a trace span. Redact secrets and personal data before they are written.
LangChain's hosted platform for tracing, datasets, evaluations and prompt management. Works with or without LangChain via its SDK.
Open-source LLM observability you can self-host: traces, sessions, cost tracking, prompt versioning and evaluation scores, with OpenTelemetry support.
An open-source proxy-based observability layer: route API calls through it to log requests, costs and latency, with caching and rate-limit features.
OpenTelemetry instrumentation for LLM SDKs and frameworks, so model calls show up as spans in any OTel backend such as Jaeger, Grafana or Datadog.
Prompt injection hides instructions in content the agent reads — a web page, email or file — to hijack its tools; jailbreaks try to talk the model out of its rules. No prompt fully prevents either, so limit what a compromised agent can do: least privilege, confirmation for risky actions and never mixing untrusted data with powerful tools unchecked.
Run code and shell tools in containers or microVMs with no secrets, limited network and resource caps. Give each tool the narrowest credentials it needs, allow-list commands and domains, and require human approval for destructive or external actions.
Agents see and store a lot of personal data. Detect and mask PII before sending it to third-party models or logs, check provider data-retention terms, honour deletion requests across memory stores and comply with laws such as GDPR.
Input and output filters — classifier models, moderation APIs or rule engines — catch harmful, hateful or off-topic content before it reaches users or tools. Measure false positives too, and test outputs across demographic groups for unfair differences.
Deliberately attack your own agent before others do: injection payloads in tool results, jailbreak prompts, data-exfiltration attempts and abuse of each tool. Automate the known attacks as a regression suite and repeat manual red-teaming whenever capabilities change.