Skip to content
theo79Public

About

Zero-dependency, local-first AI assistant with dual CLI & Web UI, Ollama and cloud multi-provider inference (Gemini, OpenRouter, OpenAI), hybrid BM25 + vector RRF memory, and predictive context routing.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

56 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Athena

Athena v0.15

Zero-dependency, local-first AI assistant with autonomous workspace tool execution & multi-turn action chaining, dual CLI & Web UI, Ollama and cloud multi-provider inference (Gemini, OpenRouter, OpenAI), hybrid BM25 + vector RRF memory, and predictive context routing.

Release v0.15 Download Windows Binary


Overview

Athena (v0.15) is a zero-dependency local/cloud hybrid AI work assistant and autonomous agent runtime designed for reading and writing workspace files safely, chaining multi-turn tool actions, remembering approved preferences, searching the web when enabled, and assisting with summarization, comparison, analysis, and drafting.

Athena combines:

  • Dual-Interface Runtime: Interactive startup selection between Terminal (CLI) and Windowed Browser Web UI (--cli / --web).
  • Dual Execution Engine: Local inference via Ollama (with cold-start VRAM protection) and Custom Local / LM Studio OpenAI-compatible servers, plus zero-SDK standard-library cloud inference via Google Gemini, OpenRouter, and OpenAI (ChatGPT).
  • Predictive Routing Engine: Decoupled capacity saturation (window_saturation_threshold) and burn-rate pace budgeting (burn_rate_pressure_limit) with proactive exhaustion penalties.
  • Hybrid Memory Retrieval Engine: BM25 lexical scoring fused with semantic vector embeddings via Reciprocal Rank Fusion (RRF, $k = 60$).
  • Autonomous Workspace Tool Execution & Multi-Turn Chaining: Sandboxed filesystem operations (read_file, write_file, list_dir, get_file_info) with strict path boundary validation and XML <action> / <action_result> multi-turn chaining.

Standalone Windows Release (v0.15)

Download the pre-packaged Windows executable archive (Athena-v0.15-windows.zip) from the GitHub Releases page (https://github.com/theo79/Athena/releases/download/v0.15/Athena-v0.15-windows.zip), extract Athena.exe, and launch it directly.


Key Architectural Features

1. Dual-Interface Mode: Terminal CLI & Windowed Browser Web UI (agent.py, web_ui.py)

Before model initialization, Athena prompts you to select how you want to interact:

Select interface mode:
[1] Terminal (CLI)
[2] Browser (Windowed Web UI)
  • CLI Bypass Flags: Pass --cli to launch directly into the terminal REPL or --web (alias --browser) to launch directly into the browser interface.
  • Zero-Dependency Local Web Server (web_ui.py):
    • Built on Python's standard library http.server.ThreadingHTTPServer.
    • Binds to http://127.0.0.1:8080 with automatic dynamic port fallback if port 8080 is busy, and opens the default browser automatically via webbrowser.open().
    • Serves a single-file modern dark-theme UI with decoupled local/cloud provider status badges (GET /api/status), an interactive model dropdown supporting both local Ollama tags (GET /api/models?provider=ollama) and dynamic OpenRouter model discovery (GET /api/models?provider=openrouter), Cloud provider + API key configuration controls (POST /api/config), and chat endpoints (POST /api/chat and POST /api/chat/stream).
    • Real-Time Server-Sent Events (SSE) Token Streaming (POST /api/chat/stream): Streams tokens over http.server.ThreadingHTTPServer (Content-Type: text/event-stream) using stream_generate() generators on OpenRouterProvider and OllamaProvider, progressively rendering tokens in the browser chat bubble as they arrive.
  • Visual Feedback & Streaming Telemetry:
    • Terminal Spinner: Displays an animated Athena is thinking / loading model... background spinner (thinking_spinner) on sys.stdout using \r and cleanly overwrites the line once the response is ready.
    • Smart Scroll Lock: Retains manual scroll position during streaming generation if the user scrolls up (distanceFromBottom > 60 pixels) to read earlier responses, and resets automatically on new message submission.
    • Interactive Stop / Cancellation: Dynamic Send / Stop (.btn-stop) button toggling backed by AbortController (userExplicitlyAborted guarded) and clean server disconnect handling without unhandled tracebacks.
    • Tri-State Status Indicators: Distinguishes between model warm-up/loading (Loading model into memory... via the #model-status-strip animated progress strip and "status": "loading"), token generation (Generating response... / Generating... and "status": "generating"), and idle (Ready and "status": "ready").
    • Resilient Connection Handling: Transparently catches client socket disconnects (ConnectionAbortedError, BrokenPipeError, ConnectionResetError) in HTTP handlers to prevent server thread crashes on Windows.

2. Dual Execution Engine, Multi-Provider Support & Interactive Wizard Navigation (models.py, settings.py)

Athena enforces a guided interactive startup wizard and implements all local and cloud providers using Python's standard library urllib.request / urllib.error (zero third-party SDK dependencies):

  • Execution Mode Selection & Sub-Menu Back Navigation (prompt_execution_mode()):
    • Prompts Select execution mode [1-3]: across [1] Local (Ollama), [2] Local (Custom / LM Studio / OpenAI-compatible server), and [3] Cloud (Gemini / OpenAI / OpenRouter).
    • Interactive Back Navigation ([0] Back to mode selection): Every sub-menu—Ollama model selection, Custom Local / LM Studio endpoint URL & model setup (0, b, or back), and Cloud provider selection—supports returning cleanly to the parent Execution Mode Selection menu without restarting Athena.
  • Local Mode ([1] Local / [2] Custom Local) & Ollama Cold-Start Protection:
    • Queries Ollama's local tags endpoint (GET http://localhost:11434/api/tags), lists installed models ([1] llama3.2, [2] mistral, etc., alongside [0] Back to mode selection), and sets CHAT_MODEL to your selection, or offers an interactive recovery menu if Ollama is offline.
    • Proactive VRAM Warm-Up (OllamaProvider.warmup_model()): Immediately sends a lightweight POST /api/generate warm-up ping when a model is selected (in the CLI or via /api/config in the Web UI) so Ollama begins allocating GPU VRAM from disk right away.
    • Extended 300s Generation Timeout: Uses a 300.0-second (5-minute) CHAT_TIMEOUT for generation requests to prevent client timeouts while multi-gigabyte models load into VRAM, while keeping tag discovery and warm-up pings responsive at 10.0 seconds (DISCOVERY_TIMEOUT).
  • Cloud Mode ([3] Cloud), Dynamic OpenRouter Discovery & Pre-Flight Key Validation:
    • Supports three cloud providers out of the box (with [0] Back to mode selection):
      • [1] Google Gemini (GeminiProvider)
      • [2] OpenRouter (OpenRouterProvider — includes list_models() dynamic model discovery via GET https://openrouter.ai/api/v1/models with automatic fallback to openrouter/free, plus SSE stream_generate())
      • [3] OpenAI (ChatGPT) (OpenAIProvider — https://api.openai.com/v1/chat/completions, supporting gpt-4o-mini, gpt-4o, and o3-mini, defaulting to gpt-4o-mini)
    • Checks environment variables and .env for GEMINI_API_KEY, OPENROUTER_API_KEY, or OPENAI_API_KEY, prompting in the terminal if missing.
    • Runs a lightweight pre-flight validation probe (e.g., GET https://api.openai.com/v1/models with Authorization: Bearer <OPENAI_API_KEY>) and re-prompts cleanly on 401 Unauthorized or invalid keys.
Provider Execution Mode API Key Variable Default Chat Model Embedding Model
Ollama Local (http://localhost:11434) None Selected via wizard (llama3.2) nomic-embed-text
Google Gemini Cloud GEMINI_API_KEY gemini-3.1-flash-lite text-embedding-004
OpenRouter Cloud OPENROUTER_API_KEY openrouter/free text-embedding-3-small
OpenAI (ChatGPT) Cloud OPENAI_API_KEY gpt-4o-mini (gpt-4o, o3-mini) text-embedding-3-small

3. Predictive Routing Engine (routing.py)

Athena includes a deterministic candidate placement and resource-budgeting module (routing.py) that separates capacity consumption from consumption pace:

  • Decoupled Threshold Metrics (RoutingConfig):
    • window_saturation_threshold (default 0.85): Fractional capacity of the context or request window consumed (window_used / window_capacity), evaluated by hard_exhausted().
    • burn_rate_pressure_limit (default 1.2): Consumption pace relative to replenishment (consumption_rate / refill_rate), evaluated by placement_drain() / should_drain_placement().
  • Proactive Exhaustion Scoring (predicted_to_run_out()):
    • Estimates time-to-exhaustion across critical_window_seconds (default 300.0s) and applies run_out_score_penalty or exclude_on_predicted_run_out inside evaluate_candidate() and choose().

4. Hybrid Memory Retrieval Layer (tool_modules/memory.py, conversation.py, experience.py)

  • Hybrid Search (Lexical + Semantic + RRF):
    • Lexical Component (lexical_score, rank_lexical): BM25-style term frequency (k1=1.5, b=0.75) with inverse document frequency, token overlap ratio, and phrase match bonuses.
    • Semantic Component (embed_text, cosine_similarity, rank_semantic): Computes vector embeddings using the active provider (nomic-embed-text on Ollama, text-embedding-004 on Gemini, or text-embedding-3-small on OpenRouter and OpenAI) and ranks entries by cosine similarity.
    • Reciprocal Rank Fusion (reciprocal_rank_fusion, hybrid_search_memory): Combines lexical and semantic rankings using RRF with constant $k = 60$: $$\text{RRF_score}(d) = \sum_{r \in {\text{lexical}, \text{semantic}}} \frac{1}{60 + \text{rank}_r(d)}$$
    • Graceful Degradation: Smoothly degrades to BM25 lexical ranking if embeddings are unavailable.
  • Bounded Session Context (ConversationSession): In-memory turn history bounded to the active session (/history, /clear).
  • Experience History (experiences.json): Compact telemetry records of past task executions, tool outcomes, and user feedback (/good, /bad, /neutral).

5. Autonomous Workspace Tool Execution & Multi-Turn Chaining Engine (tools/, agent.py)

  • Zero-Dependency Sandboxed Filesystem Tools (tools/workspace.py — WorkspaceManager):
    • Exposes read_file (with max_bytes truncation), write_file (with automatic parent directory creation), list_dir (supporting recursive traversal up to max_depth), and get_file_info.
    • Enforces strict directory boundary confinement via canonical path resolution (Path.resolve()) and containment verification (Path.is_relative_to(root_path)), rejecting parent directory traversal (../../), absolute root escapes (/etc, C:\Windows), and out-of-bounds symlinks with PermissionError.
  • Robust XML/JSON Action Block Protocol (tools/dispatcher.py — ActionDispatcher):
    • Parses model-generated <action name="tool_name">...</action> blocks with lenient markdown code-fence stripping (```json ... ```) and dispatches calls to WorkspaceManager.
    • Wraps execution outputs and captured exceptions (PermissionError, FileNotFoundError, JSONDecodeError, unknown tool names) into structured <action_result name="..." status="success|error"> blocks without crashing the runtime.
  • Autonomous Multi-Turn Chaining Loop (agent.py — run_turn_with_tools):
    • Automatically executes <action> blocks, appends <action_result> feedback to ConversationSession, and re-queries the active model provider until a final answer is produced or the safety recursion cap (max_iterations = 5) is reached.
    • Provides live UI telemetry callbacks: terminal CLI tool execution alerts (⚙ Running workspace tool: <tool_name>(<args_summary>)...) and Web UI tools_executed metadata in POST /api/chat.

Getting Started & Quickstart

1. Environment Setup

Requires Python 3.12 or newer. Athena's core runtime and unit tests run with zero required third-party packages (pure Python standard library).

python -m venv .venv
.\.venv\Scripts\Activate.ps1

On macOS/Linux:

python3 -m venv .venv
source .venv/bin/activate

2. Configuration (.env.example)

Copy .env.example to .env in the project directory (or %LOCALAPPDATA%\Athena\.env on Windows) to pre-populate optional settings, or rely on the interactive startup wizard / Web UI controls:

MODEL_PROVIDER=openrouter
MODEL_NAME=openrouter/free
WEB_SEARCH_ENABLED=false
MY_AGENT_DEBUG=false

# Cloud API Keys (if omitted, Athena will prompt interactively in Cloud mode)
OPENROUTER_API_KEY=
GEMINI_API_KEY=
OPENAI_API_KEY=

# Local Ollama endpoint (no API key required)
OLLAMA_BASE_URL=http://localhost:11434

3. Execution Commands

# Interactive startup (prompts for [1] Terminal CLI or [2] Browser Web UI)
python agent.py

# Launch directly into the Windowed Browser Web UI (http://127.0.0.1:8080)
python agent.py --web

# Launch directly into the Terminal CLI setup wizard
python agent.py --cli

# Pre-select execution mode in Terminal CLI
python agent.py --cli --mode local
python agent.py --cli --mode cloud

# Dry-run verification (initializes configuration and checks connectivity, then exits 0)
python agent.py --dry-run --mode local
python agent.py --dry-run --mode cloud

Running Tests

Execute the full unit test suite covering CLI startup flows & providers (test_cli.py), browser Web UI endpoints (test_web_ui.py), predictive routing (test_routing.py), hybrid memory retrieval (test_memory.py), workspace filesystem tools (test_tools.py), and multi-turn tool chaining (test_tool_chaining.py):

# Discover and run all unit tests with verbose output
python -m unittest discover -v

# Or run specific test suites directly
python -m unittest test_cli.py test_web_ui.py test_routing.py test_memory.py test_tools.py test_tool_chaining.py -v

License

Licensed under the Apache License 2.0.

About

Zero-dependency, local-first AI assistant with dual CLI & Web UI, Ollama and cloud multi-provider inference (Gemini, OpenRouter, OpenAI), hybrid BM25 + vector RRF memory, and predictive context routing.

Topics

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages