Most "AI agent" frameworks hide what is happening behind layers of abstraction. I wanted the opposite: a personal assistant where I can open every file, see every prompt, and explain every decision it makes.
The result is Personal AI: roughly 1,700 lines of Python that give a language model three things:
- a job (an "agent": a short JSON file with instructions),
- tools (22 plain Python functions called "skills"),
- a memory (markdown files that grow as the assistant is used).
The one rule that shapes everything: the model proposes, Python disposes. The model never touches the network, the disk or your inbox. It can only emit text. Python reads that text, decides whether it is allowed, and only then does something.
The assistant also starts out knowing almost nothing, on purpose. Its system prompt says it must not rely on general world knowledge; it may trust only (1) its memory, (2) what its skills return, and (3) what you tell it. If it cannot find something out, it says "I don't know yet". That makes its behaviour auditable: every claim traces back to a file, a web page, a database row or something you said.
Full code: github.com/rash-aad/personal_ai.
The Big Picture: Six Layers
- Interface —
pai.py, installed as the console commandpai. Commands includerun,chat,index,search,approvals,approve,reject,agents,show,revert,create-agent,delete-agent,teach,memory,rules,log. - Orchestration —
runner.pyruns the think → act → observe loop.agents.pyloads, validates and backs up agents. - Model access —
llm.py. The only place the model is called. It runs the Claude CLI in print mode with every built-in tool and every user setting disabled. - Capabilities —
skills.py. 22 plain functions in one dictionary. - State —
memory.py(markdown),index.py(SQLite search),approvals.py(a JSONL queue). All plain files. - Integrations —
mcp.pyplusconnectors/. Email and the business database run as separate processes that speak the Model Context Protocol (JSON-RPC over stdin/stdout).
External systems it can reach: the Claude CLI (the model), Ollama (optional, local embeddings), DuckDuckGo and web pages, Gmail (IMAP/SMTP) and a local SQLite file.
What Is An "Agent" Here?
In this project an agent is not a class or a process. It is a JSON file in agents/. For example, the reader agent is essentially:
Four fields:
| Field | What it does |
|---|---|
name | What you type: pai run reader "..." |
description | What the dispatcher reads to decide who fits a task |
skills | The allowlist: the only tools this agent may call |
instructions | The agent's personality and procedure (its system prompt); an optional max_steps overrides the default of 8 |
Two agents with the same code behave differently because their JSON is different. The eight agents that ship with the project:
| Agent | Skills | Job |
|---|---|---|
browser | web_search, fetch_url | Finds facts on the public web |
reader | read_txt, read_pdf | Reads and summarises local files |
writer | write_file, read_txt | Drafts text and saves it to files |
business | search_docs, db_schema, db_query, email_search, email_read, email_send, write_file | The "company assistant": answers from indexed documents, queries the database, handles mail (10 steps allowed) |
planner | list_agents, delegate | Never works itself; splits a task and hands the pieces to other agents (12 steps allowed) |
trainer | 9 self-management skills | Edits rules, agents and memory |
chat | none | Small talk |
coder | none | Writes code and reasons through its output |
Because an agent is just a file, creating or editing one is just writing a file. And because a skill is only available if it is in the list, giving an agent less power is as simple as deleting a word.
One Run, Step By Step (The Agent Loop)
You type:
pai run business "What does the Q3 contract say about refunds?"
Here is exactly what happens, in order.
- Load the agent.
agents.get("business")readsagents/business.jsonand fills in defaults for missing keys. - Build the system prompt.
runner.system_prompt()assembles, from scratch on every run:- the base rules (you know nothing; trust only memory, skill results and the user; reply with exactly one JSON object),
- the agent's instructions,
- standing rules from
memory/rules.md(apply to every agent), - the brand guide from
memory/brand.md, - memory: facts recalled for this task,
- the list of skills this agent may call, each with its description and argument names.
- Ask the model.
llm.ask()sends the prompt plus the transcript so far. The first transcript is justTASK: .... - Parse the reply. The model must answer with one JSON object, either
{"thought": "...", "skill": "search_docs", "args": {...}}to use a skill, or{"thought": "...", "answer": "..."}to finish._parse()strips code fences and grabs the first{...}block. If the text is not valid JSON, the raw text simply becomes the final answer. - Guard checks (all of them are listed further down). A skill request is only a proposal. Python checks that the skill is on this agent's list, that this exact call was not already made in this run, and whether the skill needs human approval.
- Run the skill.
skills.run()calls the Python function. Any exception is caught and turned into a string beginning witherror:. The model never sees a stack trace crash the program; it sees text it can react to. - Observe. The result (clipped to 12,000 characters) is appended to the transcript as
YOU CALLED: {...}andRESULT: ..., and the loop goes back to step 3 with the longer transcript. - Stop. The loop ends when the model answers, or when the step budget (8 by default) is used up. In that case the runner returns "I ran out of steps before finishing" plus what was gathered.
- Learn. If learning is on, a second model call decides what is worth remembering (see the memory section).
- Log and return. One JSON line is appended to
logs/runs.jsonl(time, agent, task, each skill used, answer, what was learned) and the answer is printed.
Notice how much the model is not trusted with: it does not choose the tools it has, it cannot repeat itself forever, it cannot take actions outside its allowlist, and it cannot run flagged skills at all.
How The Model Is Called (llm.py)
The whole model integration is one function. It shells out to:
--tools ""switches off Claude Code's built-in tools (file editing, shell, web). The model can only return text.--setting-sources ""ignoresCLAUDE.mdfiles and user settings, so the model sees only the prompt this project built.--output-format jsonreturns an envelope the code can parse.
An optional PAI_MODEL environment variable adds --model. A failure (missing CLI, non-zero exit, timeout, error flag in the reply) raises LLMError; ask() retries twice with 2 s then 4 s backoff and a 300 s timeout per call.
Why wrap a CLI instead of an SDK? It keeps the project dependency-free (the only Python dependency is pypdf), and every model call in the whole system funnels through about 50 lines.
Web Search: The Exact Path
Agent: browser (skills web_search and fetch_url). Task: pai run browser "What does example.com sell?"
- The model replies
{"skill": "web_search", "args": {"query": ...}}. It has no browser. All it did was ask. - The runner checks the allowlist, the repeat set and the approval flag. All pass.
skills.web_search()buildshttps://html.duckduckgo.com/html/?q=<query>.skills._get()sends the request withurllib: browser-likeUser-AgentandAccept-Languageheaders, gzip/deflate accepted and decoded, 30-second timeout.- DuckDuckGo returns a plain HTML page. There is no JavaScript engine, no cookies and no login session in this project, so JavaScript-heavy sites will not render.
- A regular expression extracts up to 8 results, each as title, link and snippet. DuckDuckGo wraps links in a redirect; the real target is unwrapped from the
uddgparameter. The list is appended to the transcript asRESULT. - The model is called again and reads the results.
- It chooses a link and asks for
fetch_url. The same guards run. _get()downloads that single page._strip_html()removes script/style/noscript blocks and all tags, decodes HTML entities and collapses whitespace. The remaining plain text (clipped to 12,000 characters) becomes theRESULT.
The model then answers from that text only. Because the prompt forbids using world knowledge, an answer like "example.com is a placeholder domain" is traceable to the page that was fetched.
Failure behaviour: a network error, bad URL or timeout is caught by skills.run() and returned as error: .... The model can try another link or say that it could not find out.
Files: Reading, PDFs And Writing
There is no upload feature, and that is deliberate. Agents work on paths on your own disk; nothing leaves the machine except text that ends up in a prompt to the model.
Path resolution (skills._path):
- an absolute path is used as given,
- a relative path is looked up in the project root first; if it is not there, in
workspace/, - a
~is expanded to your home directory.
Skills:
read_txtreads any text-like file (txt, md, code, csv...) witherrors="replace"so odd bytes never crash it.read_pdfuses pypdf'sPdfReaderandextract_text()page by page, prefixing each page with--- page N ---. It extracts the text layer only: a scanned PDF with no text layer returns empty pages, because there is no OCR.list_fileslists a directory, folders first, hidden entries skipped, so the model can discover the right filename. It is in the registry, but none of the eight shipped agents has it on their list yet, so you would add it to an agent first.write_filewrites text to a path. Relative paths go toworkspace/, missing parent folders are created. It returnswrote N chars to <path>.
Every read result is clipped to 12,000 characters (...[truncated, N chars total]). That is fine for a note or a short PDF, but too small for a 200-page contract. For big documents the right tool is document search (next two sections), which finds the relevant passages instead of dumping the whole file into the prompt.
Typical use:
Document Search, Part 1: Building The Index
What index.build() does:
- Walk. Registered folders are scanned recursively. Hidden folders,
.git,venv,node_modulesand similar are skipped; only known file types are kept (pdf, docx, pptx, xlsx, txt, md, markdown, csv, json, py, html, rst). - Skip unchanged. If a file's modification time equals the one stored in the database, it is not re-processed. Re-running is cheap.
- Extract text with standard-library code (except PDF, which uses
pypdf):- PDF:
pypdf, page by page - DOCX: a zip file; paragraphs parsed out of
word/document.xml - PPTX: a zip file; text of each slide, labelled
--- slide N --- - XLSX: a zip file; shared strings and cells, one tab-separated line per row
- text: read directly
- PDF:
- Chunk. The text is cut into pieces of 1,200 characters with 200 characters of overlap, preferring to cut at a newline or sentence end so a chunk is not cut mid-thought. Overlap means an answer that straddles a boundary still appears whole in one chunk.
- Embed. Each chunk is sent to a local Ollama server (model
nomic-embed-text) assearch_document: <chunk>, in batches of 32, and the vector is normalised to length 1. If Ollama is not running, the chunk is stored without a vector and search degrades gracefully to keyword-only. - Store. SQLite file
index/index.dbwith two tables:docs(path, mtime, title)andchunks(id, path, ord, text, vec BLOB), the vector stored as float32. - Clean up. Files that no longer exist on disk are removed from the index on the next build.
Document Search, Part 2: Finding The Answer
Agent: business, skill: search_docs.
Why two search methods? Keyword search (BM25) is precise when the query uses the same words as the document, but misses synonyms. Vector search catches paraphrases ("money back" vs "refund") but can be fuzzy about exact terms, numbers and names. Using both and combining them is called hybrid search.
- The model writes a plain-words search phrase and optionally how many passages (
k, default 5). All chunk rows are loaded from SQLite into memory. (Fine at personal scale; a very large collection would want a real vector index.) - Lexical leg. BM25 scores every chunk using term frequency, inverse document frequency and length normalisation (k1 = 1.5, b = 0.75). Only chunks sharing at least one word score; the top 40 are kept.
- Semantic leg. The query is embedded (
search_query: ...) and compared with every stored vector by dot product (cosine similarity, since all vectors have length 1). Top 40 kept. - If Ollama cannot be reached, this leg is skipped and BM25 alone carries the search.
- Fusion. Reciprocal-rank fusion. A chunk earns
1/(60 + rank)from each list it appears in; scores are summed. Chunks ranked well by both methods rise to the top. The best 20 become candidates. - Rerank. The 20 candidates (first 700 characters each) are shown to the model as numbered passages with the query, and it returns the numbers that actually help, best first, as a JSON array like
[3, 1, 7]. If this call fails, the fused top-k is used instead. - Result. The kept passages are returned as
[1] title (chunk n) - /path/to/filefollowed by the passage text, so the answering agent can cite the source file. - Log.
logs/search.jsonlrecords the query, whether the vector leg was used, the candidate ids and what was kept, so retrieval quality can be audited later.
The pai search command runs this same pipeline directly from the terminal (with an option to skip the rerank), which is handy for debugging retrieval without involving an agent.
Email And The Approval Gate
Reading mail is safe: the mailbox is opened read-only, headers are fetched with BODY.PEEK so messages are not marked as read, and an email body is capped at 6,000 characters. Search uses Gmail's own query syntax (X-GM-RAW), e.g. from:sam newer_than:7d.
Sending mail is not safe, so it never happens inside the agent loop:
- The model asks for
email_send(to, subject, body). email_sendis flaggedapproval=Truein the skill registry. The runner does not call it. Insteadapprovals.enqueue()appends a "pending" item toapprovals/queue.jsonland returns this text to the model: "queued for approval as #7. It has NOT happened yet: the user must runpai approve 7. Do not retry; tell the user it is waiting for their approval."- The model tells you honestly that the email is waiting.
- Later you run
pai approvalsto see what is pending, then eitherpai approve 7orpai reject 7. approve()callsskills.run(..., gated=False), the only way to run a flagged skill. The MCP client talks to the mailbox server, which logs in with your Gmail App Password and sends over SMTP (SSL, port 465). The queue item becomes "done" (or "failed") and the result is stored. Approving twice is refused.
An honest caveat: the gate lives in the Python runtime, not in the mailbox server. The server's own send tool has no gate, and the same server could be plugged into any other MCP client. The gate protects this app's agents from sending mail on their own; it does not protect the mailbox from every possible client.
The Business Database
Agent: business. Skills: db_schema, db_query.
-
The agent calls
db_schemaonce. The result lists every table with its row count and columns. -
It writes one
SELECTand callsdb_query. -
The call goes through the MCP client to
db_server.py, a separate process. The server enforces:- the statement must start with
SELECTorWITH, - an inner semicolon is rejected (a trailing one is stripped),
LIMIT 50is appended if the query has noLIMITof its own,- the SQLite file is opened with the URI option
mode=ro.
The last point is the real safety net: even if a check were bypassed, a read-only connection cannot modify data.
- the statement must start with
-
Rows come back as tab-separated text with a row count. A bad query returns its error text, so the model can fix the SQL and retry.
The database path comes from PAI_DB_PATH (mcp.json sets it to data/business.db), and scripts/import_leads.py seeds it from a leads workbook.
One detail worth knowing: the LIMIT 50 is a default, not a hard cap. A query that ends in its own LIMIT is passed through as written.
MCP: How Connectors Talk To Python
The Model Context Protocol is a standard way for an AI app to talk to a tool server. This project implements the small slice it needs, using only the standard library, in mcp.py:
- Client.
mcp.call(server, tool, args)looks the server up inmcp.json, starts it as a subprocess on first use, sends theinitializerequest and theinitializednotification (protocol version 2025-03-26), thentools/callwith the tool name and arguments. One JSON object per line over stdin/stdout. The process is kept alive between calls. - Server.
mcp.serve(name, tools)turns a dictionary of Python functions into an MCP server: it answersinitialize,tools/list,tools/callandping. A function that raises returns an error result instead of crashing the server. - Config.
mcp.jsonlists each server's command and environment. Two ship with the project:emailanddb.
Why separate processes? Isolation (a crash in the mailbox server cannot take the app down), one place that uses the credentials (only the mailbox server reads PAI_EMAIL_USER and PAI_EMAIL_PASS), and reuse: the same servers can be registered with any other MCP client. This is separation of code, not of secrets: the variables are set in the parent environment, which every subprocess inherits.
When the server is missing or dies, the client raises MCPError and the skill turns it into error: ... for the model.
Every Guardrail In One Place
- The model has no tools. The CLI is started with
--tools ""and--setting-sources "". It can only emit text. - Non-JSON replies cannot trigger actions; they become the answer.
- Per-agent allowlist. A skill not in the agent's JSON is refused before running (
skill '...' is not available to this agent). - No repeated calls. The exact same skill+args pair in one run gets an error telling the model to use the earlier result.
- Approval queue. Flagged skills are queued;
skills.run()also refuses them by default even if reached by another path. - Skill exceptions never crash a run. They become
error: ...text. - Read-only database at the SQLite level.
- Step budget (8 by default, set per agent).
- Output clipping: 12,000 characters for file, page, document, email and database results (
web_searchis bounded at 8 results instead); 2,000 per call in the stored tool log. - Bounded delegation: one level deep, only existing agents, never to another planner.
- Reversible agent edits: every
agents.update()writes a timestamped backup first.
What it does not protect against, so you can judge it fairly: a model can still say something wrong using correct tool results; web pages are untrusted text that is fed back into the prompt (prompt injection is a real risk for any system that reads the web); rule overwrites and deleted facts are not backed up; and the approval gate does not secure the mailbox against other clients.
Memory: How It "Learns"
There is no training and no fine-tuning. "Learning" means writing useful sentences to text files that are put into future prompts.
Three files:
memory/facts.md: for example- [2026-10-26, browser] example.com is a placeholder domain reserved for documentationmemory/rules.md: standing instructions applied to every agent (- Answer in short bullet points)memory/brand.md: a brand guide you write by hand; the AI never edits it
After every run (memory.learn): a second model call receives existing memory, existing rules, the task, what the skills returned and the final answer, and is asked for JSON: up to 6 new facts and up to 3 new rules. It is told to keep concrete facts, files and URLs the user works with, preferences and corrections, and to ignore opinions, generic knowledge and temporary failures. New items are compared against what exists (ignoring dates and case) and only genuinely new ones are appended.
If the run itself edited rules or agent instructions (the trainer does), rule extraction is skipped for that run so the same wish is not written twice.
At the start of every run (memory.recall): with 60 facts or fewer, all of them go into the prompt. Above that, facts are scored by word overlap with the task, the top 50 are kept, the 10 newest are added, and the prompt says "showing N of M facts".
So the second time you ask about something, the assistant starts with what it found the first time. The memory is plain text you can read, correct or delete.
Chat Mode, Routing And Delegation
In chat you do not name an agent. You can type @agent_name ... to pick one directly. Otherwise:
- Routing.
runner.route()gives the model a list of every agent with its description and skills (plus the skill catalogue) and asks for one name. The reply is trimmed and lowercased. A known name runs that agent; an unknown name falls back to the first agent; the special answerNEWmeans "no agent fits". - NEW.
create_agent_for()asks the trainer to build a suitable agent. If the trainer does not actually create one (it may just inspect the existing agents), chat reports that it could not, and suggests@trainerorpai create-agent. - History. Chat remembers the last 6 exchanges and prepends them to the next run as
EARLIER - user: ... / EARLIER - you answered: .... - Delegation. For multi-step work the planner agent calls
delegate(agent, task).delegate()checks three things: it is not already inside a delegation (one level only), the target agent exists, and the target is not itself a planner. Then it runs a full nestedrunner.run()for the worker with its own prompt, its own loop and its own memory update; the worker's answer comes back to the planner as an ordinaryRESULT. Example: "compare last quarter's revenue in our DB with the pricing page" becomes one delegation tobusiness(SQL) and one tobrowser(fetch the page), then the planner writes the comparison.
Because the worker will not see the conversation, the planner is instructed to make every sub-task complete and self-contained.
The Trainer: An Assistant That Edits Itself
The trainer is an ordinary agent whose skills happen to be management functions: list_agents, get_agent, set_agent_instructions, create_agent, get_rules, set_rules, read_memory, remember, forget.
Example:
get_rulesreads the current rules (set_rulesreplaces the whole file, so the model needs the old text to avoid dropping rules).set_ruleswrites the new rule file. From the next run, every agent gets it in its prompt.set_agent_instructionsedits the browser agent.agents.update()first saves the previous definition toagents/history/browser-YYYYMMDD-HHMMSS.json, then saves the new instructions and stampsupdated: <time> by trainer.- The run ends;
memory.learn()runs with rule extraction off.
Undo: pai revert browser restores the newest backup and removes it from history. Be aware of the asymmetry: agent edits are backed up, but set_rules overwrites rules.md and forget deletes facts for good, so keep a copy of anything you care about.
New agents can also be made by hand (pai create-agent) or via the trainer when chat finds no fit; when instructions are left blank, a model call writes 3 to 6 sentences of instructions from the name, purpose and skills.
Failure Behaviour At A Glance
| What goes wrong | What happens |
|---|---|
| Model replies with non-JSON | Raw text becomes the answer |
claude CLI missing / error | LLMError after 2 retries |
| Skill raises or gets bad args | error: ... text to the model |
| MCP server missing or dead | error: ... text; restarted on next use when it exited |
| Ollama not running | No vectors; BM25-only search |
| Rerank call fails | Fused top-k used |
| Agent runs out of steps | Returns what it gathered |
Memory extraction fails (LLMError) | Answer still returned, run logged |
The common thread: errors are data. They go back into the transcript as text so the model can adapt instead of the program dying.
The File Map
personal_ai/runner.py the loop, the prompt template, routing
personal_ai/llm.py the only model call
personal_ai/agents.py load / create / update / revert agents
personal_ai/skills.py the 22 skills + SKILLS registry
personal_ai/memory.py facts, rules, brand, recall, learn
personal_ai/index.py extract, chunk, embed, BM25, RRF, rerank
personal_ai/approvals.py the human-in-the-loop queue
personal_ai/mcp.py MCP client and server helper
personal_ai/connectors/ email_server.py, db_server.py
pai.py the command-line interface
agents/*.json agent definitions (+ history/ backups)
memory/*.md what it has learned, rules, brand
index/ sources.txt and index.db
approvals/queue.jsonl pending and decided actions
logs/runs.jsonl, search.jsonl an audit trail
workspace/ where agents write files by default
tests/ offline tests using a fake model
Try It
&&
Requirements: the Claude CLI on your PATH and logged in. Optional: Ollama with ollama pull nomic-embed-text for semantic search; an email App Password in PAI_EMAIL_USER / PAI_EMAIL_PASS for mail.
;
What I Took Away From Building It
- Treat the model as an untrusted planner, not as a program. Every guardrail here is ordinary code around an unreliable component.
- Make failure legible. Turning exceptions into text the model can read made the system far more robust than raising errors.
- Plain files beat clever infrastructure at this scale. JSON agents, markdown memory and a JSONL queue can all be inspected and edited with a text editor, and they make debugging trivial.
- Hybrid retrieval is worth the extra 100 lines. Keyword and vector search fail in different ways; fusing them is cheap, and a final model rerank removes most remaining noise.
- Be honest about limits: no OCR, no JavaScript rendering, in-memory vector scan, and an approval gate that lives in the app rather than the mailbox. Writing them down is part of the design.
Every diagram in this post was generated from the same facts as the code. If you read one file to understand the whole system, read runner.py: it is about 160 lines.