Building a Free AI Agent Inside Google Workspace
A tool-using chat agent that runs entirely as an Apps Script web app: no server, no hosting bill, locked to my own account.

On this page
I like building things on a zero-cost stack as a discipline, not just a budget. Most of my automation already lives in Google Sheets and Apps Script, so the obvious question was whether the agent could live there too: a chat interface that can call tools, with no server to host and no platform to subscribe to.
It can. I called the project Cheap LLM chatbot, and this is how it works.

The finished agent. The header reads: tools run automatically; changes ask first.
What it does#
Ask it something and it decides whether it needs a tool. In the screenshot I asked for 18% compound growth on 2.5 million over 6 years. It didn’t guess the arithmetic. It called a calculator tool with 2500000 * (1 + 0.18)^6 and reported the result, 6,748,885.38. (I re-checked that figure independently: it is correct.)
The input box also says “Ask anything, or paste a Google Sheet link…”, so the agent can read a sheet you point it at.
The header carries the rule I care most about: tools run automatically; changes ask first. Read-only tools execute straight away. Anything that changes data stops and waits for my approval.
The architecture#
flowchart LR B[Chat page - index.html] -->|google.script.run.agentRun| S[Code.gs on Apps Script] S -->|generateContent| M[LLM API] M -->|functionCall| S S --> C[calculator] S --> SH[SpreadsheetApp] S -->|pending change| B
It is one Apps Script project with three files:
Code.gs: the agent loop and the tools.index.html: the chat page, served bydoGetthroughHtmlService.appsscript.json: the manifest, which is where the access rules live.
The manifest is the security model#

appsscript.json: V8 runtime, three OAuth scopes, web app locked to me.
Three things in that file do most of the work:
"access": "MYSELF": only my account can open the web app."executeAs": "USER_DEPLOYING": the script runs as me, so it can reach my sheets without building a separate OAuth app.- A short scope list:
script.external_request(to call the model),spreadsheets, anduserinfo.email. The agent can’t touch Gmail or Drive because it was never granted them.
The loop#
An agent is a loop: send the model the conversation plus a list of tools, run any tool it asks for, send the result back, and stop when it answers in plain text.
The code below is a simplified version of that loop, written to show the pattern. It is not a copy of my deployed Code.gs, so expect your own to differ in the details.
const MODEL = 'gemini-flash-latest'; // use whichever free-tier model AI Studio lists
const MAX_STEPS = 6;
const NEEDS_CONFIRM = { write_cell: true };
const TOOLS = [{ functionDeclarations: [
{ name: 'calculator', description: 'Evaluate an arithmetic expression. Use ^ for powers.',
parameters: { type: 'object', properties: { expression: { type: 'string' } }, required: ['expression'] } },
{ name: 'read_sheet', description: 'Read the first rows of a Google Sheet by URL.',
parameters: { type: 'object', properties: { url: { type: 'string' } }, required: ['url'] } },
{ name: 'write_cell', description: 'Write a value to one cell. Requires user approval.',
parameters: { type: 'object', properties: { url: { type: 'string' }, a1: { type: 'string' }, value: { type: 'string' } },
required: ['url', 'a1', 'value'] } }
] }];
const HANDLERS = {
calculator: ({ expression }) => {
if (!/^[0-9+\-*/().^\s]+$/.test(expression)) throw new Error('unsupported expression');
return Function('"use strict"; return (' + expression.replace(/\^/g, '**') + ')')();
},
read_sheet: ({ url }) =>
SpreadsheetApp.openByUrl(url).getSheets()[0].getDataRange().getValues().slice(0, 50),
write_cell: ({ url, a1, value }) => {
SpreadsheetApp.openByUrl(url).getSheets()[0].getRange(a1).setValue(value);
return { ok: true };
}
};
function doGet() {
return HtmlService.createHtmlOutputFromFile('index').setTitle('Agent');
}
// Called from the page: google.script.run.agentRun(history, approvedIds)
function agentRun(history, approved) {
approved = approved || [];
const events = [];
for (let step = 0; step < MAX_STEPS; step++) {
const reply = callGemini_(history);
history.push(reply);
const calls = (reply.parts || []).filter(p => p.functionCall);
if (!calls.length) return { history, events, text: reply.parts.map(p => p.text || '').join(''), pending: null };
const parts = [];
for (const p of calls) {
const { name, args, id } = p.functionCall;
const key = name + JSON.stringify(args);
if (NEEDS_CONFIRM[name] && approved.indexOf(key) < 0) {
history.pop(); // drop the call; re-ask after approval
return { history, events, text: '', pending: { name, args, key } };
}
let out;
try { out = { result: HANDLERS[name](args || {}) }; } catch (e) { out = { error: String(e) }; }
events.push({ name, args, ok: !out.error });
const fr = { name, response: out }; if (id) fr.id = id;
parts.push({ functionResponse: fr });
}
history.push({ role: 'user', parts });
}
return { history, events, text: 'Stopped: step limit reached.', pending: null };
}
function callGemini_(contents) {
const key = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
const res = UrlFetchApp.fetch(
'https://generativelanguage.googleapis.com/v1beta/models/' + MODEL + ':generateContent',
{ method: 'post', contentType: 'application/json', headers: { 'x-goog-api-key': key },
muteHttpExceptions: true,
payload: JSON.stringify({ contents, tools: TOOLS }) });
if (res.getResponseCode() !== 200) throw new Error(res.getResponseCode() + ' ' + res.getContentText());
return JSON.parse(res.getContentText()).candidates[0].content;
}Details worth copying:
- Confirmation lives in code, not in the prompt.
write_cellis inNEEDS_CONFIRM. The loop stops and returns apendingobject, and the page shows an approve button. Telling the model to “ask first” isn’t enough, because the model can’t enforce it. - Resend the model’s turn unchanged. Newer Gemini models attach thought signatures to function calls, and stripping them breaks function calling.
- Errors go back as data. A failed tool returns
{ error }, so the model can recover instead of the run crashing. MAX_STEPSis a seatbelt against a confused model looping until the time limit.- The calculator doesn’t use a bare
eval. It only accepts digits and arithmetic characters. - The key lives in Script Properties, not in the code.
I ran this loop against stubbed Apps Script services. It confirmed that a calculator call executes and a write call returns a pending approval. That tests the plumbing, not the model’s judgement.
It is fast#

Apps Script execution log: doGet loads the page in about half a second; one agentRun took about 3 seconds.
The execution log shows the two functions doing the work. doGet serves the page in about 0.5 seconds, and agentRun completed that calculator question in about 3 seconds, including the model call. Both ran as a Web App on Version 2.
Why it costs nothing#
| Piece | Cost |
|---|---|
| Apps Script runtime and hosting | Free with a Google account |
| Auth | Free, the script runs as me |
| Secrets | Free, Script Properties |
| Model | Free tier (limits vary by model, check AI Studio) |
The limits to know#
These come from Google’s quota docs as I read them, and Google says they can change without notice.
| Limit | Consumer account | Workspace account |
|---|---|---|
| Runtime per execution | 6 min | 6 min |
| URL Fetch calls per day | 20,000 | 100,000 |
Each loop step is one UrlFetch, so a six-step run costs six calls. The practical ceiling is the 6-minute execution limit, which a chat agent rarely gets near.
Design choices worth copying#
- Narrow tools. No
deleteand nosend. If the model is wrong, the damage is limited. - Read freely, write with permission.
- Least-privilege scopes, declared in the manifest.
- One audience.
MYSELFaccess means there is no public surface to defend.
Takeaway#
You don’t need infrastructure to get an agent that does maths, reads your sheets and asks before it changes anything. A loop, a few scoped functions, one REST call and a locked-down manifest is enough, and it costs nothing until you outgrow it.