AI Agents and Agentic AI are often used interchangeably, but they're not the same. In this guide, we'll break down the differences, explore real-world use cases, and help you understand when to build an AI agent and when you need a coordinated agentic system.

An AI agent does one job well. Agentic AI pursues a goal across many jobs, many tools, and many decisions, autonomously. One is a specialist. The other is a coordinator. Gartner expects 40% of enterprise applications to include AI agents by 2026, up from under 5% last year. Most teams reaching for agentic AI actually need a single well-scoped agent. This guide explains the real difference, when each applies, and how to build both, starting today.

The Word That Is Breaking AI Projects

"Agent" is the most overloaded word in AI right now.

Your company's customer service chatbot is called an agent. The autonomous system that coordinates your entire procurement workflow is also called an agent. The tool that summarises your meeting notes is called an agent. The pipeline that monitors production systems, diagnoses incidents, and opens Jira tickets is also called an agent.

They are not the same thing.

And treating them as the same thing is one of the most reliable ways to stall an AI project before it delivers anything. You build something too simple for a complex goal. Or you build something too complex, and too brittle, for a simple task. Either way, the project gets shelved.

The distinction that matters is this:

An AI agent executes a task.

Agentic AI pursues a goal.

That sentence does not fully capture it yet. Let me make it concrete.

Part 1: What an AI Agent Actually Is

The Real Definition

An AI agent is a software system that perceives inputs, makes decisions within defined boundaries, and takes actions to complete a specific, well-defined task, usually without constant human input.

The key phrase: specific, well-defined task.

An AI agent knows what it is supposed to do. It knows where it starts and where it ends. It has a defined set of tools it can use. It operates within boundaries someone set deliberately. It does not invent new goals. It does not decide on its own to do something you did not ask for.

Think of it like a specialist contractor. You hire a plumber to fix a leaking pipe. They show up, fix the pipe, and leave. They do not redesign your bathroom. They do not start checking your electrical wiring. They do one job, do it well, and are done.

An AI agent is that plumber.

What an AI Agent Looks Like in Code

Here is the simplest possible AI agent. It takes a customer support ticket, classifies it, and routes it to the right team:

```
import anthropic
import json
import os
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
def classify_and_route_ticket(ticket_text: str) -> dict:"""
AI Agent: Ticket Classification and Routing

Single task: Read a support ticket, classify it, 
return which team should handle it.

That's it. Nothing more.
"""

response = client.messages.create(model="claude-3-5-haiku-20241022",max_tokens=300,system="""You are a customer support ticket classifier.

Your ONLY job is to classify tickets into one of these categories:
- BILLING: Payment issues, invoices, refunds, subscription questions
- TECHNICAL: Bugs, errors, performance issues, integrations
- ACCOUNT: Login, password, account settings, access
- GENERAL: Questions, feedback, feature requests
Return ONLY valid JSON in this exact format:
{
"category": "BILLING|TECHNICAL|ACCOUNT|GENERAL",
"priority": "LOW|MEDIUM|HIGH|CRITICAL",
"reason": "one sentence explaining the classification",
"suggested_team": "billing-team|tech-support|account-team|general-support"
}""",messages=[{"role": "user","content": f"Classify this ticket:\n\n{ticket_text}"}])

# Parse and return the structured result
raw = response.content[0].text.strip()return json.loads(raw)

Use it

ticket = """
Hi, I was charged twice for my subscription this month.
I see two charges of $49 on July 15 and July 16.
I need one of these refunded ASAP. Order #12345.
"""
result = classify_and_route_ticket(ticket)
print(json.dumps(result, indent=2))

Output:

{

"category": "BILLING",

"priority": "HIGH",

"reason": "Customer reports duplicate charge and requests immediate refund",

"suggested_team": "billing-team"

}

```
Notice what this agent does NOT do:

  • It does not check the customer's account
  • It does not look up the transaction
  • It does not issue the refund
  • It does not send an email
  • It does not open a ticket in Jira

It classifies. That is its entire job. And it does that one job reliably, quickly, and with clear output.

Real-World AI Agent Use Cases

These are the things AI agents are being deployed for right now, in production, at scale:

  • Customer support routing:classify incoming tickets by category, priority, and sentiment. Route to the right queue. No human needed for the routing decision.
  • Document data extraction:read an invoice, extract vendor name, amount, due date, line items. Output structured JSON. Feed into accounts payable.
  • Meeting note summarisation:take a transcript, produce a structured summary with key decisions and action items. One in, one structured output.
  • Code review pre-screening:scan a pull request for common issues (missing tests, hardcoded values, known anti-patterns) before it hits a human reviewer.
  • HR policy Q&A:answer employee questions about leave policies, benefits, and procedures using a RAG knowledge base. Scope limited to HR documents only.
  • Email triage:classify inbound sales emails as high-priority lead, existing customer, or general enquiry. Route accordingly.

The pattern across all of these: one input, defined processing, one structured output. The task is well understood. The boundaries are clear. The success metric is measurable.

Part 2: What Agentic AI Actually Is

The Real Definition

Agentic AI is an approach to building systems that pursue high-level goals by planning, reasoning across multiple steps, and coordinating multiple agents, tools, and data sources, with minimal human intervention at each step.

The key phrases: high-level goals, multiple steps, minimal human intervention.

Agentic AI does not just execute. It thinks about what needs to happen to achieve a goal. It breaks that goal into steps. It decides which tools to use for each step. It handles failures and adapts. It may spawn and coordinate multiple agents. It operates until the goal is reached or it determines the goal cannot be reached.

Think of it like a project manager. You tell them "deliver the new customer portal by end of quarter." They figure out the plan, what teams are involved, what needs to happen in what order, what blockers exist, what decisions need to be made. They coordinate the specialists. They adapt when things go wrong.

Agentic AI is that project manager.

The Four Properties That Define Agentic AI

Not every system calling itself agentic actually is. These are the four properties that define genuine agentic AI:

1. Goal-directed planning: given a high-level objective, the system creates its own plan for achieving it, rather than following a predefined script.

2. Multi-step reasoning: the system can chain multiple decisions and actions together, using the output of one step as the input to the next, adapting as it goes.

3. Tool orchestration: the system selects and calls different tools, APIs, or agents based on what is needed at each step. It is not limited to a fixed sequence.

4. Adaptive recovery: when a step fails or produces unexpected results, the system reasons about what went wrong and tries an alternative approach. It does not just crash.

What Agentic AI Looks Like in Code

Here is an agentic AI system that handles the full customer refund request, not just classifying it, but actually resolving it end-to-end:

```
import anthropic
import json
import os
from datetime import datetime
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

── Tool definitions β€” the things the agent can DO ─────────────

tools = [{"name": "lookup_customer","description": "Look up a customer's account details and subscription status by email or order ID","input_schema": {"type": "object","properties": {"identifier": {"type": "string","description": "Customer email address or order ID"}},"required": ["identifier"]}},{"name": "get_transaction_history","description": "Retrieve all transactions for a customer in the last 90 days","input_schema": {"type": "object","properties": {"customer_id": {"type": "string","description": "The customer's internal ID"},"days": {"type": "integer","description": "Number of days of history to retrieve","default": 30}},"required": ["customer_id"]}},{"name": "check_refund_eligibility","description": "Check if a transaction is eligible for a refund based on company policy","input_schema": {"type": "object","properties": {"transaction_id": {"type": "string","description": "The transaction ID to check"}},"required": ["transaction_id"]}},{"name": "issue_refund","description": "Issue a refund for a specific transaction. Only call this after confirming eligibility.","input_schema": {"type": "object","properties": {"transaction_id": {"type": "string","description": "The transaction ID to refund"},"reason": {"type": "string","description": "The reason for the refund"}},"required": ["transaction_id", "reason"]}},{"name": "send_email","description": "Send an email to the customer with the resolution details","input_schema": {"type": "object","properties": {"customer_email": {"type": "string","description": "Customer email address"},"subject": {"type": "string","description": "Email subject line"},"body": {"type": "string","description": "Email body text"}},"required": ["customer_email", "subject", "body"]}},{"name": "create_internal_note","description": "Create an internal case note recording what was done and why","input_schema": {"type": "object","properties": {"customer_id": {"type": "string","description": "Customer ID"},"note": {"type": "string","description": "The internal case note"}},"required": ["customer_id", "note"]}}
]

── Mock tool implementations ───────────────────────────────────

In production these would call real APIs

def execute_tool(tool_name: str, tool_input: dict) -> str:"""Execute a tool call and return the result as a string"""

print(f"\n  β†’ Calling tool: {tool_name}")print(f"    Input: {json.dumps(tool_input, indent=6)}")

if tool_name == "lookup_customer":
    result = {"customer_id": "cust_7Km3pQx9","email": "emma@example.com","name": "Emma Johnson","subscription": "Professional","subscription_start": "2025-01-15","status": "active"}

elif tool_name == "get_transaction_history":
    result = {"customer_id": tool_input["customer_id"],"transactions": [{"id": "txn_abc001","date": "2026-07-15","amount": 49.00,"description": "Professional Plan - July","status": "completed"},{"id": "txn_abc002","date": "2026-07-16","amount": 49.00,"description": "Professional Plan - July","status": "completed"}]}

elif tool_name == "check_refund_eligibility":
    result = {"transaction_id": tool_input["transaction_id"],"eligible": True,"reason": "Duplicate charge detected β€” same plan, consecutive days","refund_amount": 49.00}

elif tool_name == "issue_refund":
    result = {"refund_id": f"ref_{datetime.now().strftime('%Y%m%d%H%M%S')}","transaction_id": tool_input["transaction_id"],"amount": 49.00,"status": "processed","expected_arrival": "3-5 business days"}

elif tool_name == "send_email":
    result = {"sent": True,"to": tool_input["customer_email"],"subject": tool_input["subject"],"timestamp": datetime.now().isoformat()}

elif tool_name == "create_internal_note":
    result = {"note_id": "note_12345","created_at": datetime.now().isoformat(),"status": "saved"}

else:
    result = {"error": f"Unknown tool: {tool_name}"}

print(f"    Result: {json.dumps(result, indent=6)}")return json.dumps(result)

── The agentic AI loop ─────────────────────────────────────────

def handle_refund_request_agentically(ticket_text: str) -> str:"""
Agentic AI: Full Refund Resolution

Goal: Fully resolve a customer refund request end-to-end.

The agent decides:
- What information to gather
- Which transactions to investigate  
- Whether to issue a refund
- What to communicate to the customer
- What internal record to create

It keeps going until the goal is achieved.
"""

print("\n" + "="*60)print("AGENTIC AI: Starting refund resolution")print("="*60)

messages = [{"role": "user","content": f"""Resolve this customer support request completely.

Your goal: Fully resolve the customer's issue end-to-end.
This means: understand the issue, investigate, take the correct
action, notify the customer, and create an internal record.
Do NOT stop after any single step. Keep going until the issue
is fully resolved and the customer has been notified.
Customer request:
{ticket_text}"""}]

system_prompt = """You are an autonomous customer support agent.

Your job is to fully resolve customer issues end-to-end.
You have tools to look up accounts, check transactions, issue refunds,
send emails, and create internal notes.
IMPORTANT RULES:
1. Always verify the customer exists before taking action
2. Always check refund eligibility before issuing a refund
3. Never issue duplicate refunds
4. Always notify the customer after resolution
5. Always create an internal note recording what you did and why
6. If you cannot resolve something, explain clearly why
Think step by step. Use your tools in the right order.
Keep working until the issue is FULLY resolved."""
# The agentic loop β€” keeps running until the agent decides it's done
max_iterations = 10
iteration = 0

while iteration < max_iterations:
    iteration += 1print(f"\n--- Iteration {iteration} ---")

    response = client.messages.create(model="claude-opus-4-7-20250514",max_tokens=2000,system=system_prompt,tools=tools,messages=messages
    )

    print(f"Stop reason: {response.stop_reason}")

    # If the agent has finished β€” no more tool callsif response.stop_reason == "end_turn":
        final_text = next((block.text for block in response.content 
             if hasattr(block, "text")),"Resolution complete.")print(f"\n{'='*60}")print("AGENTIC AI: Goal achieved")print(f"{'='*60}")print(f"\nFinal summary:\n{final_text}")return final_text

    # If the agent wants to use tools β€” execute them allif response.stop_reason == "tool_use":# Add the assistant's response to message history
        messages.append({"role": "assistant","content": response.content
        })

        # Execute each tool call and collect results
        tool_results = []for block in response.content:if block.type == "tool_use":
                tool_result = execute_tool(block.name, block.input)
                tool_results.append({"type": "tool_result","tool_use_id": block.id,"content": tool_result
                })

        # Feed the tool results back to the agent
        messages.append({"role": "user","content": tool_results
        })

return "Max iterations reached β€” escalating to human agent"

Run the agentic system

ticket = """
Hi, I was charged twice for my subscription this month.
I see two charges of $49 on July 15 and July 16 on my card.
My order reference is #12345. Please refund the duplicate charge ASAP.
- Emma
"""
result = handle_refund_request_agentically(ticket)
```

What this agent actually does autonomously, in sequence:

  • Reads the ticket and decides to look up the customer by order ID
  • Calls lookup_customerβ†’ gets customer ID and email
  • Calls get_transaction_historyβ†’ finds two $49 charges on consecutive days
  • Recognises this as a duplicate charge
  • Calls check_refund_eligibilityon the second transaction β†’ confirms eligible
  • Calls issue_refundβ†’ processes the refund
  • Calls send_emailβ†’ notifies Emma her refund is on the way
  • Calls create_internal_noteβ†’ records the full resolution
  • Reports done

You gave it a goal. It decided the steps. It used the right tools in the right order. It resolved the issue end-to-end without you telling it what to do at each step.

That is agentic AI.

Part 3: The Difference Side By Side

Now that you have seen both in code, here is the complete comparison:

| Property | AI Agent | Agentic AI |
|---|---|---|
| Goal type | Specific task | Broad objective |
| Steps | Usually one or two | Many decided at runtime |
| Tools | Fixed, predefined set | Dynamic selects from available tools |
| Human oversight | Clear handoff point | Minimal during execution |
| Adaptability | Limited fails if input unexpected | High reasons around failures |
| Predictability | Very predictable | Less predictable |
| Auditability | Easy one action, clear output | Harder many steps, complex trace |
| Cost | Low per call | Higher many model calls per task |
| Time to build | Hours to days | Days to weeks |
| Time to trust | Fast easy to test edge cases | Slower harder to test all paths |
| Best for | High-volume, repeatable tasks | Complex, multi-step goals |

The line from the ERP Software Blog cuts right to it: "The practical difference between an AI agent and agentic AI is the difference between a tool that completes a defined task and a system that can plan, reason across several steps, and adapt its way toward a broader goal."

Part 4 β€”The Decision Framework: Which One Do You Actually Need?

This is the question that determines whether your AI project ships or stalls.

Start With an AI Agent When:

The task is well-defined and repeatable. You can describe exactly what goes in, exactly what should come out, and exactly what constitutes success. If you can write this as a test case with known inputs and expected outputs, it is an agent task.

Volume matters more than complexity. You need to process 10,000 customer emails a day, not solve a different complex problem each time. Agents are fast, cheap, and reliable at scale.

Failure needs to be obvious. If the agent cannot complete the task, it should fail clearly rather than attempting something unexpected. Agents do this naturally. Agentic systems sometimes take creative wrong turns.

You need a quick win. A well-scoped AI agent can be built, tested, and deployed in days. Use agents to demonstrate early value, build confidence, and learn what works before tackling more complex agentic systems.

The task lives within one system. Classifying a ticket, extracting data from a document, summarising a meeting, these happen in one place, with one data source, and one clear output.

Examples that fit perfectly:

  • Ticket routing and classification
  • Invoice data extraction
  • Meeting note summarisation
  • Code pre-review (common pattern detection)
  • FAQ answering from a knowledge base
  • Email subject line generation
  • Sentiment analysis on customer feedback
  • Fraud signal scoring on a transaction

Use Agentic AI When:

The goal requires planning you cannot script in advance. "Resolve this customer complaint" is not scriptable, the steps depend entirely on what the complaint is, what the customer's history shows, and what policies apply. A human would figure this out at runtime. An agentic system can too.

Multiple systems need to be coordinated. The task involves reading from a CRM, checking a database, calling an external API, writing to a ticketing system, and sending an email, with each step depending on the result of the last. This is orchestration. Agents do not orchestrate. Agentic systems do.

The environment is dynamic. The right sequence of steps cannot be known until the system starts executing, because what comes next depends on what it finds. Agentic systems handle this. Fixed-sequence agents do not.

The cost of human oversight is high. If routing every complex decision back to a human defeats the purpose of automation, you need a system capable of making those decisions autonomously, within defined authority boundaries.

You have mature AI agent building blocks. Agentic systems are more reliable when built from tested, well-scoped agents that it orchestrates. If you have not yet built and validated individual agents, building an agentic system on top of untested components is risky.

Examples that fit perfectly:

  • End-to-end customer complaint resolution
  • Automated software incident response (detect β†’ diagnose β†’ fix β†’ notify)
  • Sales pipeline management (lead β†’ qualify β†’ personalise outreach β†’ follow up)
  • Supply chain exception handling
  • Regulatory compliance monitoring and remediation
  • Full-cycle code review (analyse β†’ suggest β†’ create PR β†’ run tests)

The Test That Settles It

If you are still unsure, apply this test:

Write down the steps your process requires.

If you can write them down before the agent runs: "step 1 is always X, step 2 is always Y, step 3 is always Z" , you need an AI agent.

If the steps depend on what the system finds at each step: "step 1 varies, step 2 depends on step 1's result, step 3 may or may not be necessary", you need agentic AI.

The inability to write down the steps in advance is the most reliable signal that you are in agentic territory.

Part 5: Building Your First AI Agent : Step by Step

Let us build a complete, production-ready AI agent from scratch. This one extracts structured data from job postings β€” a real, useful task.

Step 1: Set Up

pip install anthropic python-dotenv

```

.env

ANTHROPIC_API_KEY=sk-ant-your-key-here
```

Step 2: Build the Agent

```

job_extraction_agent.py

import anthropic
import json
import os
from dataclasses import dataclass, asdict
from typing import Optional
from dotenv import load_dotenv
load_dotenv()
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
@dataclass
class JobPosting:"""Structured representation of a job posting"""
title: str
company: str
location: str
remote_allowed: bool
salary_min: Optional[int]
salary_max: Optional[int]
salary_currency: Optional[str]
required_years_experience: Optional[int]
required_skills: list[str]
nice_to_have_skills: list[str]
seniority_level: str # junior, mid, senior, principal, staff
employment_type: str # full-time, part-time, contract, freelance
visa_sponsorship: bool
application_deadline: Optional[str]
def extract_job_details(job_posting_text: str) -> JobPosting:"""
AI Agent: Job Posting Data Extractor

Input: Raw job posting text (any format)
Output: Structured JobPosting object

This is a classic AI agent β€” one clear task,
well-defined input, structured output.
"""

schema = {"title": "string β€” exact job title","company": "string β€” company name","location": "string β€” city and country, or 'Remote'","remote_allowed": "boolean","salary_min": "integer or null β€” minimum salary in local currency","salary_max": "integer or null β€” maximum salary in local currency","salary_currency": "3-letter code (GBP, USD, EUR) or null","required_years_experience": "integer or null","required_skills": "array of strings β€” must-have technical skills","nice_to_have_skills": "array of strings β€” optional/preferred skills","seniority_level": "junior|mid|senior|principal|staff","employment_type": "full-time|part-time|contract|freelance","visa_sponsorship": "boolean β€” true if company sponsors visas","application_deadline": "YYYY-MM-DD string or null"}

response = client.messages.create(model="claude-3-5-haiku-20241022",  # Fast + cheap = perfect for agentsmax_tokens=1000,system=f"""You are a job posting data extractor.

Extract structured data from job postings and return ONLY valid JSON.
No explanation. No markdown. Just the JSON object.
Required schema:
{json.dumps(schema, indent=2)}
Rules:
- If information is not mentioned, use null for optional fields
- For required_skills: only include explicitly required skills, not preferred ones
- For seniority_level: infer from years of experience and title if not stated
- For visa_sponsorship: default to false if not mentioned
- For remote_allowed: true if "remote", "hybrid", or "work from home" is mentioned""",messages=[{"role": "user","content": f"Extract data from this job posting:\n\n{job_posting_text}"}])

raw_json = response.content[0].text.strip()
data = json.loads(raw_json)return JobPosting(**data)

def process_job_postings_batch(postings: list[str]) -> list[dict]:"""Process multiple job postings efficiently"""
results = []

for i, posting in enumerate(postings, 1):print(f"Processing posting {i}/{len(postings)}...")try:
        job = extract_job_details(posting)
        results.append({"status": "success","data": asdict(job)})except json.JSONDecodeError as e:
        results.append({"status": "error","error": f"JSON parsing failed: {e}"})except Exception as e:
        results.append({"status": "error","error": str(e)})

return results

Test it with a real job posting

sample_posting = """
Solutions Architect β€” AWS (Senior Level)
SoftLed Technologies | London, UK (Hybrid β€” 3 days office)
We are looking for a Senior Solutions Architect with deep AWS expertise
to join our growing cloud team. You will lead technical pre-sales,
design enterprise cloud architectures, and support our customers'
digital transformation journeys.
What you'll need:
- 6+ years of cloud architecture experience (AWS required)
- AWS Solutions Architect Professional certification
- Strong background in Kubernetes (EKS preferred)
- Experience with DevSecOps and CI/CD pipelines
- Excellent communication skills for executive audiences
Nice to have:
- Multi-cloud experience (Azure, GCP)
- Open source contributions (CNCF ecosystem)
- Experience with AI/ML workloads on AWS
Salary: Β£85,000 β€” Β£110,000 + equity
We do not currently offer visa sponsorship.
Applications close: 2026-09-01
"""
result = extract_job_details(sample_posting)
print(json.dumps(asdict(result), indent=2))

Output:

{

"title": "Solutions Architect",

"company": "SoftLed Technologies",

"location": "London, UK",

"remote_allowed": true,

"salary_min": 85000,

"salary_max": 110000,

"salary_currency": "GBP",

"required_years_experience": 6,

"required_skills": ["AWS", "Kubernetes", "EKS", "DevSecOps", "CI/CD"],

"nice_to_have_skills": ["Azure", "GCP", "open source", "AI/ML workloads"],

"seniority_level": "senior",

"employment_type": "full-time",

"visa_sponsorship": false,

"application_deadline": "2026-09-01"

}

```
This is a clean, production-ready AI agent. One task. Structured output. Handles batches. Has error handling. Uses a fast, cheap model (Haiku) because the task does not need Opus-level intelligence.

Part 6: Building Your First Agentic AI System: Step by Step

Now let us build an agentic system. This one handles a complete software incident, from detection to resolution to post-mortem, autonomously.

```

incident_response_agent.py

import anthropic
import json
import os
from datetime import datetime
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

Tools the agent can use

tools = [{"name": "check_system_metrics","description": "Get current system metrics for a service (CPU, memory, error rate, latency)","input_schema": {"type": "object","properties": {"service_name": {"type": "string","description": "Name of the service to check"}},"required": ["service_name"]}},{"name": "search_logs","description": "Search application logs for errors or patterns in the last N minutes","input_schema": {"type": "object","properties": {"service_name": {"type": "string"},"query": {"type": "string", "description": "Search query or error pattern"},"minutes": {"type": "integer", "description": "How many minutes to look back", "default": 30}},"required": ["service_name", "query"]}},{"name": "check_recent_deployments","description": "Check if there were any deployments in the last N hours that could have caused the issue","input_schema": {"type": "object","properties": {"service_name": {"type": "string"},"hours": {"type": "integer", "default": 6}},"required": ["service_name"]}},{"name": "rollback_deployment","description": "Rollback a service to its previous deployment. Only use when deployment is confirmed as the cause.","input_schema": {"type": "object","properties": {"service_name": {"type": "string"},"reason": {"type": "string", "description": "Documented reason for rollback"}},"required": ["service_name", "reason"]}},{"name": "scale_service","description": "Scale a service up or down (adjust replica count)","input_schema": {"type": "object","properties": {"service_name": {"type": "string"},"replicas": {"type": "integer", "description": "Target number of replicas"},"reason": {"type": "string"}},"required": ["service_name", "replicas", "reason"]}},{"name": "notify_team","description": "Send an incident notification to the engineering team via Slack","input_schema": {"type": "object","properties": {"severity": {"type": "string", "enum": ["P1", "P2", "P3"]},"message": {"type": "string"},"channel": {"type": "string", "default": "#incidents"}},"required": ["severity", "message"]}},{"name": "create_incident_report","description": "Create a formal incident report documenting the timeline, root cause, and resolution","input_schema": {"type": "object","properties": {"title": {"type": "string"},"timeline": {"type": "string"},"root_cause": {"type": "string"},"resolution": {"type": "string"},"prevention": {"type": "string"}},"required": ["title", "timeline", "root_cause", "resolution"]}}
]
def execute_tool(tool_name: str, tool_input: dict) -> str:"""Mock tool execution β€” replace with real implementations"""print(f" β†’ {tool_name}({json.dumps(tool_input)})")

results = {"check_system_metrics": {"service": tool_input.get("service_name"),"cpu_percent": 94,"memory_percent": 87,"error_rate_percent": 23.4,"p99_latency_ms": 4800,"healthy_pods": 2,"total_pods": 3},"search_logs": {"matches": 847,"sample_errors": ["OutOfMemoryError: Java heap space at TaskService.processBatch():234","Connection timeout after 5000ms to database pool","GC overhead limit exceeded"],"first_occurrence": "2026-07-22T03:17:34Z","frequency": "increasing"},"check_recent_deployments": {"deployments": [{"timestamp": "2026-07-22T02:45:00Z","version": "v2.3.1","change": "Increased batch job size from 1000 to 50000 records","deployed_by": "automated-pipeline"}]},"rollback_deployment": {"status": "success","rolled_back_to": "v2.3.0","time_taken_seconds": 45},"scale_service": {"status": "success","previous_replicas": 3,"current_replicas": tool_input.get("replicas", 3)},"notify_team": {"sent": True,"channel": tool_input.get("channel", "#incidents"),"timestamp": datetime.now().isoformat()},"create_incident_report": {"report_id": "INC-2026-0722-001","status": "created","url": "https://incidents.company.internal/INC-2026-0722-001"}}

result = results.get(tool_name, {"error": f"Unknown tool: {tool_name}"})print(f"    ← {json.dumps(result)}")return json.dumps(result)

def respond_to_incident(alert: str) -> str:"""
Agentic AI: Full Incident Response System

Goal: Detect, diagnose, resolve, and document a production incident
autonomously β€” without human intervention for each step.

The agent decides:
- What to investigate first
- What the root cause is
- What the right remediation is
- Whether to rollback, scale, or take other action
- Who to notify and when
- What the incident report should say
"""

print(f"\n{'='*60}")print("INCIDENT RESPONSE AGENT: Starting investigation")print(f"{'='*60}")print(f"Alert: {alert}\n")

messages = [{"role": "user","content": f"""Investigate and resolve this production incident completely.

Your goal: Identify the root cause, implement a fix, notify the team,
and create an incident report. Do not stop until the incident is
fully resolved and documented.
Alert: {alert}
Timestamp: {datetime.now().isoformat()}"""}]

system_prompt = """You are an autonomous incident response agent for a production system.

When an incident alert comes in, you:
1. Investigate systematically β€” check metrics, logs, and recent changes
2. Form a hypothesis about the root cause based on evidence
3. Implement the most appropriate fix (rollback, scale, or other action)
4. Notify the team with clear, factual information
5. Create a complete incident report
Decision rules:
- If a recent deployment correlates with the incident start time,
rollback is the first action to consider
- If resource exhaustion (CPU/memory) is the issue without a
deployment correlation, scaling may help temporarily
- Always notify the team BEFORE taking remediation action
- Always create an incident report AFTER resolution
Be decisive. Use evidence to make decisions.
Document your reasoning at each step."""
iteration = 0
max_iterations = 15

while iteration < max_iterations:
    iteration += 1print(f"\n--- Agent iteration {iteration} ---")

    response = client.messages.create(model="claude-opus-4-7-20250514",max_tokens=2000,system=system_prompt,tools=tools,messages=messages
    )

    print(f"Stop reason: {response.stop_reason}")

    if response.stop_reason == "end_turn":
        final_text = next((block.text for block in response.content 
             if hasattr(block, "text")),"Incident resolved.")print(f"\n{'='*60}")print("INCIDENT RESPONSE AGENT: Resolution complete")print(f"{'='*60}\n{final_text}")return final_text

    if response.stop_reason == "tool_use":
        messages.append({"role": "assistant","content": response.content
        })

        tool_results = []for block in response.content:if block.type == "tool_use":
                result = execute_tool(block.name, block.input)
                tool_results.append({"type": "tool_result","tool_use_id": block.id,"content": result
                })

        messages.append({"role": "user","content": tool_results
        })

return "Max iterations reached β€” escalating to on-call engineer"

Trigger the agentic system with an alert

alert = """
CRITICAL ALERT β€” payment-service
Error rate: 23.4% (threshold: 1%)
P99 latency: 4800ms (threshold: 500ms)
2/3 pods healthy
Alert triggered: 2026-07-22T03:20:00Z
"""
respond_to_incident(alert)
```

What this agentic system does all on its own:

  • Calls check_system_metrics:confirms the service is in trouble
  • Calls search_logs:finds OutOfMemoryError pattern since 03:17
  • Calls check_recent_deployments:finds a deployment at 02:45 that increased batch size from 1,000 to 50,000 records
  • Connects the dots: deployment β†’ increased memory usage β†’ OOM errors β†’ high error rate
  • Calls notify_teamwith a P1 alert before taking action
  • Calls rollback_deploymentto v2.3.0
  • Calls check_system_metricsagain to confirm recovery
  • Calls create_incident_reportdocumenting the full timeline, root cause, and prevention steps
  • Reports complete

You gave it one alert. It investigated, diagnosed, fixed, notified, and documented, entirely on its own. That is agentic AI.

Part 7: The Architecture Patterns

Pattern 1: Single Agent (Most Common)

Input β†’ AI Agent β†’ Structured Output
Use this for 80% of AI tasks. Simple, fast, reliable, cheap.

Pattern 2: Pipeline of Agents

Raw Input β†’ Agent 1 (Extract) β†’ Agent 2 (Classify) β†’ Agent 3 (Format) β†’ Output
Use when you have sequential steps where each step has a clear, well-defined task. Each agent is still simple β€” the pipeline handles complexity.

Pattern 3: Orchestrator + Workers (True Agentic AI)

Goal ↓ Orchestrator Agent (plans and coordinates) / | \ Worker 1 Worker 2 Worker 3 (search) (analyse) (act)

Use when the task requires dynamic coordination. The orchestrator reasons about what needs to happen. The workers execute specific tasks. This is the architecture that handles genuinely complex goals.

Pattern 4: Human-in-the-Loop Agentic

Agent plans β†’ Human approves β†’ Agent executes β†’ Human reviews β†’ Agent documents
Use when actions have high stakes or irreversible consequences. The agent handles investigation and planning. Humans approve consequential actions. This gives you agentic efficiency with human accountability.

Part 8: The Safety Rules Nobody Tells You First

Agentic AI systems can take real actions with real consequences. These rules are not optional.

Rule 1: Start with read-only tools. Build and test the system with tools that only read data before adding tools that write, update, or delete. Understand its reasoning before you trust it with write access.

Rule 2: Add human confirmation for irreversible actions. Rolling back a deployment, sending external emails, deleting records, processing refunds, anything that cannot be easily undone should have a human approval step until you have deeply validated the system's judgment.

Rule 3: Set a maximum iteration limit. Always cap how many steps the system can take without completing. A runaway agent loop can be expensive and unpredictable. Max 10–15 iterations is a reasonable starting point.

Rule 4: Log everything. Every tool call, every result, every decision the agent makes should be logged with enough detail to reconstruct exactly what happened. When something goes wrong, and it will, you need the full trace.

Rule 5: Test with chaos. Before production, deliberately give the agent bad inputs, unavailable tools, and contradictory information. How does it fail? Does it fail gracefully or does it take a wrong action confidently?

Rule 6: Define the blast radius. Before giving an agent any capability, ask: if this agent makes the worst possible decision using this tool, what is the impact? Size the guardrails to the blast radius. A customer email agent needs different safeguards than a financial transaction agent.

The Bottom Line

Gartner predicts 40% of enterprise applications will include AI agents by 2026. McKinsey reports 62% of organisations are already using them. The technology is here. The question is not whether to use it. The question is which kind.

Use an AI agent when you have a specific, high-volume, repeatable task with a clear input and a defined output. Build it in days. Measure it. Ship it.

Use agentic AI when you have a complex, multi-step goal that requires planning, tool orchestration, and adaptive decision-making. Build it carefully. Test it thoroughly. Deploy it with appropriate human oversight.

And remember the most important rule of all: most teams that think they need agentic AI actually need a well-scoped agent. Start with the simpler thing. Add complexity only when you have proven the simpler thing is not enough.

The best agentic system is the one that ships. Start with an agent.

Quick Reference: When to Use What

```
ONE TASK, CLEAR OUTPUT β†’ AI Agent


Ticket classification β†’ Agent
Invoice data extraction β†’ Agent
Meeting summarisation β†’ Agent
FAQ answering (RAG-based) β†’ Agent
Email sentiment analysis β†’ Agent
Code pre-review (pattern check) β†’ Agent


MULTI-STEP, BROAD GOAL β†’ Agentic AI

Full complaint resolution β†’ Agentic
Production incident response β†’ Agentic
Sales pipeline automation β†’ Agentic
End-to-end code review + PR β†’ Agentic
Supply chain exception handling β†’ Agentic
Research + report generation β†’ Agentic


STILL UNSURE?
Can you write down every step before it runs? β†’ Agent
Steps depend on what it finds at runtime? β†’ Agentic
```

References

  • Gartner. Predicts 40% of Enterprise Applications Will Include AI Agents in 2026.https://www.gartner.com/en/newsroom
  • McKinsey. 62% of Organizations Are Already Using AI Agents.https://www.mckinsey.com/capabilities/quantumblack/our-insights/the-state-of-ai
  • Anthropic. Claude API Documentation β€” Tool Use.https://docs.anthropic.com/claude/docs/tool-use