Article · AI agents · Tool use (function calling)
AI agents: a model in a loop with tools – and when a plain workflow is enough
How an agent differs from a single call and from a workflow, five workflow patterns, an agent loop with limits and an approval gate, context management, costs and security – illustrated by complaint handling at a pierogi restaurant.
An AI agent is a language model working in a loop: it gets a goal and tools, decides the next step on its own, observes the result and keeps going until it considers the task done. It is a powerful pattern – and the most overused one. Most business problems are better solved by a predictable workflow, in which code sets the order of steps and the model performs individual stages.
- 4
- questions before building an agent – complexity, value, viability, cost of error
- 5
- workflow patterns – chaining, routing, parallelization, orchestrator, evaluator
- 1
- loop at the heart of an agent – while the model asks for tools – execute and send back
The problem: a complaint you cannot write as if-statements
A pierogi customer writes: "Order 1042 arrived 73 minutes late and cold. I want a refund!". A support worker checks the order, compares the times in the delivery log, looks at the customer's history, decides on compensation (a voucher? a refund? nothing?) and writes a reply. Sometimes they need to ask a follow-up question, sometimes hand the case to the manager because the customer mentions an allergic reaction.
The team tries to automate this in two extreme ways. First: a rigid script with dozens of conditions – it falls apart on every unusual ticket. Second: an "autonomous agent" with access to the whole database and the payment system, with the prompt "resolve complaints" – after a week it had handed out PLN 2,000 in vouchers, because customers quickly found out that a firm tone works. The good solution lies in between and starts with the question of how much autonomy is really needed.
The spectrum: call, workflow, agent
Before building an agent, answer four questions. Complexity: is the task multi-step and hard to specify up front? Value: does the outcome justify the higher cost and latency? Viability: is the model good at this type of task? Cost of error: can mistakes be caught and undone (tests, review, approval)? A single "no" is a signal to stay at a simpler level.
Five workflow patterns
Many "agents" are in practice a well-composed workflow. These patterns – described among others in Anthropic's Building effective agents – are worth knowing before you hand control to the model:
| Pattern | How it works | Pierogi example |
|---|---|---|
| Prompt chaining | the output of one step is the input of the next; validation can sit between steps | review → triage → reply draft → tone check |
| Routing | a classifier sends the case down a specialised path | order status / complaint / menu question |
| Parallelization | independent subtasks at once, or several votes and a majority | checking a review for allergens, tone and spam simultaneously |
| Orchestrator-workers | a model splits the task into subtasks and delegates them to other calls | preparing a weekly report from many sources |
| Evaluator-optimizer | one call creates, another grades against criteria, loop until done | a new dish description revised until it meets the brand guidelines |
Routing is the simplest and very effective pattern: a cheap model classifies the message, and each path has its own short prompt, its own tools and its own tests.
Workflow: routing with a cheap classifier
from typing import Literal
import anthropic
from pydantic import BaseModel
client = anthropic.Anthropic()
class Route(BaseModel):
route: Literal["order_status", "complaint", "menu_question", "other"]
# Each route gets a focused prompt (and later its own tools and evals).
PROMPTS = {
"order_status": "You answer questions about the status of pierogi orders. Use the order tools.",
"complaint": "You handle complaints about orders. Be empathetic, gather facts, never promise refunds.",
"menu_question": "You answer menu and allergen questions using only the attached menu.",
"other": "You are the general assistant of Halina's Pierogi. Keep answers short.",
}
def classify(message: str) -> str:
# A small, cheap model is enough for a 4-way classification.
result = client.messages.parse(
model="claude-haiku-5-5",
max_tokens=256,
system="Classify a customer message sent to a pierogi restaurant's chat.",
messages=[{"role": "user", "content": message}],
output_format=Route,
)
return result.parsed_output.route if result.parsed_output else "other"
def handle(message: str) -> str:
route = classify(message) # step 1: deterministic routing decided by code
response = client.messages.create( # step 2: specialised handler
model="claude-opus-5-5",
max_tokens=2048,
system=PROMPTS[route],
messages=[{"role": "user", "content": message}],
)
return "".join(b.text for b in response.content if b.type == "text")import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";
const client = new Anthropic();
const Route = z.object({ route: z.enum(["order_status", "complaint", "menu_question", "other"]) });
type RouteName = z.infer<typeof Route>["route"];
// Each route gets a focused prompt (and later its own tools and evals).
const PROMPTS: Record<RouteName, string> = {
order_status: "You answer questions about the status of pierogi orders. Use the order tools.",
complaint: "You handle complaints about orders. Be empathetic, gather facts, never promise refunds.",
menu_question: "You answer menu and allergen questions using only the attached menu.",
other: "You are the general assistant of Halina's Pierogi. Keep answers short.",
};
async function classify(message: string): Promise<RouteName> {
// A small, cheap model is enough for a 4-way classification.
const result = await client.messages.parse({
model: "claude-haiku-5-5",
max_tokens: 256,
system: "Classify a customer message sent to a pierogi restaurant's chat.",
messages: [{ role: "user", content: message }],
output_config: { format: zodOutputFormat(Route) },
});
return result.parsed_output?.route ?? "other";
}
export async function handle(message: string): Promise<string> {
const route = await classify(message); // step 1: deterministic routing decided by code
const response = await client.messages.create({
model: "claude-opus-5-5", // step 2: specialised handler
max_tokens: 2048,
system: PROMPTS[route],
messages: [{ role: "user", content: message }],
});
return response.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
}using System.Text.Json;
using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new();
// Each route gets a focused prompt (and later its own tools and evals).
var prompts = new Dictionary<string, string>
{
["order_status"] = "You answer questions about the status of pierogi orders. Use the order tools.",
["complaint"] = "You handle complaints about orders. Be empathetic, gather facts, never promise refunds.",
["menu_question"] = "You answer menu and allergen questions using only the attached menu.",
["other"] = "You are the general assistant of Halina's Pierogi. Keep answers short.",
};
async Task<string> Classify(string message)
{
// A small, cheap model is enough for a 4-way classification; the schema limits the answer.
var schema = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>("""
{"type":"object","properties":{"route":{"type":"string",
"enum":["order_status","complaint","menu_question","other"]}},
"required":["route"],"additionalProperties":false}
""")!;
var result = await client.Messages.Create(new MessageCreateParams
{
Model = "claude-haiku-5-5",
MaxTokens = 256,
System = "Classify a customer message sent to a pierogi restaurant's chat.",
OutputConfig = new OutputConfig { Format = new JsonOutputFormat { Schema = schema } },
Messages = [new UserMessageParam { Content = message }],
});
var json = result.Content.Select(b => b.Value).OfType<TextBlock>().First().Text;
return JsonDocument.Parse(json).RootElement.GetProperty("route").GetString() ?? "other";
}
string userMessage = "The pierogi arrived cold and 40 minutes late.";
string route = await Classify(userMessage); // step 1: deterministic routing decided by code
var answer = await client.Messages.Create(new MessageCreateParams
{
Model = "claude-opus-5-5", // step 2: specialised handler
MaxTokens = 2048,
System = prompts[route],
Messages = [new UserMessageParam { Content = userMessage }],
});
Console.WriteLine($"[{route}] " + string.Concat(answer.Content.Select(b => b.Value).OfType<TextBlock>().Select(t => t.Text)));The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- The agent loop
- Context: a resource that runs out
- As much autonomy, as many safeguards
- Where agents came from
- When an agent, and when a workflow
- Production agent checklist
- Test yourself
- What's next