Learning objectives
After reading this article you will be able to:
- Understand the loop of model, tools and state that defines an agent
- Tell agents, chatbots and fixed workflows apart, and know when each is enough
- Learn the risks of an agent and the defenses that limit the damage
"Agent" has become the buzzword of AI, and every product uses it differently. For developers, the useful definition is narrower and more concrete: an agent is a program where the language model decides what to do next, and your code does it.
That difference looks small, but it changes everything downstream: how much a task costs, how long it takes, what can go wrong and how you protect your data. If you are not sure how a model generates text yet, start with what an LLM is.
What is an AI agent?#
An AI agent is a system where a language model chooses, in a loop, which tools to use and when to stop, until it reaches a goal. Anthropic, in the guide where it separates the two ideas, defines workflows as systems where models and tools follow paths set in code, and agents as systems where the model directs its own process and tool usage.
Every agent has three ingredients:
- Model: the LLM that reads the goal and the history and decides the next step.
- Tools: functions your code exposes to the model, each with a name, a description and a JSON schema for its arguments. Looking up an order, reading a file, running a search.
- State: the history of what has happened so far, with messages, calls and results. It is what lets the model use the result of step 1 to decide step 2.
And a fourth one that people tend to forget: stopping conditions. Anthropic's guide recommends limits such as a maximum number of iterations to stay in control.
How does an agent loop work?#
The cycle has four steps:
- You send the model the goal and the list of tools.
- The model returns either a final answer or a request to call one or more tools, with arguments.
- Your code runs the requested tools and appends each result to the history.
- The history goes back to the model, and the cycle repeats until a final answer or the step limit.
The most important point: the model never runs the tools you define. It only asks. Your code decides whether the call runs, and with which permissions.
The example below is a complete agent in Python with the OpenAI SDK (pip install openai), in the chat completions format. It runs on any OpenAI-compatible API that accepts tools in the chat completions format: the model comes from the OPENAI_MODEL variable.
import json
import os
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY and, if set, OPENAI_BASE_URL
MODEL = os.environ["OPENAI_MODEL"]
MAX_STEPS = 8
ORDERS = {
"1001": {"status": "shipped", "zip_code": "94105"},
"1002": {"status": "awaiting payment", "zip_code": "10001"},
}
def order_status(number):
return ORDERS.get(number, {"error": "order not found"})
def delivery_estimate(zip_code):
return {"zip_code": zip_code, "business_days": 2 if zip_code.startswith("9") else 5}
FUNCTIONS = {"order_status": order_status, "delivery_estimate": delivery_estimate}
def tool(name, description, field):
return {
"type": "function",
"function": {
"name": name,
"description": description,
"parameters": {
"type": "object",
"properties": {field: {"type": "string"}},
"required": [field],
},
},
}
TOOLS = [
tool("order_status", "Status and shipping ZIP code of an order.", "number"),
tool("delivery_estimate", "Delivery estimate in business days for a ZIP code.", "zip_code"),
]
def agent(goal):
messages = [
{"role": "system", "content": "You help a store's customers. Use the tools."},
{"role": "user", "content": goal},
]
for step in range(1, MAX_STEPS + 1):
response = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
msg = response.choices[0].message
if not msg.tool_calls:
return msg.content # final answer: the loop ends
messages.append({
"role": "assistant",
"content": msg.content,
"tool_calls": [
{"id": c.id, "type": "function",
"function": {"name": c.function.name, "arguments": c.function.arguments}}
for c in msg.tool_calls
],
})
for call in msg.tool_calls:
function = FUNCTIONS.get(call.function.name)
try:
args = json.loads(call.function.arguments)
result = function(**args) if function else {"error": "unknown tool"}
except (json.JSONDecodeError, TypeError) as error:
result = {"error": f"invalid arguments: {error}"}
print(f"step {step}: {call.function.name} {call.function.arguments}")
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
return f"Stopped after {MAX_STEPS} steps without finishing."
print(agent("When will my order 1001 arrive?"))Run it with OPENAI_API_KEY and OPENAI_MODEL set (the model ID comes from the provider's models page). You will usually see two steps: the model looks up the order, finds the ZIP code in the result and only then asks for the estimate for that ZIP. Nobody coded that sequence; the model worked it out. The arguments arrive as JSON text the model wrote, so the code validates them before calling the function, and returns the error to the model instead of crashing.
What is the difference between an agent, a chatbot and a workflow?#
| Chatbot | Fixed workflow | Agent | |
|---|---|---|---|
| Who decides the next step | There is no next step | Your code | The model |
| Tools | None, or one fixed lookup | Calls in a set order | Picked by the model at each step |
| Number of steps | One | Fixed | Variable, up to a limit |
| Predictability | High | High | Lower |
| Cost and latency | One call | A few known calls | Unpredictable |
| Example | Answering questions from an FAQ | Summarizing and tagging each new ticket | Finding out why a deployment failed |
The line is blurry. A chatbot that calls a tool before replying already has a piece of an agent, and a workflow can include a step where the model picks between two branches.
When is an agent worth it?#
When you cannot predict the steps. Diagnosing a failure is the classic case: the agent reads the logs, opens the file the error points to, tests a hypothesis and changes course based on what it finds. See an example in how to use an AI agent to fix deployment errors.
When the steps are known, a workflow is cheaper, faster and easier to test. And when the task is answering a question, a single well-built call is often enough. Anthropic's guide recommends starting with the simplest solution and adding complexity only when needed, noting that agentic systems often trade latency and cost for better task performance.
To write the loop, you can use the SDK directly, as in the example, or a framework: the comparison is in LangChain, LlamaIndex, AI SDK or a direct SDK. If the tools need to serve several AI apps, the MCP protocol standardizes where they come from.
What are the risks of an agent?#
An agent acts, and actions have consequences. OWASP calls the core problem excessive agency: damaging actions triggered by unexpected, ambiguous or manipulated model output. It lists three root causes: excessive functionality, excessive permissions and excessive autonomy, when high-impact actions run without independent verification or approval.
The most common risks in practice:
- Irreversible actions. Deleting a record, charging a card, sending an email. A model mistake at step 3 cannot be undone at step 4.
- Compounding errors. Anthropic's guide points out that autonomy brings higher costs and errors that add up at each step.
- Prompt injection. A page, email or document a tool reads can carry hidden instructions the model follows. Details in what prompt injection is.
- Unbounded cost. An agent stuck in a loop burns tokens until someone notices.
The defenses that pay off most come from OWASP's recommendations and Anthropic's guide:
- Minimal, specific tools. An
order_statustool instead of open access to the database; never a generic shell unless you really need one. - Least privilege. Read-only credentials whenever possible, kept in environment variables, never in the prompt.
- Human approval before high-impact actions.
- Authorization in the downstream system. The API the tool calls checks permissions on its own, without trusting the model.
- Limits on steps, time and tokens, plus a log of every call.
- Testing in a sandbox before giving access to real data.
To run an agent in production, with a queue and worker for long tasks, see the best way to host an AI agent.
How to do this on Square Cloud#
Cubic is the AI agent in the Square Cloud dashboard, included in every plan, with a daily and weekly token budget per plan. Instead of the tools in the example, it works with your applications: it writes code, reads logs to diagnose failures and runs safe actions, at your request. Every file it edits or deletes can be undone from the chat while the conversation lasts.
Every plan has Cubic Flash. Pro and Enterprise add Cubic Pro and routines: scheduled tasks that act within what you checked beforehand, without asking for approval at run time.
To build your own agent, from Standard the AI Gateway serves the cubic model through an OpenAI-compatible API, with function calling in the OpenAI format (up to 32 tools). To point this article's loop at it, set OPENAI_BASE_URL=https://api.squarecloud.app/v2/ai, an account API key with the ai:chat scope in OPENAI_API_KEY and OPENAI_MODEL=cubic. The gateway keeps no state, and the loop already resends the history on every call. If you prefer another agent, such as Claude or Cursor, the MCP server connects that client to your account, and critical actions ask for confirmation in the AI client. See everything Cubic does on Cubic, the AI agent.
AI
Host AI apps in always-on containers
FAQs
What is the difference between an AI agent and a chatbot?
A chatbot takes a message and returns a reply. An agent takes a goal and works in a loop: it calls tools, reads the results and decides the next step until it is done. A chatbot with tools is already starting to behave like an agent.
What is the difference between an agent and a workflow?
In a workflow, your code sets the sequence of steps and the model only fills in each one. In an agent, the model decides which steps to take and in what order. Workflows are more predictable; agents handle tasks you cannot plan in advance.
Do I need a framework to build an AI agent?
No. The loop fits in a few dozen lines with the model provider's SDK. Frameworks help with memory, tracing and orchestrating several agents, but they add a layer to learn and debug.
Can an AI agent delete my data?
Yes, if it has a tool and a permission that allow it. Give it only the tools it needs, prefer read-only access and require human approval for irreversible actions such as deleting, paying or sending email.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- RAG vs fine-tuning: which to useRAG puts your data in the prompt at question time; fine-tuning changes the model's weights with examples. Compare cost, updates, latency and when to use each.
- pgvector vs a dedicated vector database: which to usepgvector stores vectors in PostgreSQL, next to your data; a dedicated vector database focuses on scale and filtering. Compare indexes, operations and migration.