Go ahead and open your Downloads folder or your Desktop right now... Do you see hundreds of files piled up in a chaotic mess? PDF receipts, user manuals, meeting slides, reference images, code files, and e-books — all jumbled together.
Here's the problem: manually organizing these files is tedious and drains your mental energy. Sure, you could write a basic sorting script that moves files by file extension — like shoving all .pdf files into one folder — but that doesn't really solve the problem. In reality, a PDF receipt and a PDF research paper belong in completely different places.
This is where Cognitive Automation — automating tasks that require basic cognitive processing — comes in. In this article, we'll build a 100% local AI Agent that runs entirely on your machine. It reads file names, analyzes the document type, and moves each file to the correct folder with precision.
---
### How the AI File Sorter Works
Instead of relying on file extensions or writing complex if-else chains, we'll use a Local LLM via Ollama as the decision-making brain. Our Python script will:
1. Scan the file list in the target folder (e.g., Downloads)
2. Send each file name to the local LLM for analysis
3. Classify the file — the LLM responds with the best-matching category from a predefined set (e.g., Receipts, Books, Projects, Media)
4. Move the file into the corresponding subfolder automatically
All processing happens on your machine. File names and sensitive document details never leave your hardware — no cloud, no third-party servers.
---
### Step 1: Set Up Your Environment & AI Model
Before writing any code, make sure you have Ollama installed (if you haven't yet, check out our previous Ollama setup guide).
We'll use a small, fast model that's smart enough for classification tasks — like Llama 3 (8B) or Gemma 2 (2B / 9B). In this example, we'll use gemma2:2b, which is extremely resource-efficient.
Open your terminal and pull the model:
ollama run gemma2:2b
Then install the required Python library:
pip install requests
---
### Step 2: Write the Python Script for Your AI Agent
Create a script called file_agent.py. The code is divided into three main parts: calling the Ollama API, making the classification decision, and handling the actual file moves.
Here's the working code:
import os
import shutil
import requests
import json
# Define source and target directories
SOURCE_DIR = os.path.expanduser("~/Downloads")
TARGET_BASE_DIR = os.path.expanduser("~/OrganizedFiles")
# Define target categories with descriptions so the AI understands context
CATEGORIES = {
"Receipts": "Receipts, invoices, payment confirmations, proof of payment",
"Books_and_Papers": "Books, e-books, research papers, in-depth technical manuals",
"Work_Documents": "Work documents, meeting reports, presentation slides (PPTX), work-related Word files (DOCX)",
"Code_and_Data": "Project code files (.py, .js, .json), database files (.csv, .xlsx, .sql)",
"Media_and_Designs": "Reference images, video files, audio recordings, raw design files (.psd, .fig)",
"Others": "Any files that don't fit the above categories or are uncertain"
}
# Pre-create target subfolders
for cat in CATEGORIES.keys():
os.makedirs(os.path.join(TARGET_BASE_DIR, cat), exist_ok=True)
def classify_file_with_ai(filename):
url = "http://localhost:11434/api/generate"
# Build a clear prompt that forces a single category name as the response
prompt = f"""
You are a personal file-organization AI assistant.
Analyze the following file name: "{filename}"
Then select exactly ONE best-matching category from the options below:
{json.dumps(CATEGORIES, ensure_ascii=False, indent=2)}
Strict rules:
- Respond with ONLY the English key name of the category (e.g., Receipts or Work_Documents)
- No explanations, no quotation marks, no introductory or closing text of any kind
"""
payload = {
"model": "gemma2:2b",
"prompt": prompt,
"stream": False,
"options": {
"temperature": 0.0 # Set to 0 for maximum determinism and consistency
}
}
try:
response = requests.post(url, json=payload)
result = response.json()
category = result.get("response", "").strip()
# Validate that the response matches a known category
if category in CATEGORIES:
return category
else:
# Fallback: search for a category name embedded in the response
for cat in CATEGORIES.keys():
if cat in category:
return cat
return "Others"
except Exception as e:
print(f"Error connecting to Ollama: {e}")
return "Others"
def organize_folder():
print(f"Scanning folder: {SOURCE_DIR}...")
files = [f for f in os.listdir(SOURCE_DIR) if os.path.isfile(os.path.join(SOURCE_DIR, f))]
if not files:
print("No files found to organize.")
return
for filename in files:
# Skip hidden files
if filename.startswith('.'):
continue
print(f"Analyzing: {filename}...")
category = classify_file_with_ai(filename)
src_path = os.path.join(SOURCE_DIR, filename)
dest_path = os.path.join(TARGET_BASE_DIR, category, filename)
# Handle filename collisions in the destination folder
if os.path.exists(dest_path):
base, extension = os.path.splitext(filename)
counter = 1
while os.path.exists(dest_path):
new_filename = f"{base}_{counter}{extension}"
dest_path = os.path.join(TARGET_BASE_DIR, category, new_filename)
counter += 1
try:
shutil.move(src_path, dest_path)
print(f"-> Moved to [{category}] ✓")
except Exception as e:
print(f"Error moving file {filename}: {e}")
if __name__ == "__main__":
organize_folder()
print("File organization complete!")
---
### Step 3: Test the Script
When you run this script, it scans all files in your Downloads folder (SOURCE_DIR), sends each name to your local AI model for classification, and immediately moves them into the appropriate subfolders under OrganizedFiles (TARGET_BASE_DIR).
Watch the classification in action:
* receipt_july2026.pdf → routed to Receipts
* intro_to_deep_learning_textbook.pdf → routed to Books_and_Papers
* marketing_plan_v2.docx → routed to Work_Documents
* data_clean_script.py → routed to Code_and_Data
The magic here is that you don't need to write regex patterns to catch hundreds of keywords. The LLM has Semantic Understanding — the ability to grasp contextual meaning — which lets it classify files by name with remarkable accuracy.
---
### Step 4: Schedule It for Full Automation
To make this a true Cognitive Automation system, you probably don't want to manually run a Python script every day. Let's schedule it to run automatically.
#### For macOS & Linux (via Cron):
1. Open Terminal and run crontab -e
2. Add a line to execute the script daily at 6:00 PM (or your preferred time):
```bash
0 18 * /usr/bin/python3 /path/to/file_agent.py
```
#### For Windows (via Task Scheduler):
1. Search for Task Scheduler in the Start menu
2. Select Create Basic Task and set the trigger to Daily
3. Under Action, choose Start a program and point it to your Python script
---
### Wrap-Up
Building a local AI file-organizing agent is just the tip of the iceberg when it comes to Cognitive Automation. It frees up your time and mental bandwidth from routine administrative tasks, so you can focus on what actually matters.
The beauty of running this on Private Brain OS is maximum privacy. Every byte of your data stays on your hardware — 100% of the time. Take this script, tweak the categories to match your workflow, and step into a more efficient, fully offline way of working!