Most agent demos work once. Production agents have to work every day, under messy input, with real money and real customer data at stake. The gap between the two is not a better prompt. It is architecture: the code, permissions, limits and review steps that surround the model.
This guide turns that architecture into ten practical lessons. Each one explains the idea, why it matters, and what to implement. It is written for developers, technical founders and product teams who want agents that are safe, measurable and commercially defensible.
Building an agent also means writing the files that steer it.
Learn how to write AGENTS.md, SKILL.md and CLAUDE.md safely, without leaking secrets. Read the AI agent instruction files guide →
The 10 lessons at a glance
- Start with the simplest approach that works
- Classify first, then route
- Build the harness, not just the prompt
- Give tools the least privilege
- Set turn, time and cost limits
- Put a human in the loop
- Defend against prompt injection
- Keep secrets and trust on the server
- Make every write idempotent
- Prove it in a four-week pilot
Lesson 1 Start with the simplest approach that works
A workflow is a fixed sequence of steps that you or your code decide in advance. An autonomous agent lets the model choose its next step from tool results and intermediate state. Agents are flexible, but flexibility costs predictability, speed and money.
| Factor | Fixed workflow | Autonomous agent |
|---|---|---|
| Who decides the next step | Your code | The model |
| Predictability | High | Lower, varies per run |
| Cost and latency | Low and stable | Higher and variable |
| Best for | Repetitive, high-risk, well-understood tasks | Open-ended tasks with unknown steps |
Lesson 2 Classify first, then route
Many requests do not need an agent at all. A small, deterministic classification step can label the request (refund, booking change, general question) and send it down a fixed path. Only the unusual leftovers reach the open-ended agent.
- Use a cheap model or rules for classification.
- Keep a short, closed list of intents.
- Send anything low-confidence to a human or a safe fallback.
Lesson 3 Build the harness, not just the prompt
The harness is all the code around the model: the loop, tool definitions, validation, logging, limits and approvals. You cannot secure an LLM by asking it nicely to behave. Rules written in a prompt are suggestions. Rules enforced in code are guarantees.
// Minimal agent harness (TypeScript-style pseudocode)
const MAX_TURNS = 8;
const ALLOWED_TOOLS = new Set(["search_orders", "get_policy"]); // read-only
for (let turn = 0; turn < MAX_TURNS; turn++) {
const step = await model.next(state);
if (step.type === "final") return step.answer;
if (!ALLOWED_TOOLS.has(step.tool)) throw new Error("Tool not permitted");
validate(step.args); // schema check on the server
const result = await runTool(step); // scoped, logged, time-limited
state = append(state, result);
}
return escalateToHuman(state); // never loop forever
Your instruction files belong to the harness too. Files such as AGENTS.md, SKILL.md and CLAUDE.md shape how a coding agent behaves, so write and secure them deliberately. SEOSiri covers this in its guide to AI agent instruction files and zero-leakage repository security.
Lesson 4 Give tools the least privilege
Every tool you hand an agent is a capability an attacker can try to steer. Start read-only. If the model physically cannot edit files, spend money or send data out, a whole class of failures disappears.
- Prefer read-only tools; add write tools one at a time.
- Scope each tool to the smallest dataset and action it needs.
- Use separate credentials per tool, never one master key.
When you connect tools through the Model Context Protocol, apply the same rule: expose only the tools a given agent needs, and review each server's permissions before connecting it.
Lesson 5 Set turn, time and cost limits
An agent facing an ambiguous tool result can loop, retry and burn budget. Hard ceilings turn a runaway into a clean failure.
- Turn limit: a maximum number of model steps per task.
- Time limit: a timeout on each tool call and on the whole run.
- Cost limit: a token or spend cap per task and per user per day.
- Fallback: when any limit hits, stop and hand off with the full state attached.
Your agent's instructions are part of its attack surface.
One careless line in an instruction file can leak keys or widen permissions. Get the zero-leakage playbook: AI agent instruction files and repository security →
Lesson 6 Put a human in the loop
Route high-consequence actions, such as payments, deletions, contract changes or customer-facing messages, through a review card that requires explicit approval. Show the reviewer what the agent plans to do, the evidence it used, and a one-click approve or reject.
Human review is not a sign the agent failed. It is how you earn the trust to automate more later. Track approval rates: when reviewers approve a category 99% of the time, that category is a candidate for automation.
Lesson 7 Defend against prompt injection
Indirect prompt injection happens when an agent reads external content, such as an email, a web page or a database row, that contains instructions disguised as data. No model is fully immune, so defense must be layered and architectural.
- Treat all retrieved content as untrusted data, never as instructions.
- Keep tools read-only and scoped (Lessons 3 and 4) so a hijacked agent can do little harm.
- Require human approval before any irreversible action.
- Filter and log outputs that leave your system.
The OWASP Top 10 for LLM Applications catalogs prompt injection and related risks, and the NIST AI Risk Management Framework gives a structure for governing them.
Lesson 8 Keep secrets and trust on the server
Never trust a value that came from the client, including prices, user IDs, discount codes and permissions. The server must re-check them every time.
- Store API keys in server-side environment secrets, never in front-end code.
- Keep secrets out of public version control. Scan commits before you push.
- Validate every input and every tool argument against a strict schema.
For a deeper look at keeping agent instructions and repositories leak-free, see the SEOSiri developer UI kit builder guide.
Lesson 9 Make every write idempotent
Networks retry. Users double-tap. Agents repeat steps. An idempotent API returns the same confirmation for the same request instead of performing the action twice.
- Generate an idempotency key per intended action and send it with the write.
- Have the server store the key and replay the original result on repeats.
- Re-verify price, stock and permissions on the server at the moment of the write.
Payment providers document the pattern well; see Stripe's explanation of idempotent requests and the IETF work on an Idempotency-Key header. For an edge-level example of defending PHP and WordPress endpoints, read the SEOSiri zero-day and WebMCP playbook.
Lesson 10 Prove it in a four-week pilot
A technically sound agent is only half the job. You also need evidence that people use it and that the economics work. Run a time-boxed pilot with a fixed cohort, pre-set targets and explicit exit criteria.
| Week | Focus | Output |
|---|---|---|
| 1 | Scope one channel and one user cohort; record the baseline | Written success targets |
| 2 | Shadow mode: agent drafts, humans act | Accuracy and error log |
| 3 | Limited live use with human approval gates | Approval rate, cost per task |
| 4 | Compare results to targets | Go, fix or stop decision |
Unit economics: model and hosting costs usually run to fractions of a cent per query at modest volume, while human review is often the largest running cost. Measure cost per resolved task, not cost per token, and decide in advance what number makes the agent worth keeping.
Production-readiness checklist
- Workflow first; agent autonomy only where needed.
- Requests classified and routed; low-confidence cases escalate.
- All rules enforced in the harness, not the prompt.
- Tools read-only and least-privilege by default.
- Turn, time and cost limits with a clean fallback.
- Human approval on high-consequence actions.
- External content treated as untrusted data.
- Secrets and validation on the server.
- Idempotency keys on every write.
- Four-week pilot with targets and exit criteria.
Frequently asked questions
What is the difference between an AI workflow and an AI agent?
A workflow follows steps that your code fixes in advance. An agent lets the model choose its next step from tool results. Workflows are more predictable and cheaper, so start there and add autonomy only when needed.
How do you stop an AI agent from looping forever?
Set hard limits in the harness: a maximum number of turns, timeouts on every tool call, and a token or spend cap per task. When a limit is reached, stop and escalate to a human with the full state.
What is indirect prompt injection?
It is an attack where malicious instructions hide inside content the agent reads, such as an email, web page or database entry. Defend with untrusted-data handling, read-only tools, scoped permissions and human approval for irreversible actions.
Why do AI agents need idempotent APIs?
Retries and double submissions can make an agent perform the same action twice. Idempotency keys make the server return the original confirmation instead of repeating the action, which protects payments and bookings.
How long should an AI agent pilot run?
Four weeks is a practical window. Use a fixed cohort and channel, pre-set quantitative targets, and explicit stop criteria so you can make a clear go, fix or stop decision at the end.
Don't stop at architecture. Lock down the files that instruct your agents next: read the AI agent instruction files guide →
Ready to put these lessons into practice?
Explore SEOSiri's open-source agent tooling and live endpoint tester at developers.seosiri.com, browse the code at SEOSiri-Official on GitHub, or see how the edge firewall layer works at guard.seosiri.com. More engineering guides are on SEOSiri, and the site's LLMs.txt page shows how it is prepared for AI search.