What an AI agent needs from data
Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:00 on Wednesday, the first demo of SwiftKart's new support assistant. Freya Larsen types: "Where is my order 1012? I think I was charged twice." Two seconds later the assistant replies: "Your order was delivered yesterday and the second charge has been refunded." Order 1012 has not been delivered, and nothing was refunded. Nora looks at you: "It sounds so sure. Where did it get that from?"
You'll learn to
- Explain why a model alone makes up answers about your data
- Follow one question round the agent loop, step by step
- Name the four things an agent needs: context, tools, memory, state
- Work out why every extra step costs more than the last
Learn
It got the answer from nowhere
Nowhere. The assistant is a large language model, or LLM: a program that has read a huge amount of public text and learned to write what is likely to come next. It was trained once and then frozen. SwiftKart's orders were never in that text, and the model has no way to reach your database.
So it does the one thing it can do: it writes the answer that sounds most likely. "Delivered yesterday" is how support replies usually sound. An answer that reads well and is made up is called a hallucination.
Think of a new hire answering the phone on day one, with no login to the order system, who is too polite to say "I don't know".
What the model can reach, and what it cannot
Freya's question goes to the model, which was trained on public text and frozen; the model writes a likely-sounding answer, and a dashed red line shows it has no way to reach SwiftKart's Postgres database, where the real order and payment rows are.
Follow the arrows from the question. The only solid path ends in a guess. The dashed red line is the one you are about to build.
Give the model something to call
A cleverer prompt will not fix this. The model needs the facts at the moment it answers, and the facts live in your tables.
So you write a small function, order_status(order_id), that runs one query and returns the row. You tell the model its name and what it does. A function you offer the model like this is called a tool.
Now the model has a choice each time it is asked: write the answer, or ask for a tool first. It asks, your code runs the tool, the result goes back to the model, and it chooses again. One trip round is a step. A model going round that loop with tools is an AI agent.
Freya's question goes round the loop
Six steps of a sequence between Freya, your code, the model and Postgres: the question arrives, the model asks for the order_status tool, your code runs the query and logs it, the model asks for the payments tool, two payment rows come back, and the model answers from those facts.
The question arrives. Your code sends it to the model together with the rules and the list of tools the model may ask for.
The model asks for a tool. It cannot look anything up. It replies with a request: call
order_statuswith 1012.Your code runs the query. One fixed SELECT, with 1012 passed as a parameter. One row comes back: shipped. Your code writes the call to a log table and saves where the run stands.
Round again. Your code sends everything again, plus the result. The question also says "charged twice", so the model asks for a second tool:
payments(1012).Two rows come back. A card payment that failed, and a wallet payment that was captured, both for 142.44 USD. Two attempts, one charge.
The model answers from facts. On step 3 it has both results and needs no more tools. It writes the answer, and your code sends it to Freya.
Look for an arrow from the model to Postgres: there is none. The model decides what to try. Your code and your database decide what is possible.
The tool is one query with a blank
Open the tool and there is nothing clever inside. It is one SQL query your team wrote, with a blank where the order number goes. The model fills in the blank and nothing else.
Run it for order 1012. It counts the payments that took money (captured) apart from the ones that did not (failed).
The query behind order_status
SELECT o.order_id,
o.status,
o.updated_at AS last_update,
COUNT(p.payment_id) FILTER (WHERE p.status = 'captured') AS captured_payments,
COUNT(p.payment_id) FILTER (WHERE p.status = 'failed') AS failed_payments
FROM orders AS o
LEFT JOIN payments AS p ON p.order_id = o.order_id
WHERE o.order_id = 1012
GROUP BY o.order_id, o.status, o.updated_at;
One row: shipped, 1 captured payment, 1 failed. That is Freya's "charged twice": two attempts, one charge. Now try 1033, the order that really was charged twice, and 1047, which has no payment yet. The LEFT JOIN keeps order 1047 in the result, so the agent does not wrongly say the order does not exist.
The loop is ordinary code
The loop around the model is not magic either. Here it is in about 30 lines of Python.
fake_model stands in for the LLM: it looks at what has been gathered so far and returns either a tool to call or the answer. A real model returns the same decision as JSON.
Everything else is the part your team writes. The tools sit in a dictionary, TOOLS, so the model can only ask for a name that is in it. And the for loop stops after 5 steps whatever happens. That stop is called a step limit. Without one, a confused model can go round forever, and every step costs money.
The loop in plain Python
import duckdb
# Tools: plain functions, each running one fixed query with a parameter (?).
def order_status(order_id):
row = duckdb.execute(
"SELECT status FROM 'data/orders.csv' WHERE order_id = ?", [order_id]
).fetchone()
return row[0] if row else None
def payments(order_id):
rows = duckdb.execute(
"SELECT status, amount FROM read_json_auto('data/payments.jsonl') "
"WHERE order_id = ? ORDER BY payment_id", [order_id]
).fetchall()
return [f"{status} {amount:.2f}" for status, amount in rows]
TOOLS = {"order_status": order_status, "payments": payments}
def fake_model(question, seen):
"""Stands in for the LLM: picks the next tool, or answers."""
if "order_status" not in seen:
return ("call", "order_status", 1012)
if "charged" in question and "payments" not in seen:
return ("call", "payments", 1012)
return ("answer", f"Order 1012 is {seen['order_status']}; payments: {seen['payments']}")
question = "Where is my order 1012? I think I was charged twice."
seen = {}
for step in range(1, 6): # a hard limit: an agent must never loop forever
decision = fake_model(question, seen)
if decision[0] == "answer":
print("answer:", decision[1])
break
_, tool, arg = decision
seen[tool] = TOOLS[tool](arg)
print(f"step {step}: {tool}({arg}) -> {seen[tool]}")
Two tool calls, then the answer on step 3. The limit of 5 is never reached here: it is there for the day the model does not stop. Each tool passes the order number as a ? parameter, never pasted into the SQL text.
Four things the agent needs from you
A look-up tool fixed Freya's question. A real assistant needs more, and each need lands on tables you build.
- Something to read: the returns policy, found at question time. This is context.
- A safe way to look things up and act: "what is the status of order 1012?" These are the tools.
- Something to remember people by: Hana prefers email updates. This is memory.
- A note of where a run has got to, so it can wait for a person to approve a refund, or survive a crash. This is state.
Four needs, and the tables behind them
The agent loop needs four things: context, tools, memory and state. Each points to the Postgres tables that provide it: documents and chunks, read-only views over orders and payments, messages and memories, and checkpoints.
Read each row left to right: a need, then the tables behind it. Lessons 16.2 to 16.4 build context, Lesson 16.5 memory and state, Lesson 16.6 tools, and Lesson 16.7 runs all of it in production.
Teams build the loop with agent frameworks such as LangGraph, the OpenAI Agents SDK, the Claude Agent SDK or LlamaIndex, and more and more they connect tools through MCP, the Model Context Protocol (Lesson 16.6). The data side is familiar: Postgres with the pgvector extension, a vector database such as Pinecone, Weaviate or Qdrant, or Databricks Vector Search and Snowflake Cortex Search. The patterns in this module carry over to all of them.
Watch every table the loop touches
An AI agent answering Maya's question "Where is my order 1064?" step by step: the model picks a tool, the tool reads a read-only view, the result goes back to the model, and a message, a tool-call log row and a checkpoint are written. In the unsafe flow Maya mistypes 1012, and a free-form text-to-SQL agent with a write-capable role shows and cancels Freya's order, which the read-only view with row-level security blocks.
Press Next step and watch which table is read or written at each step. This run follows Maya Chen asking about her own order, 1064. Then flip the Unsafe switch: she mistypes 1012, which is Freya's order, and an agent allowed to write any SQL shows it and even cancels it. Lesson 16.6 builds the protection.
Sometimes the path is fixed
Not every question needs a loop. "What is the returns policy?" always takes the same two moves: search the help articles, then write the answer from what was found. Your code fixes that path, and the model is called once.
That fixed path is called RAG, short for retrieval-augmented generation: retrieve first, then generate. It becomes an agent when the model picks its own next move, such as searching again or calling order_status.
Think of a bus and a taxi. The bus takes the same route every time. The taxi driver picks the route as the traffic changes.
RAG or an agent?
| RAG (retrieval-augmented generation) | Agent |
|---|---|
| One fixed path: search, then answer | The model chooses the next step each time |
| Retrieves text chunks from a knowledge base | Calls any tool: search, SQL views, APIs, actions |
| One model call per question | Several model calls and tool calls per question |
| Enough for "what is the returns policy?" | Needed for "where is my order, and refund it if it is lost" |
| Easy to test: same question, same retrieval | Harder: needs step limits, logs and checkpoints |
Every step sends everything again
Now the part that decides the bill. The model keeps nothing between calls. On every step your code sends the whole context again: the rules (the system prompt), the tool list, the question and every tool result so far.
Models count text in tokens, which are pieces of words, and you pay per token. Work it out for the assistant (the sizes are made up for the example):
- Rules 800 tokens, tool list 1,200, question 30. Step 1 sends 2,030.
- Each step adds one tool call and its result: about 450 tokens.
- Step 2 sends 2,030 + 450 = 2,480.
- Step 3 sends 2,030 + 900 = 2,930.
What the model reads at step 3
A bar of 2,930 input tokens at step 3: 800 of system prompt, 1,200 of tool list and 30 of question, all sent every step, and 900 tokens of the first two tool calls and results, which grow each step.
Read it left to right. The three grey blocks are sent on every step. The amber block is the results so far, and it is the only part that grows.
A run of 5 steps sends 2,030 + 2,480 + 2,930 + 3,380 + 3,830 = 14,650 tokens. A run of 10 steps sends 40,550. Twice the steps, nearly three times the tokens: the cost grows with the square of the number of steps.
So two habits keep the bill small. Keep the step limit low: it is a budget, not only a safety net. And keep tool results short: the 5 rows the model needs, not 500.
Tokens one whole run sends
Bars compare the total input tokens of a whole run: 2,030 for 1 step, 7,440 for 3 steps, 14,650 for 5 steps and 40,550 for 10 steps.
Each bar is one whole run. Compare the last two: twice the steps, nearly three times the tokens.
Remember: every step resends everything before it. Few steps, small results.
What one run leaves behind
Freya has her answer. Now look at what the run left in Postgres, because these rows are how you will explain the next wrong answer.
Three tables, three jobs. messages keeps the conversation. tool_calls is the audit log: every tool the agent used, with its arguments and how long it took. checkpoints saves where the run stood after each step, as JSON in a JSONB column, so a run that crashes can carry on from its last step.
What one run leaves behind
SELECT c.step,
t.tool,
t.args,
t.ms,
c.state ->> 'next' AS next_step
FROM checkpoints AS c
LEFT JOIN tool_calls AS t
ON t.thread_id = c.thread_id AND t.step = c.step
WHERE c.thread_id = 't-1012'
ORDER BY c.step;
Read it top to bottom: step 1 called order_status, step 2 called payments, step 3 called no tool and answered. ->> reads one JSONB field as text. Lessons 16.5 and 16.6 build these tables properly.
The model is not a database. It cannot look anything up by itself, and it rarely says "I do not know" unless you give it a way to find out. Every fact in an answer (a status, an amount, a date, a policy) must come from a tool result or a help article found in that run. If you cannot point to the row it came from, treat the answer as a guess.
Numbers to remember
| What | Number | Why it matters |
|---|---|---|
| Fixed context in the example | 800 + 1,200 + 30 = 2,030 tokens | Sent again on every step |
| Added per step | About 450 tokens | One tool call and its result |
| Step n sends | 2,030 + 450 × (n − 1) | Step 3 sends 2,930 |
| A run of n steps sends | n × 2,030 + 450 × n(n − 1) / 2 | 5 steps: 14,650. 10 steps: 40,550 |
| Step limit in the example loop | 5 | A run that cannot finish in its budget stops and hands over to a person |
The token sizes are made up for the example. Real ones come from your provider's usage numbers, which Lesson 16.7 logs for every call.
What changed at SwiftKart
At 9:40 Freya asks again. This time the assistant calls two tools and answers from two rows: order 1012 shipped on 3 June, the card attempt failed and took no money, and the wallet payment of 142.44 USD is her only charge. Every word can be traced to a row.
Nora's next question is harder: "Now ask it about our returns policy." That answer is not in the orders table. It sits in a help article, in a paragraph that may not share one word with the customer's question. Lesson 16.2 teaches the assistant to find text by its meaning.
In one line
An agent is a model choosing tools in a loop. You give it context, tools, memory and state as tables, and the database, not the prompt, decides what it can do.
Interview corner
What is the difference between RAG and an agent?
RAG is a fixed pipeline: embed the question, retrieve the most relevant chunks, put them in the prompt and generate one answer. An agent is a model in a loop that chooses its next action each time, which may be a retrieval, a database query through a tool or an action such as creating a return. Agents can answer harder questions but need step limits, logging and checkpoints.
What does an AI agent need from the data platform?
Four things. Context: a knowledge base kept fresh by a pipeline and searchable by meaning and keywords. Tools: safe, narrow access to business data, usually read-only views behind parameterised functions. Memory: conversation history and long-term facts about users. State: checkpoints so a run can pause for approval, survive a crash and resume.
Where would you put the limits on what an agent can do?
In code and in the database, not in the prompt. Code keeps a fixed list of tools, validates every argument and caps the number of steps. The database user the tools connect as can only read the views it needs, row-level security limits rows to the signed-in customer, and timeouts stop runaway queries. A prompt can be talked out of its rules; a missing GRANT cannot.
What happens to the cost of a run as the number of steps grows, and what do you do about it?
The model is stateless, so every step resends the system prompt, tool definitions, conversation and all earlier tool results. With a fixed context of about 2,000 tokens and 450 tokens added per step, 5 steps send about 14,650 input tokens and 10 steps about 40,550: the growing part is quadratic. I would cap steps and retries per tool, keep tool results small (a few rows, only the needed columns), trim tool definitions to the tools this route needs, and log tokens per call so a looping run shows up in a cost report the same day.