Guide / AI engineering Fundamentals
19. Agents, tool use, MCP, memory, multi-agent
An agent is an LLM in a loop: observe → decide (call a tool or answer) → act → observe the result → repeat until done or a limit is hit. A workflow is a fixed sequence of LLM and code steps you define. Interviewers love the question “when would you not use an agent?” — answer: when the steps are known in advance, use a workflow; it’s cheaper, faster, testable and predictable.
19.1 Tool calling#
- You describe tools with name, description, and JSON Schema parameters; the model returns a structured call; your code executes it and returns the result to the model.
- Good tools: few, well-named, with clear descriptions of when to use them, narrow inputs (enums, IDs), helpful error messages the model can recover from, idempotent where possible.
- Return concise results (not 10,000-row dumps); paginate or summarize.
- Parallel tool calls cut latency when calls are independent.
- Never trust tool arguments: validate with schemas, check permissions on the server side as the user, not as the agent.
19.2 Agent architectures#
| Pattern | How | Use when |
|---|---|---|
| ReAct | Interleave reasoning and tool calls step by step | General tool-using assistants |
| Plan-and-execute | Plan all steps first, then execute (re-plan on failure) | Long multi-step tasks, cost control |
| Router | Classify the request and send to a specialised chain/agent | Many distinct intents (support bots) |
| Reflection / evaluator-optimizer | Generate, critique, revise | Quality-critical writing, code |
| Orchestrator-workers (supervisor) | A lead agent splits work and delegates to sub-agents, then merges | Research, broad parallel tasks |
| State machine / graph (LangGraph) | Explicit nodes, edges, state, checkpoints | Production agents needing control, recovery, human approval |
19.3 MCP (Model Context Protocol)#
An open protocol (introduced by Anthropic in late 2024, now widely adopted) that standardises how AI applications connect to tools and data. An MCP server exposes tools (actions), resources (readable data), and prompts (templates); an MCP client inside the host app (an IDE, chat app, or your agent) discovers and calls them over stdio (local) or HTTP (remote, with OAuth). Benefit: write an integration once, use it from any MCP-compatible client. Interview points: auth and least privilege per server, tool-poisoning risk (malicious tool descriptions), too many tools bloating context, and auditing calls. Agent-to-agent protocols (e.g. Google’s A2A) address agents talking to other agents, rather than to tools.
19.4 Memory#
- Short-term: conversation history within the context window, trimmed or summarized.
- Working state: structured state object in the graph (cart contents, collected slots, step) — more reliable than hoping the model remembers.
- Long-term: facts and preferences extracted and stored (vector store or key-value profile), retrieved when relevant. Needs privacy controls, expiry, and user-visible deletion.
- Episodic: past task traces used as examples for similar future tasks.
19.5 Production concerns#
- Limits: max steps, max tokens, max wall-clock time, max cost per task; detect loops (same tool + args repeated).
- Checkpointing: persist state after each step so a crash resumes instead of restarting (LangGraph checkpointers, Temporal for durable workflows).
- Human-in-the-loop: pause for approval before irreversible or high-value actions (refunds, emails, deletes).
- Sandboxing: run code or risky actions in isolated environments with no ambient credentials.
- Idempotency: tool actions with side effects take an idempotency key, since agents retry.
- Observability: trace every LLM call and tool call with inputs, outputs, tokens, latency and cost.
- Fallbacks: hand off to a human or a deterministic flow when confidence is low or the agent fails.
19.6 Multi-agent systems — honest trade-offs#
Multi-agent helps for parallelisable breadth (research across many sources) and separation of concerns (distinct tools/permissions per agent). It costs many more tokens, adds coordination failures, and is harder to debug. Start with one agent with good tools; split only when evals show a benefit.
19.7 Voice agents#
- Cascaded pipeline: VAD (voice activity detection) → streaming STT → LLM → streaming TTS. Each stage streams so speech starts before the full answer exists. Flexible (any LLM, tools, text logs) but adds latency.
- Speech-to-speech models (Gemini Live, OpenAI Realtime): lower latency and more natural prosody; less control and harder to inspect.
- Latency budget: humans expect a reply within ~500–800 ms of finishing speaking. Budget STT finalisation, LLM TTFT, TTS first audio; use filler phrases or acknowledgements for slow tool calls.
- Turn-taking: endpointing (when has the user finished?), barge-in (user interrupts → stop TTS immediately, truncate the assistant’s message in history to what was actually spoken).
- Transport: WebRTC for browsers/apps (handles jitter and packet loss), WebSockets for server-side streams, SIP/PSTN via Twilio/Exotel for phone calls.
- Frameworks: Pipecat, LiveKit Agents, Vapi/Retell-style platforms.
- Eval: simulated callers with personas, word error rate, task completion, latency percentiles, interruption handling.