Back home
Agentic Runtime Architecture — Local LLM + Tool Loop

How an agentic loop turns messages into tested code.

Instead of a single prompt-and-reply exchange, an agentic system runs a closed control loop: a local model proposes tool actions, an orchestrator executes them inside a sandboxed workspace, and real test results feed back as messages until the task passes.

4 Rolessystem · user · assistant · tool
4 Toolslist · read · write · pytest
12 StepsDefault self-healing cap
100% LocalOllama RTX 4070 + Sandbox
The Agentic Concept

Plan, act, observe, and self-correct — without human copy-pasting.

A standard chat completion stops after generating text. An agentic workflow gives the model structured capabilities (list_files, read_file, write_file, run_pytest) and wraps inference inside a while / for loop bounded by --max-steps.

Because every file write and pytest traceback is appended back into the conversation history, the model observes the consequences of its own code and repairs syntax or import errors autonomously.

System Anatomy

Four decoupled layers keep inference safe and deterministic.

The Brain — Ollama + qwen2.5-coder

Runs locally on the RTX 4070 GPU. Interprets requirements, writes FastAPI routes and pytest suites, and diagnoses stack traces across loop iterations.

The Orchestrator — agent.py

Manages the conversation state array, executes HTTP requests to /api/chat, parses structured or fallback JSON tool calls, and enforces --max-steps.

The Sandbox Guard — WorkspaceGuard

Resolves and locks all file operations strictly inside TARGET_DIR (e.g., C:\dev\fastapi-target), creating parent folders automatically while blocking path traversal.

The Verifier — exec_local + Target .venv

Runs pytest using the isolated virtual environment of the target repository so dependency checks and test execution never collide with the agent runtime.

The Message Protocol

Every turn is an append-only list of four message roles.

Ollama's /api/chat endpoint is stateless across HTTP calls. The orchestrator maintains memory by sending the growing messages array on every step.

Click any message row to inspect payload & effect
PowerShell CLIcode-agentagent.pyOrchestratorOllama LLMqwen2.5-coderGuard & Execfs_local / exec_localTARGET_DIR.venv / app / tests#1[CLI ARG] python agent.py $prompt#2[system + user] POST /api/chat + TOOLS#3[assistant] tool_calls / fallback JSON#4[ACTION] execute_tool(write_file)#5[DISK / VENV] Write file / run pytest#6[role: tool] Append tool result & loop#7[role: tool (retry)] Pytest fail -> rewrite loop#8[assistant] Final summary to stdout
Step #2 · system + user · POST /api/chat + TOOLS

Sends behavioral rules, user goal, and available tool schemas to local Ollama.

{ "model": "qwen2.5-coder", "messages": [system, user], "tools": TOOLS, "stream": false }
Behavioral Contract
role: "system"

Sets the engineering persona, enforces clean triple-quoted Python strings, and mandates running run_pytest after every code modification.

Task Specification
role: "user"

Injected from the PowerShell CLI or stdin. Defines target files, endpoints, and verification criteria without manual file editing.

Reasoning & Tool Intent
role: "assistant"

Generated by Ollama (qwen2.5-coder). Either requests function executions via tool_calls or emits the final completion summary once tests pass.

Grounded Observation
role: "tool"

Appended by agent.py after executing WorkspaceGuard or pytest. Feeds real file contents, write confirmations, or tracebacks back into context.

Interactive Execution Trace

One task. Four stages inside the agentic control loop.

Select any stage below to inspect how messages move between agent.py, Ollama, and your target FastAPI workspace during a single automated build-and-test cycle.

InitTool CallSandboxVerified
Step 1 · Context Init

System rules + user goal enter the message array

The orchestrator (agent.py) loads .env.local, initializes WorkspaceGuard on TARGET_DIR, and sends the initial messages list (system + user) plus the TOOLS schema to Ollama via POST /api/chat.

{ "role": "user", "content": "Create app/main.py with GET /health and run_pytest." }
tap to collapse
Step 2 · Model Decision

The LLM proposes structured tool calls instead of raw prose

Qwen2.5-coder evaluates the context and returns an assistant message containing tool_calls (or JSON extracted by extract_fallback_calls) specifying write_file, read_file, list_files, or run_pytest.

{ "role": "assistant", "tool_calls": [{ "function": { "name": "write_file", "arguments": { "rel_path": "app/main.py" } } }] }
tap to inspect payload
Step 3 · Sandbox Execution

WorkspaceGuard and exec_local act on disk safely

The model never touches the OS directly. agent.py validates paths inside TARGET_DIR, writes UTF-8 files, and runs pytest inside the target .venv, capturing returncode, stdout, and stderr.

{ "role": "tool", "content": "{\"returncode\": 1, \"stderr\": \"ModuleNotFoundError: No module named app.main\"}" }
tap to inspect payload
Step 4 · Self-Correction

Tool output feeds back into the loop until tests pass

Every tool result is appended to messages with role: 'tool' and sent back to Ollama on step + 1. If pytest fails, the model reads the traceback, rewrites the file, and re-runs tests until green or --max-steps is reached.

{ "role": "assistant", "content": "All pytest checks passed in C:\\dev\\fastapi-target." }
tap to inspect payload
Safety & Determinism

Guardrails that keep local code generation reliable.

  • ✓Strict workspace isolation: code-agent stays separate from fastapi-target and any additional target projects
  • ✓Path traversal protection: WorkspaceGuard blocks reads or writes outside the resolved TARGET_DIR root
  • ✓Dual tool-call parsing: handles native Ollama tool_calls as well as balanced JSON extraction from message content
  • ✓Closed-loop verification: code changes are only considered complete after pytest returns exit code 0
  • ✓Step-by-step console observability: logs [CONFIG], [STEP], [TOOL], and truncated [RESULT] on every turn
CLI Execution Pattern

Triggering a new build cycle from PowerShell.

C:\dev\code-agent — Orchestrator Command
$env:TARGET_DIR = "C:\dev\fastapi-target"
python agent.py "Update app/main.py, add tests, and run_pytest."

The orchestrator loops up to --max-steps turns, logging every tool invocation and halting automatically once the model confirms passing tests.