Writing13 min readNewsletter

How to build an agentic-first project, step by step

A practical process for building AI agents that do real work. Define the job, design safe tools, enforce guardrails in code, test with evals and roll out in stages, with one worked example from start to finish.

#ai-agents#system-design#best-practices

When an AI agent project stalls, the model is rarely the problem. The trouble is everything around it: a fuzzy goal, tools with too much power, no tests, and no plan for the day the agent gets something wrong.

An agent that looks great in a demo can still lose you money in production. The demo runs on five clean examples. Production sends thousands of messy ones, at 3 a.m., with real money attached.

This post walks through a process for building agents that hold up: nine steps, with one example carried all the way through.

What “agentic-first” means

An agent is a model working in a loop. It reads the situation, picks a tool, looks at the result and decides the next step, until the job is done or it hands the work to a person.

Agentic-first means you design the work for that loop from day one. The agent handles routine cases end to end. People handle the exceptions, set the limits and review the results. It’s the opposite of bolting a chatbot onto an existing app and hoping it helps.

Every agent has four parts:

    request
       |
       v
+-------------+   tool call    +---------------------------+
|    MODEL    | -------------> |  YOUR CODE (guardrails)   |
| decides the |                |  limits, permissions,     |
|  next step  | <------------- |  idempotency, logs        |
+-------------+   tool result  +-------------+-------------+
       |                                     |
       v  done, or stuck                     v
  an outcome, or                       YOUR SYSTEMS
  a person takes over                orders, payments
Part What it does Who owns it
Model Decides the next step The model provider
Tools The only actions the agent can take You
Guardrails Limits the agent can’t talk its way past You
Loop Runs the steps, stops runaway runs, logs everything You

Three of the four parts are yours. That’s where most of the engineering goes.

First, check that you need an agent

Not every problem needs one. Use the simplest thing that works:

  • One model call when the task is a single step: classify an email, summarize a document, pull fields from an invoice.
  • A fixed workflow when the steps are always the same and only the inputs change. Your code calls the model at known points.
  • An agent when the right next step depends on what the last step found, and writing every path by hand isn’t practical.

Then ask two more questions. Is the result worth the extra cost and time of a loop? And when the agent is wrong, can you catch it and undo it? If either answer is no, stay with a workflow.

The example: refund requests

Picture an online store whose support team handles refund requests by hand. Each one means opening the order, checking the delivery date, reading the policy, deciding, and then issuing a refund or writing back.

The path changes with every request. A damaged item, a late delivery, a duplicate charge and a change of mind all go different ways. That makes it a good fit for an agent. A wrong refund also has a clear cost, which makes it a good teaching example. The store and every number below are illustrative.

Step 1: Write the job description

Before any code, write down the job the way you would for a new hire. If you can’t fill in this table, you’re not ready to build.

Question Refund agent
Input A customer’s refund request and order ID
Output A refund issued, or the case handed to a person with a summary
Done means The customer gets the right outcome under the refund policy
Business metric Support hours saved, and refunds issued correctly
Cost of a mistake Money refunded that shouldn’t be, or an unhappy customer
Hard limits Never refund more than was paid. Never refund over $100 without a person.

The last two rows matter most. They decide your guardrails, your rollout and how much freedom the agent gets.

Step 2: Do the job by hand first

Take 20 to 50 real cases and work through them yourself, or sit with the person who does. For each one, write down what you looked at, what you decided and why.

You’ll come away with three things:

  1. The tools you need. Every time you opened a system, that’s a tool.
  2. The rules nobody wrote down. “Damaged items get a refund up to 60 days after delivery, not just 30.” Those go into the policy.
  3. Your first test set. These cases, with their right answers, become your evals in Step 7.

Skipping this step is the most common reason agents disappoint. You can’t automate a decision you’ve never watched someone make.

Step 3: Design small, safe tools

Tools are the agent’s hands. They decide what it can and can’t do, so design them with care:

  • One job per tool. get_order reads. issue_refund writes. Don’t build one manage_order tool that does everything.
  • Separate reads from writes. Reads are safe to retry. Writes move money, so they get the strictest checks.
  • Describe each tool for a new hire. The description is the model’s only documentation. Say what the tool does, when to use it and when not to.
  • Validate inputs. Strict schemas make every call arrive in the shape you expect.
  • Return clear errors. “Over the $100 limit, use escalate_to_human” lets the agent recover. A stack trace doesn’t.
  • Always include a way out. An escalate_to_human tool turns “I’m not sure” into a safe action instead of a guess.

Here are the three tools for the refund agent. The examples use TypeScript and the Anthropic SDK, but the ideas carry over to any model and language.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const AUTO_REFUND_LIMIT = 100; // dollars; larger refunds need a person

const tools: Anthropic.Tool[] = [
  {
    name: "get_order",
    description:
      "Look up an order by ID. Returns the items, amount paid, delivery date and any refunds already issued. Use this before deciding anything.",
    strict: true,
    input_schema: {
      type: "object",
      properties: { order_id: { type: "string" } },
      required: ["order_id"],
      additionalProperties: false,
    },
  },
  {
    name: "issue_refund",
    description: `Refund all or part of an order. Only for amounts up to $${AUTO_REFUND_LIMIT} that the refund policy allows. For anything else, use escalate_to_human.`,
    strict: true,
    input_schema: {
      type: "object",
      properties: {
        order_id: { type: "string" },
        amount: { type: "number", description: "Refund amount in dollars" },
        reason: { type: "string", description: "One sentence, for the audit log" },
      },
      required: ["order_id", "amount", "reason"],
      additionalProperties: false,
    },
  },
  {
    name: "escalate_to_human",
    description:
      "Hand the case to a person. Use when the request is unclear, outside the policy, over the refund limit, or you are unsure.",
    strict: true,
    input_schema: {
      type: "object",
      properties: {
        summary: { type: "string", description: "What the customer wants and what you found" },
        recommendation: { type: "string", description: "What you would do, and why" },
      },
      required: ["summary", "recommendation"],
      additionalProperties: false,
    },
  },
];

Step 4: Put guardrails in code, not in the prompt

A prompt is guidance. Code is enforcement. Telling the model “never refund more than $100” helps, because it steers it toward the right tool. But the rule only holds if your code refuses the call.

Every action that can cost money gets checked where the agent can’t argue with it:

type ToolInput = Record<string, unknown>;
type ToolResult = { content: string; isError?: boolean };

// `orders`, `payments` and `helpdesk` stand in for your own systems.
async function runTool(name: string, input: ToolInput, caseId: string): Promise<ToolResult> {
  switch (name) {
    case "get_order": {
      const order = await orders.get(String(input.order_id));
      return order
        ? { content: JSON.stringify(order) }
        : { content: "No order with that ID.", isError: true };
    }

    case "issue_refund": {
      const orderId = String(input.order_id);
      const amount = Number(input.amount);

      // Re-read the order. Never trust amounts the model passes in.
      const order = await orders.get(orderId);
      if (!order) return { content: "No order with that ID.", isError: true };

      const refundable = order.total - order.refunded;
      if (!(amount > 0 && amount <= refundable)) {
        return { content: `Refund must be more than $0 and at most $${refundable}.`, isError: true };
      }
      if (amount > AUTO_REFUND_LIMIT) {
        return {
          content: `$${amount} is over the $${AUTO_REFUND_LIMIT} limit. Use escalate_to_human instead.`,
          isError: true,
        };
      }

      // One refund per case: a retried call can't pay out twice.
      const refund = await payments.refund({
        orderId,
        amount,
        reason: String(input.reason),
        idempotencyKey: `refund:${caseId}:${orderId}`,
      });
      return { content: `Refunded $${amount}. Refund ID ${refund.id}.` };
    }

    case "escalate_to_human": {
      const ticket = await helpdesk.escalate({
        caseId,
        summary: String(input.summary),
        recommendation: String(input.recommendation),
      });
      return { content: `Handed to a person. Ticket ${ticket.id}.` };
    }

    default:
      return { content: `Unknown tool: ${name}`, isError: true };
  }
}

Three guardrails live in that function:

  • Amount limits. A refund can’t exceed what’s left on the order, and anything over $100 goes back to the agent with instructions to escalate.
  • Idempotency. The refund carries a key tied to the case, so a retried call can’t pay out twice.
  • Fresh data. The tool re-reads the order before refunding instead of trusting numbers the model passed in.

Handle permissions the same way. The agent’s credentials should reach only the systems its tools need, and nothing else.

Step 5: Write the system prompt like an onboarding doc

The system prompt is the agent’s first-day briefing. Write it plainly: the goal, the policy, the rules and what “finished” looks like.

const SYSTEM = `You handle refund requests for an online store.

Goal: give each customer the right outcome under the refund policy, or hand the case to a person.

Refund policy:
- Full refund within 30 days of delivery if the item is unused or arrived damaged.
- Damaged items reported within 60 days of delivery can still be refunded.
- Never refund more than the amount paid minus refunds already issued.

How to work:
- Call get_order before deciding anything.
- Refund only with issue_refund, and only up to $${AUTO_REFUND_LIMIT}.
- If the request is unclear, outside the policy or over the limit, call escalate_to_human.
- When you're done, write one line for the log: what you did and why.`;

Keep it stable. The policy and rules belong here. Anything that changes per request, like the customer’s message or the order data, stays out of it. A stable prompt is easier to test and cheaper to run, because it can be cached.

Step 6: Build the loop with limits and logs

The loop sends the conversation to the model, runs the tools it asks for, sends the results back and repeats. Three things make it safe to run in production: a step limit, a clear exit for anything unexpected, and a log line for every step.

const MAX_STEPS = 8; // stops a confused agent from looping forever

type Outcome = { status: "finished" | "handed_off"; note: string };

export async function handleRefundRequest(caseId: string, request: string): Promise<Outcome> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: request }];

  for (let step = 1; step <= MAX_STEPS; step++) {
    const response = await client.messages.create({
      model: "claude-opus-5-5",
      max_tokens: 16000,
      system: SYSTEM,
      tools,
      output_config: { effort: "medium" },
      messages,
    });
    log({ caseId, step, stopReason: response.stop_reason, usage: response.usage });

    // Finished: the agent refunded or escalated, and wrote its log line.
    if (response.stop_reason === "end_turn") {
      const text = response.content.find((block) => block.type === "text");
      return { status: "finished", note: text?.type === "text" ? text.text : "" };
    }

    // Anything other than a tool call (a refusal, a cut-off answer) goes to a person.
    if (response.stop_reason !== "tool_use") {
      return handOff(caseId, `Agent stopped early: ${response.stop_reason}`);
    }

    messages.push({ role: "assistant", content: response.content });

    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of response.content) {
      if (block.type !== "tool_use") continue;
      const result = await runTool(block.name, block.input as ToolInput, caseId);
      log({ caseId, step, tool: block.name, input: block.input, isError: result.isError ?? false });
      results.push({
        type: "tool_result",
        tool_use_id: block.id,
        content: result.content,
        is_error: result.isError,
      });
    }
    messages.push({ role: "user", content: results });
  }

  return handOff(caseId, `Hit the ${MAX_STEPS}-step limit`);
}

async function handOff(caseId: string, reason: string): Promise<Outcome> {
  await helpdesk.escalate({ caseId, summary: reason, recommendation: "Review by hand" });
  return { status: "handed_off", note: reason };
}

Look at what happens when things go off script. If the agent hits the step limit, refuses, or stops for any reason other than finishing or calling a tool, a person gets the case. The loop never fails silently.

I wrote the loop by hand so you can see every step. In production, an SDK tool runner or a managed agent platform can run the loop for you. The guardrails still belong in your tool code.

Step 7: Build evals before you trust it

An eval is a test suite for the agent: real cases with known right answers, run on every change. Start with the cases from Step 2 and keep adding to them.

Case Order Expected
Arrived damaged $40, delivered 5 days ago Refund $40
Changed mind, item unused $60, delivered 10 days ago Refund $60
Changed mind $45, delivered 50 days ago Escalate: outside the policy
Arrived damaged, large order $350, delivered 3 days ago Escalate: over the limit
Order ID doesn’t exist None Escalate: ask for the right ID
Already refunded in full $80, $80 refunded Escalate: nothing left to refund

Run the agent against test copies of your systems, such as a fake order store and your payment provider’s test mode, and check each outcome. Track four numbers on every run:

  • Pass rate: how many cases got the right outcome.
  • Wrong-action rate: how many did something they shouldn’t have, like refunding when they should have escalated. This matters more than the pass rate.
  • Escalation rate: how often the agent hands off. Too high and it saves no time. Too low and it may be overconfident.
  • Cost and steps per case: what each resolution costs you.

Change the prompt, a tool description or the model, then rerun. If a number gets worse, you find out before your customers do. Evals also tell you which model to use: start with the most capable one, try cheaper ones, and keep the cheapest that still passes.

Step 8: Roll out in stages

Don’t jump from zero to fully autonomous. The agent earns its freedom with data:

  1. Shadow mode. The agent decides, but people still do the work. Compare its decisions with theirs for a week or two.
  2. Approval mode. The agent prepares each action and a person approves it with one click. This is where most of the time savings start.
  3. Autonomy within limits. The agent acts on its own below the limits, refunds up to $100 here, and escalates the rest.
  4. Raise limits slowly. Only while the wrong-action rate stays low, and one limit at a time.

Each stage has a way back. Lower the limit, or return to approval mode.

Step 9: Run it like a production service

Once it’s live, the agent is a service you’re on call for. Treat it like one:

  • Trace every run: the input, each tool call and result, the final outcome and the cost. When something goes wrong, you need to see exactly what the agent saw.
  • Watch a small dashboard: resolution rate, escalation rate, errors, cost per case and time per case.
  • Alert on change, not just failure. A sudden jump in escalations or refund amounts often means a system upstream changed.
  • Read a sample by hand every week. Go through a handful of cases the agent closed on its own. It’s the cheapest way to catch slow drift.
  • Turn every mistake into a test. A wrong answer in production becomes an eval case, so the same mistake can’t ship twice.

The checklist

  • Start from a business outcome and a job description, not from a model.
  • Check whether a single call or a fixed workflow is enough before building an agent.
  • Do the job by hand first, and turn those cases into your first evals.
  • Keep tools small, typed and clearly described. Separate reads from writes.
  • Enforce limits, permissions and idempotency in code. The prompt explains them; the code keeps them.
  • Always give the agent a way to hand off to a person.
  • Cap the steps, log every step, and send anything unexpected to a person.
  • Watch the wrong-action rate before the pass rate.
  • Roll out in stages: shadow, approval, then autonomy within limits.
  • Run it like a production service, with traces, a dashboard, alerts and a weekly review.

Where to start

Pick one job that eats hours every week and has a clear right answer. Write its job description, work 20 cases by hand, and build the smallest agent that can handle them, with a person approving every action. You’ll learn more in that first week than in a month of demos.

If you’re working out where an agent fits in your business, I’d like to hear what’s taking up your team’s week.