Posted on
Artificial Intelligence

Artificial Intelligence Agent Projects

Author
  • User
    linuxbash
    Posts by this author
    Posts by this author

Artificial Intelligence Agent Projects for Your Linux Terminal

Your terminal is already the most powerful automation platform you own. Now imagine pairing it with a smart agent that can suggest the exact Bash command, summarize noisy logs, or answer man-page questions—all locally, and under your control.

This post shows you how to stand up a practical, Linux-first AI agent environment and build three useful agent projects you can run from Bash. We’ll favor local-first, reproducible tooling and include install instructions for apt, dnf and zypper wherever relevant.

Why AI agents belong in your shell

  • Proximity to the real work: On Linux, jobs are scripts, services, logs, and files. Agents that live in the terminal can propose actions you can execute immediately.

  • Local-first is now easy: With projects like Ollama, you can run capable models on your own machine—no API keys, no data leaving your box.

  • Composable: Bash, Python, jq, ripgrep, and containers give you a safe playground to prototype, sandbox, and observe agent behavior.

1) Prerequisites: a minimal, local-first stack

Install core tools. Pick the commands for your distro.

  • Ubuntu/Debian (apt):
sudo apt-get update
sudo apt-get install -y \
  python3 python3-venv python3-pip pipx \
  git curl jq ripgrep sqlite3 podman
  • Fedora/RHEL/CentOS (dnf):
sudo dnf install -y \
  python3 python3-pip python3-virtualenv pipx \
  git curl jq ripgrep sqlite podman
  • openSUSE (zypper):
sudo zypper refresh
sudo zypper install -y \
  python3 python3-pip python3-virtualenv pipx \
  git curl jq ripgrep sqlite3 podman

Install Ollama (local LLM runtime) and pull a model:

curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3
ollama run llama3 "hello from linux"

Optional: create a Python virtual environment for project code:

python3 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip

You’re set. Next: build.

2) Project 1 — A command-suggesting terminal agent (safe-by-default)

Goal: You describe a task in plain English. The agent proposes one safe Bash command, asks for confirmation, logs what happened, and then executes.

Install the lightweight client library:

. .venv/bin/activate
pip install ollama

Create agent_command.py:

#!/usr/bin/env python3
import os, sys, json, shlex, subprocess, datetime
import ollama

MODEL = os.environ.get("AGENT_MODEL", "llama3")
LOGFILE = os.environ.get("AGENT_LOG", "agent_command.log.jsonl")

SYSTEM = """You are a cautious Linux CLI assistant.

- Output exactly one shell command for bash on Linux that solves the user's task.

- Prefer read-only, non-destructive actions by default (use --dry-run or -n where available).

- Never use 'rm -rf /', 'mkfs', 'dd' to block devices, 'shutdown', or destructive operations.

- If the task is ambiguous, choose the least-destructive inspection command.

- Do not include explanations, only the command.
"""

BANNED = [
    " rm -rf", "mkfs", " :(){ :|:& };:", "shutdown", "reboot", "halt",
    ">/dev/sd", " of=/dev/sd", "dd if=", " :(){", "chown -R /", "chmod -R 777 /"
]

def is_safe(cmd: str) -> bool:
    low = " " + cmd.lower().strip()
    return not any(bad in low for bad in BANNED)

def main():
    if len(sys.argv) < 2:
        print("Usage: agent_command.py \"describe your task\"")
        sys.exit(1)

    task = sys.argv[1]
    msgs = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": task}
    ]
    res = ollama.chat(model=MODEL, messages=msgs)
    cmd = res["message"]["content"].strip()

    # simple guardrails
    if "\n" in cmd:
        cmd = cmd.splitlines()[0].strip()
    if not is_safe(cmd):
        print(f"[blocked] Proposed command rejected by safety filter:\n  {cmd}")
        sys.exit(2)

    print(f"Proposed command:\n  {cmd}")
    ans = input("Run this command? [y/N] ").strip().lower()
    allowed = ans in ("y", "yes")

    record = {
        "ts": datetime.datetime.now().isoformat(),
        "task": task,
        "model": MODEL,
        "cmd": cmd,
        "allowed": allowed,
    }

    if allowed:
        try:
            # run via bash -lc to support shell features safely
            completed = subprocess.run(["bash", "-lc", cmd], check=False)
            record["returncode"] = completed.returncode
            print(f"Return code: {completed.returncode}")
        except Exception as e:
            record["error"] = str(e)
            print(f"Error: {e}")
    else:
        print("Aborted.")

    with open(LOGFILE, "a") as f:
        f.write(json.dumps(record) + "\n")

if __name__ == "__main__":
    main()

Usage:

python agent_command.py "find the 5 largest log files under /var/log"
python agent_command.py "show open TCP ports with process names"

Tips:

  • For risky tasks, run inside a throwaway container:
podman run --rm -it --network=none -v "$PWD":/work -w /work registry.fedoraproject.org/fedora:latest bash

3) Project 2 — Log triage agent for journalctl errors (pure Bash + HTTP)

Goal: Summarize recent system errors and suggest next steps.

Ensure jq is installed (see apt/dnf/zypper above). Create triage-logs.sh:

#!/usr/bin/env bash
set -euo pipefail

MODEL="${AGENT_MODEL:-llama3}"
LINES="${LINES:-400}"
OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"

logs="$(journalctl -p 3 -xb --no-pager | tail -n "$LINES")"

prompt=$(cat <<'EOF'
You are a Linux SRE assistant. From the following journalctl errors:

- Group similar issues.

- Show the 3–5 most important items.

- For each item: probable cause, impacted service, and one next command to run.

- Use concise bullets.
EOF
)
prompt="$prompt

<logs>
$logs
</logs>
"

json=$(jq -n --arg model "$MODEL" --arg prompt "$prompt" \
  '{model:$model, prompt:$prompt, stream:false}')

curl -s "$OLLAMA_URL/api/generate" -d "$json" | jq -r '.response'

Make it executable and run:

chmod +x triage-logs.sh
./triage-logs.sh

You can cron this daily and send to a file:

0 9 * * * /path/to/triage-logs.sh >> /var/log/agent-triage.log 2>&1

4) Project 3 — Docs Q&A over man pages with grep-first RAG

Goal: Ask natural-language questions and get answers grounded in local man pages without setting up a full vector database.

Create man-qa.sh:

#!/usr/bin/env bash
set -euo pipefail

MODEL="${AGENT_MODEL:-llama3}"
OLLAMA_URL="${OLLAMA_URL:-http://localhost:11434}"

question="${*:-}"
if [[ -z "$question" ]]; then
  echo "Usage: man-qa.sh \"How do I extract a tar.gz to a directory?\"" >&2
  exit 1
fi

# Build a simple keyword pattern (words > 3 chars)
pattern="$(tr -cd '[:alnum:] ' <<<"$question" | tr ' ' '\n' | awk 'length>3' | paste -sd'|' -)"
pattern="${pattern:-tar|extract|archive}"

# Find candidate pages via apropos (man -k)
candidates=$(man -k . 2>/dev/null | rg -i -m 15 "$pattern" | awk '{print $1}' | cut -d'(' -f1 | sort -u | head -n 8)

context=""
for page in $candidates; do
  # dump and grep relevant lines with surrounding context
  snippet=$(man -P cat "$page" 2>/dev/null | rg -n -i -C2 "$pattern" || true)
  if [[ -n "$snippet" ]]; then
    context+="\n<<< $page >>>\n$snippet\n"
  fi
  # limit context size
  if [[ ${#context} -gt 8000 ]]; then break; fi
done

prompt=$(cat <<EOF
Answer the user's question using only the provided man-page snippets. Quote commands and flags accurately and include a short example when possible.
If relevant info is missing, say what page to check next.

Question:
$question

Snippets:
$context
EOF
)

json=$(jq -n --arg model "$MODEL" --arg prompt "$prompt" \
  '{model:$model, prompt:$prompt, stream:false}')

curl -s "$OLLAMA_URL/api/generate" -d "$json" | jq -r '.response'

Usage:

chmod +x man-qa.sh
./man-qa.sh "How do I extract a tar.gz to a specific directory?"
./man-qa.sh "Show IPv6 routes with ip command"

Real-world notes and options

  • Models: Start with llama3. For tighter command suggestions, smaller instruct models can be snappier. Pull additional models with ollama pull <name>.

  • Cloud fallback: If you want to use a cloud API, install a client and export your key:

. .venv/bin/activate
pip install openai
export OPENAI_API_KEY=sk-...

Then adapt the Python in Project 1 to call the OpenAI chat API instead of Ollama.

  • Reproducibility: Pin Python dependencies with pip-tools or requirements.txt. For scripts, ship a Makefile that sets up .venv.

  • Sandboxing: For any command-executing agent, prefer running inside podman with --network=none, bind mounts to a throwaway workspace, and consider ulimit and seccomp profiles.

Safety checklist for command-executing agents

  • Always confirm before executing.

  • Default to read-only or dry-run commands when available.

  • Maintain an allow/deny list (e.g., block rm -rf, mkfs, dd to block devices).

  • Log everything: prompts, proposed commands, return codes.

  • Consider running in a rootless container with no network for risky operations.

  • Timeouts for long-running commands.

Conclusion and next steps

You now have a Linux-native agent toolkit and three practical projects:

  • A safe terminal command suggester

  • A log triage assistant

  • A grep-first docs Q&A helper

Pick one to productionize this week. Add a simple TUI, wire in Podman sandboxes for risky tasks, and schedule the triage in cron. When you’re ready, layer on more tools (package managers, file search, service control) behind confirmation prompts.

If you build something useful, wrap it as a script in your dotfiles and share it with your team. Your shell just got a lot smarter—without leaving Linux.