6 AI Agent Principles
Most AI agent projects fail because of planning failures, not technical ones. Internalise these principles before filling in the template.
6 AI Agent Patterns
Choose the right pattern for your use case. The pattern you choose determines your implementation complexity, cost, and reliability.
Use Case & Problem Definition
The most common AI agent failure is building the wrong thing. Define the problem precisely before choosing any technology. A well-defined use case takes 30 minutes to write and saves weeks of wasted development.
Hint: Give the agent a name and describe what it does in one sentence. If you cannot describe it simply, the scope is too broad.
e.g. LeadResearcher Agent — automatically researches inbound leads from CRM and enriches their profile with company size, funding status, tech stack, and recent news before the sales call.
Hint: Quantify the problem. How much time, money, or errors does it cost today? Numbers justify the build.
e.g. Our sales team spends 45 minutes per lead manually researching LinkedIn, Crunchbase, and company websites before each discovery call. This time could be spent on calls — not research. With 30 leads per week, that is 22 hours of manual research that could be automated.
Hint: Map exactly what happens today. This becomes your agent's task list. Every manual step is a potential agent tool call.
e.g. 1. Sales rep receives new lead in HubSpot CRM 2. Manually searches LinkedIn for the contact's background and role 3. Searches Crunchbase for company funding and size 4. Googles company name + 'news' to find recent announcements 5. Searches BuiltWith or G2 for their technology stack 6. Copies findings into a HubSpot note field 7. Spends additional 10 mins synthesising into a call brief
Hint: Define what good output looks like. Include a measurable quality threshold. Without this, you cannot evaluate whether the agent is working.
e.g. The agent completes a full lead research brief — LinkedIn summary, company overview, funding status, tech stack, and recent news — within 3 minutes of a new lead being added to HubSpot, with accuracy comparable to manual research 90%+ of the time.
Hint: Agents are triggered by: webhook events, scheduled cron jobs, user commands, database row changes, or API calls. Choose the trigger that fits your workflow.
e.g. New contact added to HubSpot with company domain filled in. Webhook fired to n8n which triggers the agent pipeline. Alternative triggers considered: scheduled daily batch, Slack command (/research @contact), or manual button in HubSpot sidebar.
Hint: Define the output format precisely. Where does it go? Who sees it? What format does it need to be in?
e.g. A structured JSON object containing: contact LinkedIn summary, company description, employee count, funding total and last round, tech stack (top 5 tools), and 3 recent news items. This is converted to a formatted HTML note and saved to the HubSpot contact record.
Agent Architecture & Pattern
Choosing the right agent pattern determines your implementation complexity, reliability, and cost. Match the pattern to the task structure — do not over-engineer a simple workflow.
Hint: Choose from: ReAct, Plan & Execute, Multi-Agent, RAG Agent, Code Interpreter, or Autonomous Loop. See the pattern guide above.
e.g. ReAct Agent (Reason + Act + Observe) Rationale: Lead research is an exploratory task with variable steps. The agent needs to decide which tools to use based on what it finds — sometimes LinkedIn is enough, other times Crunchbase data is missing and it needs to search the web. ReAct handles this adaptive flow well.
Hint: How will you orchestrate the agent? Options: n8n, LangChain, LlamaIndex, custom Python with Claude API, or a managed platform like Vertex AI Agents.
e.g. n8n self-hosted on Railway — handles trigger (HubSpot webhook), orchestrates the Claude API call sequence, manages tool calls, and writes output back to HubSpot via their API. Alternative considered: LangChain with FastAPI backend. Rejected because n8n provides better visual debugging and our team is already familiar with it.
Hint: Start with a single agent. Add multi-agent complexity only when a single agent cannot handle the task reliably.
e.g. Single agent for MVP. The LeadResearcher agent handles all research tasks itself. V2 consideration: Split into ResearchAgent (data gathering) + SynthesisAgent (brief writing) if quality of synthesis is not meeting the 90% accuracy threshold with a single agent.
Hint: Estimate token usage per task. If tool outputs are large, plan how to summarise or truncate before passing to the LLM.
e.g. Using Claude Sonnet (200k context). Each research task passes: system prompt (500 tokens) + tool results accumulated across tool calls (estimated 3,000–8,000 tokens per lead) + output format instructions (200 tokens). Total estimated 10,000 tokens per task — well within context limits. No summarisation required at MVP scale. Will revisit if processing companies with very long news histories.
LLM Selection & Configuration
The choice of model affects cost, speed, accuracy, and context length. Match the model to the task requirements — not every agent needs the most expensive model.
Hint: Recommendation: Claude Sonnet for most agentic tasks. Use GPT-4o for multimodal. Use Haiku/GPT-4o mini for high-volume, simple tasks where cost matters.
e.g. Claude claude-sonnet-4-6 (Anthropic) Rationale: Sonnet provides the best balance of instruction-following, tool use accuracy, and cost for our use case. Its 200k context window handles large tool outputs without truncation. Testing showed 94% accuracy on lead research tasks vs 89% for GPT-4o mini at 3× the cost.
Hint: Define a fallback strategy. What happens if your primary model is unavailable or returns an error?
e.g. Claude Haiku as fallback if Sonnet API is unavailable or rate-limited. Haiku handles simple lookups well at lower cost. Complex synthesis tasks are queued and retried with Sonnet.
Hint: Temperature 0.0–0.3 for factual/research tasks. Temperature 0.7–1.0 for creative tasks. Low temperature = more consistent, predictable output.
e.g. temperature: 0.2 (low — research tasks need consistency, not creativity) max_tokens: 4096 (sufficient for a structured research brief) top_p: 1.0 (default) tool_choice: auto (agent decides which tools to use) stop_sequences: None required
Hint: Calculate cost per task before building. Multiply by expected volume. Compare to the manual cost you are replacing.
e.g. Input tokens per task: ~8,000 (system prompt + tool results) Output tokens per task: ~1,500 (research brief) Claude Sonnet pricing: $3.00/1M input, $15.00/1M output Cost per task: (8,000 × $0.000003) + (1,500 × $0.000015) = $0.024 + $0.0225 = ~$0.047 per lead At 30 leads/week: $1.41/week or ~$73/year. Negligible vs manual research cost.
Tools & Integrations
Tools are the actions an agent can take — APIs it can call, databases it can query, code it can run. Define each tool precisely with its inputs, outputs, and failure behaviour before writing a line of code.
Define each tool the agent can use. Every tool needs a name, description, inputs, outputs, provider, and error handling strategy.
Add your own tool
Copy the structure above for each additional tool your agent needs
System Prompt & Prompt Engineering
The system prompt is the most important artefact in your agent. It defines the agent's identity, scope, behaviour, output format, and safety boundaries. Write it carefully — it is the instruction manual the agent follows for every task.
Hint: Your system prompt should define: role, task steps, output format, constraints, and error handling. Be explicit — the agent cannot infer what you have not written.
e.g.
You are LeadResearcher, an AI agent that researches business leads for a B2B SaaS sales team.
## Your Role
You help sales representatives prepare for discovery calls by researching contacts and their companies. You gather factual, publicly available information and present it in a structured brief.
## Your Task
When given a contact name, company domain, and optional LinkedIn URL, you will:
1. Research the contact's professional background using LinkedIn data
2. Research the company using Crunchbase for funding and size data
3. Identify the company's technology stack using BuiltWith
4. Search for recent news about the company (last 90 days)
5. Synthesise findings into a structured research brief
## Output Format
Return a JSON object with this exact structure:
{
"contact": { "name", "role", "background_summary" },
"company": { "name", "description", "employees", "funding", "tech_stack" },
"recent_news": [{ "headline", "date", "summary" }],
"sales_angles": ["angle 1", "angle 2", "angle 3"]
}
## Important Rules
- Only use publicly available information
- Do not speculate or invent data you cannot verify
- If a data point is unavailable, set it to null — do not guess
- Complete all research in a maximum of 8 tool calls
- If you cannot gather minimum viable data, return a partial brief with a note explaining what is missingHint: The user prompt passes task-specific data to the agent at runtime. Use template variables filled from your trigger (webhook, database, etc.).
e.g.
Research this lead for an upcoming sales call:
Contact Name: {{contact.first_name}} {{contact.last_name}}
Contact Title: {{contact.job_title}}
Company: {{contact.company}}
Company Domain: {{contact.company_domain}}
LinkedIn URL: {{contact.linkedin_url}} (may be empty)
Priority: {{contact.deal_value}} deal in pipeline. Call scheduled for {{call.date}}.Hint: Asking the agent to think step by step (chain-of-thought) significantly improves accuracy on complex tasks. Include this in your system prompt or user prompt.
e.g. Before taking any action, briefly state your research plan in 2–3 sentences. This helps with debugging and ensures the agent has understood the task correctly before executing tool calls.
Hint: Define programmatic validation rules that run after the agent produces output. Do not rely solely on the agent to self-validate.
e.g. After generating the output JSON, validate: □ contact.name is not null □ company.name is not null □ At least 3 of 5 company fields populated □ recent_news contains at most 5 items □ sales_angles contains exactly 3 items If validation fails, regenerate the affected sections before returning.
Memory & State Management
Memory is what separates a one-shot AI call from a true agent. Define exactly what the agent should remember, how long it should remember it, and where it is stored.
Hint: Types: In-Context (within one task), Short-Term (within a session), Long-Term (across sessions via vector store), External (database or cache).
e.g. For the LeadResearcher agent: In-Context Memory (within a single task run): Tool call results are accumulated in the conversation history and used by subsequent tool calls within the same task. No persistent memory needed between tasks. No long-term memory required for this agent: each lead research task is independent. Previous research on Company A does not inform research on Company B. Future v2 consideration: cache company research results for 30 days so researching a second contact at the same company does not repeat the same API calls.
Hint: If long-term memory is needed, use Supabase with pgvector for semantic search, or Redis for key-value cache. Define TTL (time-to-live) for all stored data.
e.g. No memory storage required for MVP. V2 company cache architecture: - Store company research results in Supabase table (company_research_cache) - Key: company_domain, Value: JSON research object - TTL: 30 days (updated_at column, filter stale records) - Before API calls, check cache first. If fresh cache hit, skip external API calls. - Estimated savings: 60% API cost reduction for teams working in same verticals
Hint: Define what happens when tool results push the context window close to the model limit. Summarisation is the standard strategy.
e.g. Tool results are appended to the conversation history as tool_result messages. If accumulated context exceeds 50,000 tokens, apply a summarisation step: 1. Call Claude Haiku with all tool results 2. Ask it to produce a 500-token summary of findings so far 3. Replace raw tool results with the summary in the context 4. Continue agent execution with summarised context This prevents context overflow on leads with extensive news history or many tool calls.
Safety, Guardrails & Human Oversight
Agents that take real-world actions can cause real-world harm. Every irreversible action must have a safety layer. Define your guardrails before deployment — not after an incident.
Hint: Classify every action by risk. Read-only actions = autonomous. Writes to external systems = validate. Emails, payments, deletions = human approval required.
e.g. LOW RISK (fully autonomous — no approval needed): - web_search: read-only, no side effects - fetch_linkedin_profile: read-only API call - fetch_company_data: read-only API call - fetch_tech_stack: read-only website analysis MEDIUM RISK (log and allow, flag anomalies): - update_crm_record: writes to production HubSpot — validated before submission HIGH RISK (require human approval before execution): - send_email: not in MVP scope. Would require explicit human approval for each email - delete_record: not in scope. Never allowed without dual approval
Hint: Validate all inputs before the agent starts. Garbage in = garbage out. Input validation prevents wasted API spend on invalid tasks.
e.g.
Before agent execution, validate:
□ company_domain is a valid domain format (regex: /^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/)
□ contact_id exists in HubSpot before agent runs
□ contact_id is not on the do-not-research list (GDPR opt-out records)
□ Rate limit check: no more than 10 agent tasks per minute per team
If validation fails: return error to n8n, log reason, send Slack alert, do not start agent.Hint: Always set a maximum iteration count and timeout. Agents can get stuck in loops — these limits are your safety net.
e.g. max_tool_calls: 10 (agent must complete research in 10 or fewer tool calls) max_execution_time: 120 seconds (agent killed and error returned if exceeded) max_retries_per_tool: 2 (each tool can be retried twice on failure) If max_tool_calls exceeded: return partial results with a warning flag If max_execution_time exceeded: return whatever has been gathered so far
Hint: Define exactly what data flows through the agent and how it is protected. Agents often touch PII — compliance cannot be an afterthought.
e.g. The agent processes: contact names, company domains, LinkedIn URLs, email addresses Rules: - No PII logged in plaintext — contact_id used as reference, full data not stored in logs - Tool call inputs/outputs logged for 30 days then purged - Research briefs stored in HubSpot only — not in agent logs - LinkedIn scraping complies with robots.txt and rate limits - All API calls over HTTPS only - GDPR: contacts with 'do_not_research' flag in HubSpot are excluded before agent runs
Hint: Even a 'fully automated' agent needs human review checkpoints. Define when the agent escalates to a human rather than failing silently.
e.g. For LeadResearcher (low-risk agent), no human approval required in the automated flow. Human review triggered when: - Agent confidence score below threshold (if implemented) - Task takes more than 90 seconds (Slack alert: 'Agent taking longer than expected on [contact_id]') - Agent returns partial results (Slack alert with summary of what is missing) - CRM write fails after 3 retries (Slack alert with raw JSON for manual entry) Weekly review: sales manager reviews 10 random research briefs for accuracy assessment
Testing & Evaluation
AI agents are probabilistic — they do not always produce the same output. Systematic testing before deployment prevents embarrassing or costly failures in production.
Hint: Build a test set of 10–30 inputs with known expected outputs. Run every prompt change against this set before deploying.
e.g. 20 test leads selected to represent diverse cases: 5 well-known companies (Stripe, Notion, Linear, Figma, Vercel) — expected output well-understood 5 mid-size companies with Crunchbase data — validate funding data accuracy 5 small companies with limited online presence — validate graceful degradation 3 companies with recent news — validate news retrieval and recency 2 edge cases: one-person companies, holding companies with no web presence Golden output manually created for each test case. Agent output compared to golden output using LLM-as-judge scoring.
Hint: Define metrics before you build. You need a baseline to know if your changes are improvements or regressions.
e.g. Accuracy (primary): % of fields populated with correct information vs golden output Target: >90% across all fields Measured by: LLM-as-judge (Claude grades agent output against golden output on 1–5 scale) Completeness: % of required output fields populated (non-null) Target: >95% for critical fields (company name, contact role) Target: >80% for optional fields (funding amount, tech stack) Latency: Time from trigger to CRM update Target: <3 minutes per lead Measured by: n8n execution time tracking Cost per task: actual token spend per lead Target: <$0.10 per lead Measured by: Anthropic API usage dashboard
Hint: Test every failure mode explicitly. AI systems fail in unexpected ways — discovering these before production is far cheaper than after.
e.g. Test scenarios for failure modes: □ LinkedIn URL invalid or private — agent should note and continue without LinkedIn data □ Crunchbase API returns 429 rate limit — agent should retry once, then use web search as fallback □ Company has no web presence — agent should return partial brief with explanation □ Contact name returns multiple LinkedIn matches — agent should select most likely match based on company domain □ All tool calls fail — agent should return graceful failure message, not crash □ Context window near limit — summarisation step should trigger correctly □ CRM API write fails — Slack alert should fire with fallback JSON
Hint: Agents degrade over time as the world changes (API responses, company data). Define a regular evaluation cadence.
e.g. Before any system prompt change: 1. Run full golden test set (20 leads) 2. Compare new scores to baseline scores 3. No deployment if accuracy drops more than 2% on any metric After any tool change: 1. Run 5 test cases that exercise the changed tool 2. Verify output format unchanged 3. Check cost metrics — tool changes often change token usage Weekly production monitoring: 1. Sample 10 production outputs 2. Score manually against expected quality 3. Flag any emerging patterns of failure for prompt tuning
Deployment & Infrastructure
AI agents running in production need reliable infrastructure, monitoring, and incident response. An agent that runs in a Jupyter notebook is not a production agent.
Hint: Define every component in your deployment architecture. Where does each part run? Who maintains it? What are the failure points?
e.g. Trigger: HubSpot webhook → n8n (self-hosted on Railway) Orchestration: n8n workflow handles tool call loop LLM API: Anthropic Claude API (direct HTTP from n8n) Tool APIs: Serper, ProxyCurl, Crunchbase, BuiltWith (all via n8n HTTP nodes) Output: n8n writes to HubSpot CRM API Logs: n8n execution logs + custom Supabase logging table Alerts: n8n error handler → Slack webhook No custom backend required for MVP. n8n handles all orchestration.
Hint: List every secret and environment variable. Define rotation policy. If a key is compromised, how quickly can you rotate it?
e.g. Environment variables (stored in n8n credential store): - ANTHROPIC_API_KEY — Claude API key - SERPER_API_KEY — web search API key - PROXYCURL_API_KEY — LinkedIn data API key - CRUNCHBASE_API_KEY — company data API key - HUBSPOT_ACCESS_TOKEN — CRM write access token - SLACK_WEBHOOK_URL — error notification webhook Never stored in code or version control. Rotated every 90 days.
Hint: All LLM APIs have rate limits. Define your concurrency strategy and what happens when you hit limits.
e.g. Anthropics rate limits: 60 requests/minute on Tier 1 plan Max concurrent agent tasks: 5 (to stay within API limits) Queue system: n8n queue mode handles task concurrency Backoff strategy: exponential backoff on 429 errors (1s, 2s, 4s, 8s, give up and alert) Expected load: 30 leads/week = ~4–5 tasks/day at most No rate limiting issues expected at this volume. Monitor if volume increases above 100 leads/week.
Hint: Log every agent execution with its metrics. You need this data to debug failures and optimise cost and performance over time.
e.g. Metrics tracked per task (logged to Supabase): - contact_id, task_start_time, task_end_time, duration_seconds - tool_calls_used, tokens_input, tokens_output, cost_usd - output_fields_populated, quality_score (LLM-judge) - status: success | partial | failed | timeout Slack alerts triggered by: - Task failure (any status != success) - Task duration > 3 minutes - Daily cost exceeds $5 (spike detection) - API key error (immediate — possible compromise) Weekly Slack summary: total tasks, success rate, avg cost, avg duration
Cost Analysis & ROI
AI agents must justify their cost. Calculate the full cost of building and running the agent against the value it delivers — including the hidden costs of maintenance and monitoring.
Hint: Include developer time, not just API costs. Agent development takes longer than expected — build in 50% contingency.
e.g. Internal development time: 40 hours × $150/hr = $6,000 Tool API setup and testing: 8 hours × $150/hr = $1,200 n8n infrastructure: $20/month (Railway hosting) API costs during testing: ~$50 Total build cost: ~$7,250 Ongoing monthly cost: ~$100/month (infrastructure + APIs at current volume)
Hint: Calculate the current cost in human time × hourly rate. This is the baseline your agent must beat.
e.g. 30 leads/week × 45 min manual research = 1,350 min/week = 22.5 hours/week Sales rep hourly rate: $50/hour (fully loaded cost) Weekly manual research cost: 22.5 × $50 = $1,125/week Annual manual research cost: $1,125 × 52 = $58,500/year Additional value: faster research (3 min vs 45 min) = more discovery calls per day
Hint: Include maintenance time as a cost. Agents require ongoing prompt tuning, tool updates, and monitoring — budget 1–4 hours per month.
e.g. LLM cost: $0.047/task × 30 leads/week × 52 weeks = $73/year Tool API costs: ~$150/year (ProxyCurl, Crunchbase at 1,560 leads/year) n8n hosting: $240/year Maintenance: 2 hours/month × $150/hr = $3,600/year Total annual running cost: ~$4,063/year
Hint: Calculate payback period and ongoing ROI. If payback is over 12 months, reconsider the scope or whether a simpler automation would achieve the same result.
e.g. Year 1 cost: $7,250 (build) + $4,063 (running) = $11,313 Year 1 saving: $58,500 (manual research replaced) Year 1 ROI: ($58,500 - $11,313) / $11,313 = 417% Payback period: 7,250 / (58,500 - 4,063) monthly = 1.6 months Year 2+ ongoing ROI: ($58,500 - $4,063) / $4,063 = 1,340% annually Conclusion: Build decision is clear. Proceed.
Done planning? We build it.
This template is built from our experience designing and deploying AI agents for businesses across sales, operations, customer support, and content workflows. We use this exact framework internally before every agent build.
If you have completed this template and are ready to build, we can turn your plan into a production AI agent in 28 days — using Claude, n8n, Supabase, and whatever integrations your workflow requires.
AI Systems Shipped
Agents, RAG, automation
Agent Delivery
Plan to production
Avg Cost Saving
vs manual process replaced
Response Time
On all new enquiries