
How to Make Your Existing App Agentic (Without the Hype or a Rewrite) đ¤
Published
From the course: Building AI Agents, session 1: Tool Use and Function Calling
Your manager just asked, âCan we make the app agentic?â đ You have a working app with tested functions, a database and real users. You donât want to throw any of that away.
Good news: you shouldnât. An agent is not a new app. Itâs a small loop that lets a language model choose which of your existing functions to call. By the end of this post youâll know where that loop belongs in your app, where it doesnât, and youâll have about 40 lines of Python that do it safely.
TL;DR âĄ
- Find the fuzzy step. Look for the one place where users ask in free text and the path through your code canât be predicted. Everything else stays normal code.
- Wrap existing functions as tools. Give each one a name, a clear description and an input schema. Donât rewrite them.
- Add the loop, with a brake. The model picks a tool, your code runs it, the result goes back, and this repeats. Add a hard limit on turns.
- Gate anything that changes data. Read-only tools run freely. Refunds, deletes and emails need a human âyesâ.
- Log every step. If you canât replay what the agent did, you canât debug it or trust it.
đ§ First, the honest part: agent or workflow?
Anthropicâs engineering team splits âagentic systemsâ into two kinds. A workflow runs LLM calls and tools along code paths you define. An agent lets the model decide its own steps and which tools to use. Their advice is to start with the simplest thing that works. Often one well-written LLM call with good context is enough. Reach for an agent only when the number of steps genuinely canât be predicted.
Thatâs the âbeyond hypeâ filter. Ask this about each feature:
| Question | If yes â |
|---|---|
| Is the input already structured (a form, a button)? | Keep normal code. No LLM. |
| Is it one fixed transformation (summarise, classify, extract)? | One LLM call. |
| Is it a known sequence of steps? | A workflow: your code decides the order. |
| Does the next step depend on what the last step found? | An agent. |
Our running example is ShopDesk, a small e-commerce support app. It already has three functions: get_order(), search_faq() and refund_order(). The checkout, the order pages and the admin screens all stay exactly as they are. Only one step fits the last row of the table: the support chat box. A message like âmy order 1042 hasnât arrived and I want my money backâ needs a lookup first, and what happens next depends on the result.
đ The loop in one picture
The model only chooses. Your code runs every function, decides what needs approval and decides when the loop must stop.
đ ď¸ Step by step
1. Find the fuzzy step
Look in your app for if "refund" in message style keyword routing, or long chains of elif. Those are signs that a human question is being forced into a fixed path. In ShopDesk, thatâs the /support endpoint, and that one handler is all we convert.
2. Wrap your existing functions as tools
A tool is a description the model reads: a name, a sentence explaining what it does and when to use it, and a JSON Schema for its inputs. The function behind it doesnât change. Anthropicâs guide says to put as much care into this âagent-computer interfaceâ as you would into a UI. Vague descriptions are the most common reason an agent picks the wrong tool.
Write descriptions for a new colleague: say what the tool returns and when not to use it. For example: âLook up an order by its numeric ID. Use before answering any question about delivery or refunds.â
3. Add the loop, with a brake
With Claudeâs Messages API, you send your tools along with the conversation. When the model wants a tool, the response comes back with stop_reason == "tool_use" and a tool_use block holding the tool name, an id and the input. You run the function and send back a tool_result block carrying the same id. You repeat while stop_reason is "tool_use". When it becomes "end_turn", the model has its final answer.
The brake is a MAX_TURNS constant. Without it, a confused model can call get_order() forever while you pay for every call.
4. Gate anything that changes data
Split tools into read tools (get_order, search_faq) and write tools (refund_order). Read tools run immediately. Write tools go through an approval function first. In production thatâs a button in your admin panel; in the demo below itâs input(). If the human says no, you tell the model so, and it can explain that to the customer.
5. Log every step
Print or store each tool name, its input and its result. When a customer complains, this log is the only way to see whether the model misread the request, picked the wrong tool or got bad data from your own function.
đť The code: before and after
Before: the keyword router most apps start with.
def support_reply(message: str) -> str:
if "refund" in message.lower():
return "Please email refunds@shopdesk.example with your order ID."
if "where" in message.lower() or "arrive" in message.lower():
return "Track your order on the Orders page."
return "Sorry, I didn't understand. Try 'refund' or 'where is my order'."
It never looks anything up, so every real question ends in âemail usâ.
After: the same app, with the existing functions exposed as tools. Install the SDK with pip install anthropic and set ANTHROPIC_API_KEY.
import json
import anthropic
# --- Your existing app code, unchanged ---
ORDERS = {"1042": {"status": "lost in transit", "total": 59.0, "paid": True}}
def get_order(order_id): return ORDERS.get(order_id, {"error": "not found"})
def search_faq(query): return "Lost parcels are refunded in full after 10 days."
def refund_order(order_id): return {"refunded": True, "order_id": order_id}
# --- New: describe them as tools ---
def tool(name, desc, props):
return {"name": name, "description": desc,
"input_schema": {"type": "object", "properties": props,
"required": list(props)}}
ID = {"order_id": {"type": "string", "description": "Numeric order ID, e.g. '1042'"}}
TOOLS = [
tool("get_order", "Look up an order's status and total. Use before any delivery or refund answer.", ID),
tool("search_faq", "Search the help-centre policies.", {"query": {"type": "string"}}),
tool("refund_order", "Refund an order in full. Only after checking the order and policy.", ID),
]
FUNCS = {"get_order": get_order, "search_faq": search_faq, "refund_order": refund_order}
WRITE_TOOLS = {"refund_order"} # these need a human "yes"
MAX_TURNS = 6 # the brake
def approved(name, args):
return input(f"Approve {name}({args})? [y/N] ").strip().lower() == "y"
def support_agent(message: str) -> str:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": message}]
for _ in range(MAX_TURNS):
resp = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024,
tools=TOOLS, messages=messages)
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
messages.append({"role": "assistant", "content": resp.content})
results = []
for block in resp.content:
if block.type != "tool_use":
continue
if block.name in WRITE_TOOLS and not approved(block.name, block.input):
output = {"error": "A human declined this action."}
else:
output = FUNCS[block.name](**block.input)
print(f"[log] {block.name}({block.input}) -> {output}")
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": json.dumps(output)})
messages.append({"role": "user", "content": results})
return "Sorry, I couldn't finish that. A human agent will follow up."
print(support_agent("Order 1042 never arrived. Can I get my money back?"))
Three details matter here:
- The assistantâs whole
resp.contentgoes back intomessagesbefore the tool results. The model needs to see its owntool_userequest next to the matchingtool_result. - Every
tool_resultcarries thetool_use_idof the call it answers. - The final
returnafter the loop is the graceful exit when the brake trips.
A typical run looks up order 1042, checks the FAQ policy, asks you to approve the refund and then replies to the customer. Your three original functions didnât change at all. đ
â ď¸ Pitfalls (and when not to do this)
- Making the whole app an agent. Checkout, login and anything with a fixed sequence should stay deterministic code. Theyâre faster, cheaper and testable.
- Vague tool descriptions. âGets dataâ leads to wrong calls. Say what the tool returns, what the inputs look like and when to use it.
- No turn limit. Agents trade cost and latency for flexibility, and a loop without a brake gives you all the cost and none of the flexibility.
- Trusting tool output blindly. Your function might return
{"error": "not found"}. Make errors explicit so the model reports them instead of inventing an order status. - Letting the model act on money or data alone. Keep a human approval step on write tools until your logs show the agent is reliable.
đ Recap and next step
You donât convert an app into an agent; you convert one fuzzy step and leave the rest as code. Wrap the functions you already have as tools, run them in a loop with a brake, and put a human in front of anything that writes data.
Try next: take your own appâs messiest if/elif handler, expose two read-only functions as tools, and run the loop above with WRITE_TOOLS empty. Watch the [log] lines to see what the model chooses.
đŹ Which part of your app would you make agentic first, and which part would you never hand to a model? Tell me in the comments đ