DEV Community

Sakshi Lunawat
Sakshi Lunawat

Posted on AI-assisted

Hand-Rolling an Agentic Loop: A Local Coding Assistant

After shipping a basic chatbot and a RAG pipeline, I wanted to go one level deeper: a coding agent that could actually read, search, and modify files in a workspace. The motivation was twofold. First, a learning goal: I wanted a hands-on understanding of the agentic loop — tool dispatch, context management, and guardrails — without the abstraction layers that production frameworks add. Second, a design constraint — I wanted everything to run on my machine. No cloud round-trips, no telemetry, no "your code is now training data" fine print.

The goal was to keep the implementation hand-rolled. No LangChain, no AutoGPT. Just a local LLM, a tool registry, and a loop.

Setup

I ran everything locally through Ollama. I pulled two models — Gemma 4:12B and Qwen3.8:27B — and set up a minimal Python project with uv. The agent runs entirely on the CLI. No web UI, no API server.

1. Read Tools: The Starting Point

I started with the three primitives every file-aware agent needs: list_folder, read_file, and search_folder. All three are built on pathlib and are intentionally simple — no AST parsing, no semantic search. Just rglob, read_text, and a line-level substring match.

Each tool is defined as a JSON schema (function name, description, parameters) and registered in a flat dispatch dictionary. The agent loop calls ollama.chat with the tool schemas attached; when the model returns a tool_calls block, I dispatch each call through the registry, append the result as a tool-role message, and loop.

The loop itself is capped at 15 iterations. On the second-to-last iteration, I inject a "nudge" message telling the model to stop exploring and summarise what it already has. This is a cheap way to prevent the model from spinning in circles when it's stuck. If the loop exhausts without a final text response, the user gets a fallback message suggesting they rephrase or break the task down.

I ran this read-only loop for a while before adding anything else. It was enough to browse a codebase, grep for a symbol, and get a summary. That felt like a useful tool on its own.

2. Guardrails: Layered Access Control

Once the agent could read files, the obvious question was: what stops it from reading /etc/passwd or your .env?

I built a three-layer validation system:

  • System paths are hard-blocked. A platform-aware list of OS-critical directories (/System, /usr, /etc, C:\Windows, etc.) is checked first. No prompt, no override.
  • Workspace boundary with a prompt. The agent's working directory is the default scope. If a path falls outside it, the user is prompted with a y/N confirmation. Once granted, that folder is added to the allow-list for the session.
  • Sensitive filenames are hard-blocked for writes. A glob-pattern list (.env, *.key, *.pem, .git, secrets, etc.) prevents the agent from writing to credential files even inside the workspace.

Reads and writes have different validation paths. Reads can be prompted; writes are denied outright if they fall outside the workspace or hit a sensitive pattern. The principle: reads are exploratory and reversible, writes are not.

3. Context Management

The system prompt is loaded from a separate SystemPrompt.txt file at startup. It encodes the agent's behavioural rules — always read README.md first, check current code state before suggesting changes, be concise, don't re-read files already in context, and so on.

Conversation history is capped at the last 20 messages. This is a blunt instrument, but for a local agent with a 27B model, it keeps the context window manageable and the latency reasonable. A sliding window is not the same as a summarisation strategy, and I'm aware of that trade-off.

4. Session Management

Sessions are persisted as individual JSON files under a per-project directory (~/personal_agent/agent_memory/<project_name>/sessions/). Each session gets a UUID filename. A conversations.json index maps human-readable names to session files, with a "current" pointer for the active conversation.

The command layer (/load, /list, /clear, /delete, /exit) sits on top of this. /exit and /clear both persist the current conversation under an LLM-generated name before starting fresh — the model is asked to produce a 2–3 word summary of the conversation, which becomes the session name. It's a small touch, but it makes sessions discoverable without manual bookkeeping.

5. Write Tools and Atomicity

Writes go through an atomic-write helper: write to a temp file in the same directory, fsync, then os.replace(). This is the standard POSIX-safe pattern — the target file is never left in a half-written state. There's also a 5 MB hard cap on content size to prevent the model from generating a multi-gigabyte file.

patch_file is the most interesting write tool. Instead of rewriting an entire file, it does a literal string replacement with an occurrences parameter (1, N, or -1 for all). When the old_text doesn't match, it attempts a near-miss search — comparing the first 20 characters and progressively shorter prefixes — and returns a snippet of the closest region. This helps the model self-correct without a full re-read.

6. What I'd Do Next

The agent is functional but deliberately minimal. A few things I'd tackle next:

  • MCP (Model Context Protocol) integration for external tool servers (GitHub, databases).
  • Structured output validation — right now tool arguments are passed through as-is; a schema-validation layer would catch malformed calls before they hit the dispatch.
  • A proper test suite. The validation layer and the atomic-write path are the two areas where a regression would be painful.
  • Summarisation-based context management instead of a hard 20-message window.

Final Thoughts

Building this in a weekend taught me more about agent design than reading three blog posts about it. The hard part isn't the loop — it's the guardrails, the context management, and the failure modes you don't think about until the model tries to rm -rf your .git directory. Keeping everything local and hand-rolled made those trade-offs visible in a way that a framework would have hidden.

Top comments (1)

Collapse
 
aisovereign profile image
Ananya Soni •

Hi, I am the Founder and CEO of AGI Systems Directorate. At our company, we work to achieve Artificial General Intelligence through a four-pillar hybrid approach combining autonomous AI agents, large language models, robotics, and biological human brain replication mechanisms.

I really appreciate your setup here, especially keeping the execution loop completely local via Ollama. Most people still build agents as thin API wrappers where you send a request to a remote endpoint, wait for a response, and call it a day. Beyond privacy, skipping cloud APIs saves you from dealing with the constant headache of 402 payment errors, 403s, 529 overloads, 500 internal server errors, malformed JSON payloads, and custom retry logic. Hand-rolling the dispatch dictionary, POSIX-safe atomic writes with fsync and os.replace, and that prefix-based near-miss fallback inside patch_file shows solid engineering instinct.

Capping conversation history at a hard sliding window of 20 messages is going to bottleneck you fast on multi-file tasks. Once an agent starts reading files, running search_folder, and iterating on patches, 20 turns evaporate in a couple of steps, and the model forgets the original file structure or architectural constraints it discovered at the start of the session.

Since you already noted moving toward summarization, the cleanest upgrade without blowing up local latency on a 27B model is a tiered memory architecture paired with observation masking. For observation masking on tool outputs, instead of keeping raw read_file or search_folder payloads in the active window forever, you can replace older tool outputs beyond the last 4 to 6 turns with compact one-line references like "[read src/main.py: lines 1-140, defined AppRouter and dispatch_loop]", keeping the reasoning traces and assistant tool calls intact while stripping bulky file dumps that eat 80% of your KV cache. For a rolling structured state anchor, rather than generic prose summarization that slowly loses exact symbol names and paths, you can maintain a persistent structured scratchpad block pinned right below SystemPrompt.txt, and every 10 to 12 messages have the model update a strict JSON or key-value state object tracking modified files, verified function signatures, active allow-listed directories, and remaining subtasks, then drop the older raw turns behind that checkpoint. And for semantic retrieval over your existing session store, since you are already saving sessions as UUID JSON files under agent_memory, embedding or indexing past tool outputs and decision logs locally, even with a lightweight BM25 or small local embedding model, lets the agent query its own earlier discoveries on demand instead of bloating the active context window. Personally, I prefer this last semantic retrieval method over the others because it is the exact approach we rely on across our own AI models.

Also, on your next step for structured output validation, binding Pydantic models directly to Ollama's format schema parameter will eliminate malformed tool arguments before they ever touch your dispatch loop. Great breakdown overall, looking forward to seeing how the MCP layer and context upgrades turn out.