Unit 7 · ML & applied AI · Lesson 10 of 13
AI workflows, agents and tool contracts
Step 1: Learn the ideas
- The augmented LLM: retrieval, tools and memory
- Workflow patterns: prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer
- Agent loops, stopping conditions and budgets
- Tool contracts: schemas, descriptions, validation and errors
- Server-side authorization and least privilege
- Side effects: idempotency, previews, confirmation and compensation
- Human-in-the-loop review and escalation
- Observability: traces, transcripts and replay
Why it matters
Agentic features move LLMs from producing text to changing state: sending email, updating a CRM, running code. The hard problems are mostly classic distributed-systems and security problems in a new setting: contracts, authorization, retries, idempotency and auditability. In an AI-assisted outreach product, for example, the difference between a draft that a user approves and an email sent automatically is the central design decision, and interviewers probe exactly that kind of judgment.
Core ideas
Workflows versus agents. A workflow is code that calls models along predefined paths; an agent lets the model choose the next step and the tools to use, in a loop, until it decides it is done. Workflows are cheaper, more predictable and easier to test; agents handle open-ended tasks whose steps cannot be enumerated, at the cost of latency, spend and compounding errors. Start with the simplest thing that works: one well-designed call with retrieval, then a workflow pattern.
- Prompt chaining: a fixed sequence of steps with programmatic checks between them.
- Routing: classify the input, then send it to a specialized path or model.
- Parallelization: split into independent subtasks, or sample several times and vote.
- Orchestrator-workers: a model plans subtasks dynamically and delegates them.
- Evaluator-optimizer: one call drafts, another critiques against criteria, repeat.
Use an agent when the path genuinely depends on intermediate results, and give it budgets (steps, tokens, wall time), explicit stopping conditions and a way to ask a human for help.
Tool contracts. A tool is an API whose client is a model. Specify:
- a precise name and description: what it does, when to use it, what it does not do;
- an input schema with types, enums, required fields and ranges;
- server-side validation of every argument, because model-produced arguments are untrusted input, like form data;
- structured, actionable errors ("start_date must be in the future; received 2024-01-03") that let the model correct itself;
- concise outputs containing what the next step needs, with stable identifiers rather than large dumps.
A few task-shaped tools ("schedule_meeting") usually work better than thin wrappers around every endpoint ("list_users", "list_events", "create_event").
Permissions. Authority belongs to the user, never to the model. Every tool call executes with the end user's identity and is authorized on the server against that user, the tenant and the specific resource, exactly as if the user had called the API directly. Grant the minimum scopes the task needs (read-only where possible), keep credentials out of prompts, and never let a model-chosen parameter such as tenant_id widen access.
Side effects. Classify each tool as read-only, reversible or irreversible. For writes: accept an idempotency key so a retry after a timeout cannot duplicate the action; offer a preview or dry run; require explicit human confirmation for irreversible or external actions (sending, paying, deleting); rate-limit; and record who approved what. For multi-step operations, design compensating actions such as cancel or undo.
Human review. Put people at approval gates for high-impact actions, route low-confidence or policy-sensitive cases to review, and sample routine outputs for audit. Make review fast by showing the proposed action, its inputs, its sources and a diff.
Observability. Log full trajectories (prompts, tool calls, arguments, results, decisions) with request IDs, so failures can be replayed and turned into evaluation cases.
Common misconceptions
- "Agents are more advanced, so prefer them." Use the simplest pattern that meets the requirement; many proposed agents should be workflows.
- "The system prompt can enforce permissions." Prompts are not security boundaries; enforce authorization in the tool server.
- "The provider's schema validation is enough." Validate again on the server, including semantics: does this record belong to this tenant?
- "Retries are harmless." Retrying a non-idempotent write after a timeout can duplicate it; use idempotency keys.
- "Human approval slows everything down, so skip it." Gate only irreversible or external actions and make approval quick; that is usually a small share of calls.
- "More tools make an agent more capable." Overlapping tools confuse tool selection and widen the attack surface.
How to approach it
Design one tool end to end on paper: schema, validation, authorization check, idempotency, errors and logging. Then take a task you know well and decide which parts are a workflow, which need an agent, and where a human approves. Map the OWASP "excessive agency" risk onto your design. Senior-level discussions add failure recovery, cost control and the evaluation of trajectories.
Suggested order
- 1Read "Building Effective Agents", including the appendix on prompt engineering your tools; summarize each workflow pattern with one example of your own.
- 2Read "Writing effective tools for agents", focusing on choosing tools, namespacing, returning meaningful context and writing tool descriptions.
- 3Read the JSON Schema getting-started guide and write schemas for three tools using enums, required fields and ranges.
- 4Read OWASP LLM06:2025 Excessive Agency and list the mitigations that apply to your tools.
- 5Design one side-effecting tool end to end (practice guidance) and review it against the misconceptions above.
- 6Read the parts of "Demystifying evals for AI agents" on tasks, trials, transcripts and outcomes, and plan how you would test the agent.
Step 2: Check off what you can do
Tap each one you can genuinely do or explain. Each earns 10 XP.
Step 3: Go deeper
Building Effective AgentsStart here
Anthropic EngineeringWorkflow patterns versus agents, when each fits, and practical tool-design advice.
Open(opens in a new tab)Link responded, 5 Oct 2026Writing effective tools for agents — with agentsStart here
Anthropic EngineeringDesigning tool interfaces, descriptions and responses that models use correctly, and evaluating them.
Open(opens in a new tab)Link responded, 5 Oct 2026JSON Schema: Creating your first schema
JSON Schema (json-schema.org)The schema vocabulary used for tool inputs and structured outputs; practice writing strict schemas.
Open(opens in a new tab)Link responded, 5 Oct 2026OWASP Top 10 for LLM Applications (2025)
OWASP Gen AI Security ProjectSection: LLM06:2025 Excessive Agency
Risks from excessive functionality, permissions and autonomy, with mitigations such as least privilege and human approval.
Open(opens in a new tab)Link responded, 5 Oct 2026
Step 4: Practice
Write a tool specification for send_outreach_email, or another side-effecting action you know well: a JSON Schema input, a description that says when not to use it, server-side checks (authenticated user, tenant ownership of the contact, rate limit, recipient validation), an idempotency key, a preview mode, a confirmation requirement and structured errors. Implement it as a small HTTP handler with tests that try to break it: a model-supplied tenant_id, a replayed request, a missing confirmation. Then implement the same task as a fixed workflow and as a small agent loop with a step budget, and compare success rates over 20 runs.
No external problems are linked; follow the guidance above.
Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).
Step 5: Test yourself
Answer each one out loud or on paper before you finish the lesson.
- Question 1When is an orchestrator-workers workflow better than a fixed chain?
- Question 2What should a tool error message contain to help the model recover?
- Question 3A model passes another tenant’s ID to a tool. What stops it?
- Question 4How do idempotency keys interact with retries after timeouts?
- Question 5Which actions in an outreach product need human approval, and which do not?
- Question 6What budgets and stopping conditions would you put on an agent loop?
You’re done when you can
- Explain workflows versus agents and pick one for three scenarios with reasons, in under five minutes.
- Write a complete tool contract with schema, validation, authorization, idempotency and errors.
- Explain where authorization is enforced and why prompts cannot enforce it.
- Implement and test one side-effecting tool against replay and privilege-escalation attempts.
Finish the lesson
Unlocks next: Prompt injection, permissions, privacy and model limitations


