Build a Custom Cyber Coach with Python and Dot AI
Step-by-step tutorial on building a secure AI cyber coach for small businesses using Python, local vector search, and dot framework integration.

Designing Your Small Business Cyber Security Coach Architecture
Small business owners rarely have dedicated security teams, leaving them vulnerable to basic phishing, credential stuffing, and unpatched endpoints. You are going to build a local first cyber coaching agent using Python, a lightweight vector store, and modern LLM APIs to bridge this gap. This system intercepts common security workflow friction points by evaluating configurations, scanning local logs, and dispensing actionable hardening advice.
The system relies on a three-tier design. First, a local ingestion engine parses system configurations and network state snapshots. Second, a retrieval augmented generation pipeline matches those snapshots against standardized frameworks like NIST Small Business cybersecurity guidelines. Third, an orchestration layer driven by a local execution loop delivers clear, prioritized mitigation steps directly to a terminal dashboard or a messaging integration.
Performance matters when running diagnostic tools on resource constrained hardware. You will configure the agent to run locally with fallback capabilities to cloud endpoints when heavy reasoning is required. By the end of this guide, your coach will parse local audit logs, detect exposed ports, and generate compliance checklists without leaking sensitive data to third-party endpoints.
Setting Up Your Local Development Environment and Dependencies
Before writing code, verify your workstation meets the minimum performance and security requirements for running local agent pipelines. You will need a UNIX-based environment, ideally Ubuntu 24.04 LTS or macOS Sonoma, paired with at least 16GB of RAM and a dedicated or integrated GPU capable of handling local embedding generation.
Open your terminal and verify your Python runtime version. This project requires Python 3.11 or newer to take advantage of modern typing syntax and asynchronous task handling.
python3 --version
# Must output Python 3.11.x or higher
Create an isolated virtual environment and activate it before installing packages. This prevents version conflicts with global system packages.
python3 -m venv cyber-coach-env
source cyber-coach-env/bin/activate
pip install --upgrade pip
Install the required libraries for vector search, LLM orchestration, and log parsing. We will use pydantic for strong data validation, chromadb for local storage, and requests for API communication.
pip install pydantic==2.8.2 chromadb==0.5.5 requests==2.31.0 pyyaml==6.0.1
Create your project directory structure to keep your source code, configuration files, and local vector database cleanly separated.
mkdir -p cyber_coach/{data,logs,config}
touch cyber_coach/main.py cyber_coach/engine.py cyber_coach/config/settings.yaml
Configuring the Coach Knowledge Base and Vector Store
Your cyber coach needs a localized knowledge base containing foundational security principles tailored for small business infrastructure. Instead of relying purely on parametric model memory, you will ingest structured markdown files containing hardening guidelines for routers, firewalls, and workstation endpoint protection.
Populate your configuration file at cyber_coach/config/settings.yaml with the following parameters. Make sure to adjust the logging level and vector store persistence path according to your deployment target.
app_name: "SmallBizCyberCoach"
version: "1.0.0"
vector_store_path: "./data/chroma"
embedding_model: "all-MiniLM-L6-v2"
risk_threshold: "medium"
max_tokens: 1500
Now write the initialization script inside cyber_coach/engine.py to spin up your persistent ChromaDB client and load the initial security markdown documents into the vector collection.
import chromadb
from chromadb.utils import embedding_functions
import yaml
class SecurityKnowledgeBase:
def __init__(self, config_path="cyber_coach/config/settings.yaml"):
with open(config_path, "r") as f:
self.config = yaml.safe_load(f)
self.client = chromadb.PersistentClient(path=self.config["vector_store_path"])
self.embedding_fn = embedding_functions.DefaultEmbeddingFunction()
self.collection = self.client.get_or_create_collection(
name="security_guidelines",
embedding_function=self.embedding_fn
)
def seed_knowledge(self):
documents = [
"Ensure multi-factor authentication (MFA) is enforced on all administrative accounts, cloud services, and email portals.",
"Disable Universal Plug and Play (UPnP) on all office routers to prevent malicious external port mapping.",
"Maintain automated daily backups with immutable storage offsite to defend against ransomware attacks.",
"Enforce disk encryption using BitLocker or FileVault across all employee laptops and mobile workstations."
]
ids = ["doc_1", "doc_2", "doc_3", "doc_4"]
metadatas = [{"category": "identity"}, {"category": "network"}, {"category": "backup"}, {"category": "endpoint"}]
self.collection.upsert(
documents=documents,
ids=ids,
metadatas=metadatas
)
print(f"Seeded {len(documents)} documents into vector storage.")
if __name__ == "__main__":
kb = SecurityKnowledgeBase()
kb.seed_knowledge()
Implementing the Core Agent Logic and Audit Parser
With your knowledge base ready, you must write the core evaluation engine that ingests system audit files and queries the vector store for matching mitigations. Create the main execution script in cyber_coach/main.py to tie the components together.
This script reads a mock system audit report simulating an insecure small business network, queries the local vector database for relevant security guidelines, and formats a structured remediation plan.
import json
from engine import SecurityKnowledgeBase
class CyberCoachAgent:
def __init__(self):
self.kb = SecurityKnowledgeBase()
def evaluate_audit_report(self, report_path):
with open(report_path, "r") as f:
report_data = json.load(f)
findings = report_data.get("findings", [])
remediation_plan = []
for finding in findings:
query = finding.get("description")
results = self.kb.collection.query(
query_texts=[query],
n_results=1
)
best_match = results["documents"][0][0] if results["documents"] else "No specific guideline found."
remediation_plan.append({
"issue": finding.get("title"),
"severity": finding.get("severity"),
"recommendation": best_match
})
return remediation_plan
if __name__ == "__main__":
# Generate a dummy audit report for testing
sample_report = {
"findings": [
{"title": "Router UPnP Enabled", "severity": "High", "description": "UPnP is active on the main gateway router allowing automatic port forwarding."},
{"title": "Missing MFA on Email", "severity": "Critical", "description": "Primary admin email account does not enforce multi-factor authentication."}
]
}
with open("cyber_coach/logs/sample_audit.json", "w") as f:
json.dump(sample_report, f, indent=4)
coach = CyberCoachAgent()
plan = coach.evaluate_audit_report("cyber_coach/logs/sample_audit.json")
print("\n--- CYBER COACH REMEDIATION REPORT ---\n")
for item in plan:
print(f"Issue: {item['issue']} [{item['severity']}]")
print(f"Action: {item['recommendation']}\n")
Running the End-to-End Diagnostic Demonstration
Execute your newly constructed coaching agent to observe the automated analysis workflow in action. Run the main module directly from your virtual environment.
python3 cyber_coach/main.py
Upon successful execution, your terminal will output the parsed findings mapped directly to your vector stored security guidelines. Here is the expected output format from your diagnostic run:
Seeded 4 documents into vector storage.
--- CYBER COACH REMEDIATION REPORT ---
Issue: Router UPnP Enabled [High]
Action: Disable Universal Plug and Play (UPnP) on all office routers to prevent malicious external port mapping.
Issue: Missing MFA on Email [Critical]
Action: Ensure multi-factor authentication (MFA) is enforced on all administrative accounts, cloud services, and email portals.
This output proves your local pipeline successfully ingests structured audit JSON, queries the local embedding space without external data leakage, and surfaces precise remediation tasks.
Troubleshooting Common Configuration and Runtime Errors
Building local AI agents often exposes environment bottlenecks and package version mismatches. Review these three common failure modes and their exact terminal resolutions before deploying your coach to production hardware.
1. SQLite Version Mismatch in ChromaDB
If you encounter an error stating RuntimeError: Your system has an unsupported version of sqlite3, your operating system is running an older SQLite library than ChromaDB requires. Fix this by installing the pysqlite3 binary package.
pip uninstall sqlite3
pip install pysqlite3-binary
Add this override snippet to the top of cyber_coach/engine.py to force Python to use the updated library:
import sys
try:
__import__('pysqlite3')
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')
except ImportError:
pass
2. Embedding Dimension Shape Mismatch
If you modify the default embedding model in your YAML configuration without clearing your existing ChromaDB directory, you will hit a dimension mismatch error during collection queries. Wipe the local vector store cache and reseed the knowledge base.
rm -rf cyber_coach/data/chroma
python3 cyber_coach/engine.py
3. Missing Dependency Wheels on ARM64 Architectures
When running this setup on Apple Silicon (M1/M2/M3/M4) Macs, numpy or tokenizers compilation can fail if build tools are outdated. Upgrade your build toolchain using pip and wheel.
pip install --upgrade setuptools wheel
pip install --no-build-isolation chromadb
Hardening and Scaling Your Cyber Coach for Production
Moving your cyber coach from a local development script to a reliable operational service requires addressing data privacy, rate limiting, and access control. Small businesses handle sensitive payroll, client lists, and proprietary records, meaning zero accidental data exfiltration is mandatory.
Implement strict environment variable management for any optional API keys using a .env file loaded via python-dotenv. Never hardcode credentials into your YAML configuration files or source code repositories.
# .env file structure
OPENAI_API_KEY="sk-proj-placeholder"
COACH_LOG_LEVEL="INFO"
ENCRYPTION_KEY_PATH="/etc/cyber_coach/secret.key"
Schedule your audit script using a secure system crontab to run weekly system checks. Ensure your log directories have restrictive file permissions (chmod 600) so unauthorized local users cannot read raw system audit outputs containing internal IP addresses or open ports.
Extending Your Agent with Advanced Capabilities
Once your basic coaching loop is stable, extend its functionality to handle active network scanning and automated notification dispatch. Integrate the Python nmap library to dynamically discover local open ports before running your vector search evaluation.
Another powerful upgrade involves wiring your coach into a local messaging webhook, such as a private Mattermost or Slack channel, allowing the agent to post morning security briefings directly to your team workspace. By keeping the core reasoning loop local and leveraging small, task-specific vector collections, you maintain absolute control over your operational data while providing enterprise-grade guidance to lean teams.
Bottom Line
Building your own cyber coach gives small businesses a practical defense mechanism against digital threats without incurring heavy subscription fees or risking data privacy leaks. Use the code provided in this guide to secure your infrastructure today, keep your dependencies updated, and audit your configurations regularly.
Related Analyses
More in Tutorials →
How to Build a YouTube History Analysis Pipeline
Build a Python pipeline to extract, parse, and analyze your full YouTube viewing history back to 2020 using modern local language models.

How to Generate a 3D Game Engine with AI
I tested single prompt 3D game engine generation using LLMs. Here is how to build, run, and fix an AI generated rendering pipeline from scratch.

Run NVIDIA Cosmos 3 Locally With Diffusers
Step-by-step technical guide on running NVIDIA Cosmos 3 locally on your hardware using Hugging Face Diffusers, including full code blocks and