A CLI code explainer powered by a local Llama model via Ollama — paste any code snippet and get a plain-English explanation, fully offline.
Ollama runs LLMs locally. After installing, pull a model and start the server.
# In your terminal — one-time setup:
# 1. Download Ollama from https://ollama.com/download
# 2. Pull a model (3B = ~2 GB download):
ollama pull llama3.2
# 3. Ollama starts automatically as a background service.
# The API is at http://localhost:11434
Ollama exposes a local REST API — the same interface as OpenAI, but free and local.
import requests, json
def explain_code(code_snippet, model='llama3.2'):
prompt = f"""Explain the following code in simple, plain English.
Focus on WHAT it does and WHY, not a line-by-line walkthrough.
Be concise — 3-5 sentences max.
Code:
{code_snippet}"""
response = requests.post(
'http://localhost:11434/api/generate',
json={'model': model, 'prompt': prompt, 'stream': False},
timeout=120,
)
data = response.json()
return data['response']
# Test it
sample = """
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
"""
print(explain_code(sample))
This function calculates the nth Fibonacci number using recursion. It works by breaking the problem down: the Fibonacci number at position n is the sum of the two numbers before it. The base cases (n=0 and n=1) return the number itself, stopping the recursion. Note: this approach is elegant but inefficient for large n because it recalculates the same values many times.
Stream the response token by token so users see the explanation as it generates.
import requests, json, sys
def explain_code_streamed(code_snippet, model='llama3.2'):
prompt = f"""You are a helpful coding tutor. Explain this code in plain English.
Tell the reader WHAT the code does, HOW it works at a high level,
and any important caveats. Be friendly and concise.
{code_snippet}"""
with requests.post(
'http://localhost:11434/api/generate',
json={'model': model, 'prompt': prompt, 'stream': True},
stream=True, timeout=120,
) as resp:
print("\nExplanation:\n" + "="*40)
for line in resp.iter_lines():
if line:
data = json.loads(line)
print(data.get('response',''), end='', flush=True)
if data.get('done'): break
print()
def main():
print("Code Explainer (Ollama + llama3.2)")
print("Paste your code below. Type END on a new line when done.\n")
lines = []
while True:
line = input()
if line.strip() == 'END':
break
lines.append(line)
code = '\n'.join(lines)
if code.strip():
explain_code_streamed(code)
main()
You built a zero-cost AI coding assistant that runs entirely on your own machine. No rate limits, no API costs, no data leaving your computer. The same Ollama API works with any open-source model — swap llama3.2 for codellama, phi3, or deepseek-coder.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.