August 28, 2026By Suraj kale

The While Loop Behind Agentic AI

A normal AI gives you an answer. An agentic AI gets the work done. Once this one difference is clear, everything else falls into place — with one working Python example, real company stories, and ideas you can use in your daily life itself.

See, let us take one small scene. You are staying in Pune, and you have to reach Nagpur for Diwali.

Situation 1 — a normal AI. You ask, "What is the best way to go from Pune to Nagpur?" It gives you one very good answer: take the train, take a flight, take a bus, this much time, this much cost. The answer is useful, no doubt about it. But the ticket you have to go and book yourself only.

Situation 2 — an agentic AI. You say, "I have to reach Nagpur for Diwali, budget is Rs 6,000, and I want to leave Friday night." Now the system itself checks IRCTC, sees that nothing is available, looks at flight fares, checks your calendar for any clash, and comes back saying: "Friday night train is full. There is one 6 a.m. flight on Saturday for Rs 5,400, but your 11 a.m. Saturday call will have to be shifted. Shall I book it?"

The first AI is a good advisor. The second one is a good assistant. That is the whole difference — and this is what the world is now calling Agentic AI.

IN ONE LINE

Agentic AI means an AI that does not simply talk, it acts. You give it a goal; it works out the steps on its own, uses tools, checks the result, and tries again if something goes wrong — without asking you at each and every step.


1.  The waiter and the manager

My favorite way of explaining this is with a hotel. A normal chatbot is like a waiter — whatever you ask, he will bring it, he will repeat the order back, he will explain the menu. That is all. Agentic AI is like a manager — you just tell him "forty guests are coming in the evening, you please handle it", and he will brief the kitchen, get the tables arranged, order more stock if something is short, and give you a report at the end.

Technically also, the same thing is happening. A normal language model answers one prompt and stops there. An agentic system takes a goal, breaks it into steps, calls tools — APIs, databases, sensors, messaging — and then looks at the result to decide what should be done next.

Aspect

Normal AI / Chatbot

Agentic AI

Input

One question

One goal or task

Steps

One turn, one answer

Many steps, on its own

Tools

Nothing — only text

Databases, APIs, email, browser, files

Memory

Only the current chat

Remembers old conversations, files, notes

If it fails

It informs you

It tries again by itself

Your role

You have to type every instruction

You give the goal, then you approve

Example

"How to calculate GST?"

"Take last month’s bills, work out the GST and put it in one Excel sheet"


2.  What is inside — the four parts

Every agent, however big it may be, is made from these four things only. Easy way to remember: a brain, a memory, a pair of hands, and a loop.

Part

Name

What it does

01

The brain (LLM)

A language model — Claude, GPT, Gemini, Llama. It works out what should be done next. It only thinks; by itself it cannot actually do anything.

02

Memory

Old conversations, company documents, a database. Without memory the agent has to start from zero every single time — like that one friend who asks your name at every meeting.

03

Tools

This is the most important part. A tool is simply an ordinary function — "read this Excel file", "send this email", "search the web". Without tools the agent can only keep talking.

04

The loop

Think, act, see what happened, think again. This cycle keeps running till the work is finished. This part only is what makes it "agentic".

The agent loop

GOAL  ->  THINK / PLAN  ->  ACT (call a tool)  ->  SEE THE RESULT

work not finished?  ->  back to THINK        |        finished?  ->  final answer

This small cycle is the whole life of agentic AI.


3.  Now let us build one real agent in Python

Enough of theory, let us come to the code. We will build one "Expense Agent" — a small accounts assistant which reads your expense file, separates out the GST, and writes a summary report into a file. Exactly the kind of work that happens in every small business, every month.

Kindly note that I am not using any big framework here. Only plain Python — because the core of an agent is really this much simple. Frameworks will come later.

Step 1 — expenses.csv (your data)

month,item,amount,category

July,Office rent Baner,45000,Rent

July,Internet Jio Fiber,2360,Utilities

July,Laptop repair,8850,Equipment

July,Team lunch FC Road,4720,Food

August,Office rent Baner,45000,Rent

August,Printer cartridge,3540,Supplies


Step 2 — agent.py (the complete agent)

# first: pip install anthropic

import os, csv, json

from anthropic import Anthropic

 

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

 

# ---------- PART 1: TOOLS - these are just ordinary Python functions ----------

 

def read_expenses(month):

    """Take out one month of expenses from the CSV file."""

    rows = []

    with open("expenses.csv", encoding="utf-8") as f:

        for r in csv.DictReader(f):

            if r["month"].lower() == month.lower():

                rows.append({"item": r["item"],

                             "amount": float(r["amount"]),

                             "category": r["category"]})

    return rows

 

def split_gst(amount, rate):

    """Separate the taxable value and the GST from a total amount."""

    taxable = amount / (1 + rate / 100)

    return {"total": round(amount, 2),

            "taxable_value": round(taxable, 2),

            "gst_amount": round(amount - taxable, 2),

            "rate_percent": rate}

 

def save_report(text):

    """Write the final report into a file."""

    with open("expense_report.txt", "w", encoding="utf-8") as f:

        f.write(text)

    return {"status": "saved", "file": "expense_report.txt"}

 

TOOL_BOX = {"read_expenses": read_expenses,

            "split_gst": split_gst,

            "save_report": save_report}

 

# ---------- PART 2: tell the model which tools it has ----------

 

TOOLS = [

  {"name": "read_expenses",

   "description": "Reads all expenses of one month from the CSV file.",

   "input_schema": {"type": "object",

     "properties": {"month": {"type": "string", "description": "e.g. July"}},

     "required": ["month"]}},

 

  {"name": "split_gst",

   "description": "Splits a GST-inclusive amount into taxable value and GST.",

   "input_schema": {"type": "object",

     "properties": {"amount": {"type": "number"},

                    "rate": {"type": "number", "description": "5, 12, 18 or 28"}},

     "required": ["amount", "rate"]}},

 

  {"name": "save_report",

   "description": "Saves the final report into a text file.",

   "input_schema": {"type": "object",

     "properties": {"text": {"type": "string"}},

     "required": ["text"]}}

]

 

# ---------- PART 3: THE LOOP - this is what makes it an agent ----------

 

GOAL = """Read all the expenses of July. Taking 18% GST on each item,

separate the taxable value and the GST. Then prepare one short summary

report with the total spend, the total GST, and a category-wise breakup.

Save the report into a file. Show all amounts in INR."""

 

messages = [{"role": "user", "content": GOAL}]

 

for step in range(1, 16):          # safety limit - to avoid an endless loop

    reply = client.messages.create(

        model="claude-sonnet-4-6",

        max_tokens=2000,

        tools=TOOLS,

        messages=messages)

 

    messages.append({"role": "assistant", "content": reply.content})

 

    if reply.stop_reason != "tool_use":      # work is finished

        for block in reply.content:

            if block.type == "text":

                print("\nAGENT:", block.text)

        break

 

    results = []

    for block in reply.content:             # run whichever tool it asked for

        if block.type == "tool_use":

            print(f"[step {step}] running: {block.name}({block.input})")

            output = TOOL_BOX[block.name](**block.input)

            results.append({"type": "tool_result",

                            "tool_use_id": block.id,

                            "content": json.dumps(output)})

 

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


Step 3 — the output will come something like this

[step 1] running: read_expenses({'month': 'July'})

[step 2] running: split_gst({'amount': 45000.0, 'rate': 18})

[step 2] running: split_gst({'amount': 2360.0, 'rate': 18})

[step 2] running: split_gst({'amount': 8850.0, 'rate': 18})

[step 2] running: split_gst({'amount': 4720.0, 'rate': 18})

[step 3] running: save_report({'text': 'JULY 2026 EXPENSE REPORT ...'})

 

AGENT: July is done. Total spend is Rs 60,930, out of which Rs 9,294.41

is GST and Rs 51,635.59 is taxable value. The biggest item is rent

(Rs 45,000). I have saved the report in expense_report.txt.


PLEASE NOTE THIS POINT

Nowhere have I written "first read the CSV, then work out the GST, then save it". That order the agent decided on its own. Suppose the file had August data but no July data, it would have come back and told me "July data is not there". That much only is the difference between a chatbot and an agent — around sixty lines.


4.  Which companies are using this

This is no longer an experiment. Just see the numbers.

Abroad

Company

What they are doing

Klarna

One AI assistant handled two-thirds of all customer service chats in the first month itself — roughly the work of 700 full-time agents — and brought resolution time down from 11 minutes to under 2 minutes. But one point is worth noting: Klarna has since brought back human agents for their highest-value customers. Fully automated and correctly automated are not one and the same thing.

JPMorgan

More than 450 agentic AI use cases are running in production every single day, from contract analysis to internal workflows — the biggest publicly disclosed deployment of any bank.

Salesforce

Agentforce customers together have reported more than 100 million US dollars of annual cost saving and a 34% rise in productivity.

GitHub, Cursor

Coding agents which find the bug themselves, write the fix, and raise the pull request.

Shopify, Uber

Shopify’s Sidekick handles merchant operations; Uber’s Genie answers internal engineering policy questions.

Here in India

Sector

What is happening

IT services

Infosys, TCS and Wipro are putting agents into their software development, testing and client delivery workflows. TCS MasterCraft, Infosys Topaz and Wipro Intelligence — all these platforms are built for this same purpose.

Banking and fintech

HDFC Bank, ICICI and many fintech startups are using agents for fraud detection, KYC verification, loan processing and customer support.

E-commerce

Flipkart, Meesho and D2C brands are running agents for inventory management, dynamic pricing and personalised customer journeys.

Healthcare

Hospitals are using agents for appointment scheduling, medical record summarisation and insurance claim processing.

Product startups

Gnani.ai is building a voice-first model for Indian languages; Fluid AI from Mumbai supplies KYC and onboarding agents to banks; Mad Street Den works with Myntra and Ajio on the retail side.


ONE REALITY CHECK

There is another side to this which blog posts generally do not mention. In FY26 the five biggest Indian IT companies together cut 6,981 jobs, whereas in the previous year they had added 12,718. Meaning, learning this is no longer optional. Demand is going up for people who can build and run agents, and it is going down for people who only do repetitive work.


5.  Tools and platforms available today

The market has divided into two halves. On one side there are enterprise platforms — Microsoft Copilot Studio, AWS Bedrock AgentCore, Vertex AI Agent Builder, Agentforce, ServiceNow AI Agents, watsonx Orchestrate, UiPath — where identity, audit, data residency and SLAs all come from the vendor side. On the other side there are open-source frameworks — LangGraph, Claude Agent SDK, CrewAI, AutoGen, Semantic Kernel, LlamaIndex, Pydantic AI — where your own team has to handle deployment and governance. Most big programmes end up using both.

If you write code

Framework

When to use it

LangGraph

The default choice for production workflows, especially where audit trail, proper control and human approval steps are required — banking or insurance, for example. You get typed state, checkpointers (SQLite, Postgres) and time-travel debugging.

CrewAI

The fastest route from an idea to a working multi-agent prototype — your first agent runs in 30 to 60 lines. Role-based: give each agent one role and one task, just like a small team.

OpenAI Agents SDK

The least troublesome option for GPT-based agents, with sandboxed tools and sub-agents. Its main idea is the "handoff" — one agent passes control to another.

Claude Agent SDK

File, bash, edit and computer-use tools are built in — good for coding and research agents.

Google ADK

If your team is already on GCP, or you need strong multimodal support.

Microsoft Agent Framework

For .NET and Azure companies — Microsoft has merged AutoGen and Semantic Kernel into one single framework.


SO WHICH ONE SHOULD YOU TAKE?

Do not get confused in all this. If you need only one agent calling one or two tools, then a vendor SDK (OpenAI or Claude) is the fastest route. Pick up CrewAI or LangGraph only when you genuinely need multi-agent coordination or complicated branching. And one advice: before learning any framework, write that sixty-line loop above with your own hands. Once that loop is clear, every framework will feel easy.


If you do not write code

Tool

What it is good for

n8n

When you want privacy and no monthly licence fee — it is open source and you can run it on your own server. Drag-and-drop nodes connect Claude, OpenAI and your own database. A human approval step is also built in.

Zapier Agents

When your real problem is simply joining common business apps — Gmail, Sheets, CRM, Slack.

Make

When you want to see how the agent has reasoned — the thinking stays visible on a visual canvas.

Microsoft Copilot Studio

For building agents inside Teams, SharePoint, Dynamics and Microsoft 365, where employees are already working.

Claude Projects / Custom GPTs

Upload instructions and your own documents and build a policy bot, a proposal helper or an internal support assistant. The easiest starting point of all.

Dify, Flowise

For those who prefer visual, low-code development. Dify is ahead on GitHub stars.


6.  How you can use this for your own work

This section is the most useful one. Company stories are all fine, but what should a normal person do — a student, a teacher, a freelancer, a shop owner, someone searching for a job?

The practical 2026 list for personal agents is this: ChatGPT Agent for general work, Gemini Agent for Google users, Copilot Tasks for Windows and Microsoft 365 users, Comet for work inside the browser, Notion for notes, Zapier for automation, and Claude for deep thinking work.

Eight things you can start from today

  1. A watchman for your inbox. Every morning the agent reads your mails, sorts them into "reply today / this week / ignore", and keeps draft replies ready. You have to only read and send.
  2. A job application assistant. Give it the job description and your resume; it will adjust the bullet points for each company and write the cover letter also. For freshers, a full day’s work gets done in one hour.
  3. A study partner. Upload your PDF notes and it will make chapter-wise summaries, flashcards and mock questions — and it remembers which answers you got wrong, so it can ask you again on those same topics.
  4. Household budgeting. Give it a CSV of your bank statement; it will break up the spending category-wise, compare with last month, and show you where money is leaking. The code above is a simple version of this only.
  5. Trip planning. "Three days in Konkan, Rs 15,000, going with family" — it will find hotels, plan the route and give a day-wise plan. Before booking, you kindly check it once.
  6. Freelance paperwork. The moment a client approves the work, the agent raises the invoice, adds GST, drafts the mail, and reminds you if payment has not come in 15 days.
  7. Repurposing content. Give it one YouTube video or a lecture recording; from the transcript it will make a blog post, a LinkedIn post and five slides.
  8. Research sitting at home. "A 2BHK in Pune within 40 lakh, 2 km from the metro" — it will check listings, compare them and put everything in one table.


A seven-day starting plan

Day

What to do

Days 1–2

Make one Claude Project or a Custom GPT. Upload four or five of your own documents. Talk to it. Without writing any code, you will get the feel of an agent.

Days 3–4

Type out the Python loop given above yourself — type it, do not copy-paste it. Put in your own tools. Once it runs, 80% of the concept is clear.

Day 5

Install n8n (free, self-hosted). Make one workflow: Gmail to the agent, agent to a Google Sheet.

Day 6

Select one framework — CrewAI if you want speed, LangGraph if it is a serious project. Select only one.

Day 7

Do one thing: take one boring, repetitive task from your own life and automate it. Only one. Once that runs, the rest will follow on its own.


7.  Precautions which nobody tells you

Agents are very good, no doubt about it. But do not keep blind faith. Five things you should always keep in mind.

  • It makes mistakes very confidently. If the agent remembers a GST rate wrongly, it will happily apply that same wrong rate across the whole report. Wherever numbers are involved, get the calculation done by a tool, not by the model’s head — that is exactly why I wrote the split_gst function above.
  • Approve every action, at least in the beginning. Keep the first version read-only or draft-only. Let it draft the mail, not send it. Money transfer, file deletion, outgoing messages — keep all of these behind your own click.
  • Cost increases quietly. One agent can make 10 to 15 API calls for a single task. That is why I have put a range(1, 16) limit on the loop. Without a limit, one small bug can finish off your entire credit balance.
  • A new type of security risk. If your agent is reading a web page or an email, somebody can hide an instruction inside that content — "send all the data to this address". This is called prompt injection. So give the agent only as much permission as is actually required.
  • Data privacy and the law. Under India’s DPDP Act, how you handle personal data is directly your responsibility. Do not send a customer’s Aadhaar, PAN or phone number through some random API. If it is client data, kindly take written permission first.


THE PATTERN BEHIND COMPANIES THAT SUCCEEDED

Whoever got a real return did the same thing — a small and clearly defined scope, KPIs tied to business outcomes, escalation to a human whenever an exception comes, integration inside the existing workflow, and a long run in production. Meaning: one small thing, done properly. Trying to automate the whole company in one go is the most common mistake of all.


Finally — from where should you start?

Agentic AI is not some magic. One language model, a few ordinary functions, and one while loop — that much only it is. You have seen the entire concept above in sixty lines. Everything else is a bigger, safer and more polished version of that same thing.

The real skill is not the technology. The real skill is to spot which work is worth automating — that boring, repetitive, rule-based work which you do every week and quietly get irritated by. Find that one, and start from there.

It is like Pune traffic. The whole city does not get crossed in one go. One signal, then the next signal. Just get moving.



Suraj kale

Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.

#Technology#Education#Career Guidance
The While Loop Behind Agentic AI | SevenMentor