Metadata-Version: 2.4
Name: nixtee-cli
Version: 0.11.1
Summary: Scoped PyTorch accuracy prediction, architecture search and MCP tools
Home-page: https://github.com/ajandera/nixtee-cli
Author: Nixtee s.r.o
Keywords: PyTorch GNN architecture search accuracy prediction MCP
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: click
Requires-Dist: requests
Requires-Dist: torch
Requires-Dist: pyyaml
Requires-Dist: questionary
Requires-Dist: mcp<3,>=2.3
Requires-Dist: keyring<26,>=25
Requires-Dist: rich
Requires-Dist: pandas
Provides-Extra: finetune
Requires-Dist: transformers<6,>=4.51; extra == "finetune"
Requires-Dist: huggingface-hub<3,>=0.34; extra == "finetune"
Requires-Dist: safetensors<1,>=0.5; extra == "finetune"
Requires-Dist: pillow<14,>=11; extra == "finetune"
Requires-Dist: sentencepiece<1,>=0.2; extra == "finetune"
Dynamic: author
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Nixtee CLI

Predict neural network accuracy before training for supported PyTorch models. Nixtee compares candidate graphs using a calibrated GNN. For the public UCI HAR completed-training benchmark, the production API supports 30 verified sequential graphs. Measure latency and memory locally on your target hardware.

## Try the public benchmark

```sh
python -m pip install https://nixtee.com/downloads/nixtee_cli-0.11.1-py3-none-any.whl
nixtee configure
curl -fsSLo uci-har-gru.py https://nixtee.com/downloads/uci-har-gru.py
nixtee validate --model-path uci-har-gru.py \
  --evaluation-protocol uci-har-sequence-validation-selected-max60-patience8-h200-v1 --json
```

Create a Free account at [nixtee.com](https://nixtee.com/#get-started) to obtain an API key and secret. The default allowance is 1,000 successful predictions per UTC calendar month and 250 per rolling five hours.

Start MCP with `nixtee mcp --transport stdio --workspace /absolute/path`. Use the Docker sandbox described in the [MCP setup guide](https://nixtee.com/docs/quick-start#mcp-connections). Call `predict_performance` with the source of the PyTorch `Net` class in `model_code` and `benchmark: "uci-har"` for the public benchmark. See [Nixtee for AI agents](https://nixtee.com/for-agents) for scope and example output.

---

## Table of Contents
1. [Key Features](#key-features)
2. [Architecture & Storage Locations](#architecture--storage-locations)
3. [Prerequisites](#prerequisites)
4. [Installation & Setup](#installation--setup)
   - [For Testers and Users (Quick Start)](#for-testers-and-users-quick-start)
   - [For Developers (Local Development)](#for-developers-local-development)
   - [Using Nix (Reproducible Dev Shell)](#using-nix-reproducible-dev-shell)
5. [Usage & CLI Commands](#usage--cli-commands)
   - [Interactive Chat Session Slash Commands](#interactive-chat-session-slash-commands)
6. [QA & Manual Testing Protocols](#qa--manual-testing-protocols)
   - [Test Case 1: Configuration & Credentials Storage](#test-case-1-configuration--credentials-storage)
   - [Test Case 2: Workspace Dataset Autodetection](#test-case-2-workspace-dataset-autodetection)
   - [Test Case 3: Interactive Design and Optimization Loop](#test-case-3-interactive-design-and-optimization-loop)
   - [Test Case 4: Security & Static AST Sanitization](#test-case-4-security--static-ast-sanitization)
   - [Test Case 5: Model Context Protocol (MCP) Server](#test-case-5-model-context-protocol-mcp-server)
7. [Development & Code Structure](#development--code-structure)
   - [Adding CLI Commands](#adding-cli-commands)
   - [Customizing the AST Security Engine](#customizing-the-ast-security-engine)
   - [Registering Custom MCP Tools](#registering-custom-mcp-tools)

---

## Nixtee Architect Compact

The Nixtee Desktop 1.2.0 Apple Silicon build includes Architect v0.2 Compact
and a private llama.cpp runtime. Nixtee starts the runtime locally when Design
or Search needs it. Ollama is optional in this build. The desktop Python
engine still needs Python 3.11+ and may download dependencies on first setup.
GNN validation continues to use the Nixtee API.

CLI 0.11.0 can use the same local bundle. Set `NIXTEE_ARCHITECT_DIR` to the
directory containing the GGUF and `runtime/llama-server`. In the macOS
application this is `Nixtee.app/Contents/Resources/architect`.

```sh
NIXTEE_ARCHITECT_DIR="/path/to/Nixtee.app/Contents/Resources/architect"   nixtee design --prompt 'Build a 12-feature classifier with three logits per example' --output model.py
```

A CLI installation without the bundle uses its existing Ollama setup.

| Evaluated model | Model file | Passed |
| --- | ---: | ---: |
| Nixtee Architect v0.2 Compact, Qwen Coder 1.5B with LoRA, Q8_0 | 1.65 GB | **59/59** |
| Nixtee Architect v0.1, Qwen Coder 7B with LoRA, Q4_K_M | 4.68 GB | 53/59 |
| Qwen Coder 3B, previous Nixtee default | — | 34/59 |

The evaluation used identical prompts and one deterministic generation per
model. It checked executable PyTorch behavior and requested architecture
constraints, including output shapes, finite gradients, depth and pooling where
applicable. The 59 cases include 28 reused synthetic cases, 28 new synthetic
cases and three short training checks on public CSV datasets. The result
measures this architecture-design suite. Training and evaluation details are
in the [benchmark notes](benchmarks/perun/architecture-sft/README.md).

## Key Features

- **Automated Performance Prediction:** Extract Graph representation of a PyTorch model and query the GNN SaaS backend for supported learned accuracy predictions. Unsupported datasets/protocols return a clear unavailable result; no latency is requested or returned.
- **Intelligent Architecture Design:** Local PyTorch design with the bundled Nixtee Architect Compact model or a separately selected Ollama model.
- **Automated Optimization Loop:** Iterative refinement of model designs (up to 20 attempts) to target >80% accuracy based on local dataset context.
- **Security-First AST Sanitization:** Static analysis blocks execution of dangerous statements (e.g. `os.system`, `subprocess`, `eval`) and enforces pure model definitions.
- **Model Context Protocol (MCP):** Start a built-in MCP server supporting stdio/SSE/Streamable HTTP to integrate with external tools (e.g. Claude Desktop, cursor, or other agent frameworks).

---

## Architecture & Storage Locations

To aid development and debugging, be aware of the following system paths:
* **API Configuration File:** `~/.nixtee/credentials` (Stores API Key and Secret, generated via `/configure` or `nixtee configure`).
* **Chat History Storage:** `~/.nixtee/chat_history.json` (Maintains conversation context between sessions).
* **Workspace Output Directory:** `./nixtee_models/` (Where generated Python models and optimization checkpoints are stored).
* **Generated Target Model:** `./generated_model.py` (The final output containing the PyTorch class definition with injected hyperparameters and custom training launcher).

---

## Prerequisites

- **Python:** Version 3.10 or higher.
- **Ollama for installations without an Architect bundle:** Nixtee uses Ollama locally to power its AI generation. If not already present, the CLI will automatically download and start the service (using `curl -fsSL https://ollama.com/install.sh`) and synchronize the `qwen2.5-coder:3b` intelligence module on its first run.

---

## Installation & Setup

Choose the setup method appropriate for your workflow:

### For Testers and Users (Quick Start)

Install the CLI globally or into your current Python environment:

```bash
pip install .
```

Alternatively, if you use [Nix](https://nixos.org/), run the CLI instantly without installing dependencies:

```bash
nix run github:ajandera/nixtee-cli
# or for local repository checks:
nix run
```

### For Developers (Local Development)

To modify or inspect the Nixtee CLI code, follow these steps to install in editable mode:

1. **Clone the repository:**
   ```bash
   git clone https://github.com/ajandera/nixtee-cli.git
   cd nixtee-cli
   ```

2. **Set up a Python Virtual Environment:**
   ```bash
   python3 -m venv venv
   source venv/bin/activate
   ```

3. **Install in Editable Mode with Dependencies:**
   ```bash
   pip install -e .
   ```

4. **Verify Development Mode Setup:**
   Run `nixtee --help` or run the script directly:
   ```bash
   python nixtee_cli.py --help
   ```

### Using Nix (Reproducible Dev Shell)

If you have Nix installed, you can launch a reproducible dev shell containing Python 3.10 and all required packages (PyTorch, Pandas, Click, Questionary, MCP, Rich, and more) pre-configured:

```bash
nix develop
```
Inside this shell, run the script directly via:
```bash
python nixtee_cli.py --help
```

---

## Usage & CLI Commands

Once installed, use the following root commands:

* `nixtee` (or `python nixtee_cli.py`): Starts the interactive AI assistant shell.
* `nixtee configure`: Launches the terminal configuration wizard to save your Nixtee, Hugging Face, and Kaggle API credentials.
* `nixtee hf search <query> [--type datasets|models]`: Search Hugging Face Hub for datasets or models.
* `nixtee hf download <repo_id> [--file filename]`: Download a dataset from Hugging Face directly into the local workspace.
* `nixtee kaggle search <query>`: Search Kaggle for public datasets.
* `nixtee kaggle download <owner/dataset>`: Download and extract a Kaggle dataset into the local workspace.
* `nixtee mcp [OPTIONS]`: Starts a Model Context Protocol (MCP) server.
  - `--transport <stdio|sse>` (default: `stdio`)
  - `--port <integer>` (default: `8000`, only for `sse` transport)
* `nixtee create-llm --output <path>`: Creates a compact decoder-only SML with causal SDSI Neural ODE blocks in place of self-attention.

### Creating an SML with SDSI Neural ODEs

The `create-llm` command writes a standalone PyTorch language model. Its sequence mixer follows the attached SDSI paper's predictor, state-dependent damping, and dissipative correction steps. A causal depthwise convolution provides local token interaction, so no attention layer is used. The generated `Net` accepts integer token IDs, returns next-token logits, and includes autoregressive `generate` support. Tokenization and training data preparation remain the caller's responsibility.

```bash
nixtee create-llm --output sml.py
# Tune the small-model dimensions and SDSI integrator:
nixtee create-llm --output sml.py --vocab-size 4096 --context-length 128 --width 96 --layers 3 --dt 0.1 --alpha 0.01
```

The defaults are a small local experiment configuration, not a pretrained model. The resulting weights are randomly initialized and must be trained on tokenized text before useful generation.

---

### Interactive Chat Session Slash Commands

When running the interactive chat session (via `nixtee`), you can enter standard chat prompts or use these helper commands:

| Command | Action |
| :--- | :--- |
| `/help` | Displays help panel with all available slash commands. |
| `/dataset` | Open interactive menu to switch active dataset or view details. |
| `/hf search <query>` | Search Hugging Face datasets directly inside the chat session. |
| `/hf download <repo_id>` | Download Hugging Face dataset and set it as active dataset. |
| `/kaggle search <query>` | Search Kaggle datasets directly inside the chat session. |
| `/kaggle download <dataset_ref>` | Download & extract Kaggle dataset and set it as active dataset. |
| `/usage` | Queries the Nixtee API for token usage stats (this month and last 5 hours). |
| `/history` | Fetches and displays a tabular log of past model predictions from the API. |
| `/configure` | Runs the API configuration wizard within the interactive session. |
| `/mcp` / `/mcp start` | Starts a background local SSE MCP server on port 8000. |
| `/mcp connect <cmd> [args...]` | Adds an external stdio server for Qwen in `~/.nixtee/credentials`; HTTP(S) URLs are also accepted. |
| `/mcp status` | Shows the current chat session’s server thread, uptime, exposed tools and configured external servers. |
| `clear` | Clears the session memory and resets chat history (keeps system prompt). |
| `exit` / `quit` | Ends the interactive session. |

---

## QA & Manual Testing Protocols

Use these test cases to verify the correctness of the CLI system.

### Test Case 1: Configuration & Credentials Storage
1. Execute configuration:
   ```bash
   nixtee configure
   ```
2. Enter a mock API Key and Secret when prompted.
3. Verify that the file `~/.nixtee/credentials` has been created.
4. Verify the file contents using:
   ```bash
   cat ~/.nixtee/credentials
   ```
5. Ensure the directory and file permissions are secure:
   - Credentials directory permissions should be `0700` (`drwx------`).
   - Credentials file permissions should be `0600` (`-rw-------`).

### Test Case 2: Workspace Dataset Autodetection
1. Create a dummy dataset in the current directory:
   ```bash
   echo "feature1,feature2,feature3,label" > dummy_data.csv
   echo "0.1,0.2,0.3,1.0" >> dummy_data.csv
   echo "0.4,0.5,0.6,0.0" >> dummy_data.csv
   ```
2. Launch the interactive assistant:
   ```bash
   nixtee
   ```
3. Check the "Workspace Context" panel in the output. It should auto-detect and display:
   ```text
   Workspace Context: Found datasets: dummy_data.csv
   ```
4. Verify that Nixtee correctly parses the target column. It prioritizes columns named `target`, `y`, `label`, or `class`, or prompts you with a selectable menu if none are found.

### Test Case 3: Interactive Design and Optimization Loop
1. Start `nixtee` in interactive mode.
2. Ask the assistant to design a model:
   ```text
   You > Design a PyTorch network with 3 linear layers
   ```
3. The AI assistant should generate Python code defining a `Net` class inheriting from `torch.nn.Module`.
4. The CLI will detect this code block and prompt:
   ```text
   Detected Python code. Start automated optimization (up to 20 attempts)? [Y/n]
   ```
5. Confirm (`Y`). The CLI will perform an optimization loop:
   - Generates intermediate versions in `nixtee_models/optimized_model_v{attempt}.py`.
   - Sends the model graph and feature shapes (derived from your local CSV or default=10) to the API.
   - If estimated accuracy is below 80%, it auto-appends feedback and loops again (up to 20 times).
   - If accuracy plateaus (equal results 3 times in a row) or hits early success (>= 80%), it breaks early.
6. Check that the final `generated_model.py` is written in your root directory and contains injected hyperparameters (`NIXTEE_LEARNING_RATE`, etc.) and a custom training launcher.
7. Confirm the prompt to start training:
   ```text
   Would you like to start the training process with these optimized parameters? [y/N]
   ```
   Selecting `y` executes `python generated_model.py` to verify PyTorch integration.

### Test Case 4: Security & Static AST Sanitization
1. Create a malicious model definition file containing forbidden commands:
   ```bash
   echo "import os\nclass Net:\n  def __init__(self):\n    os.system('echo dangerous')\n" > malicious_model.py
   ```
2. Test loading the model. If you trigger prediction on this model, the AST analyzer (`is_code_safe`) will catch this execution.
3. Try starting the CLI and pasting code containing `import os; os.system(...)`.
4. Ensure the program halts the execution of the model and displays the security alert panel:
   ```text
   ⚠️ Security Alert: Potential malicious code detected!
   The AI generated code containing forbidden calls: ['forbidden call: os.system']
   Execution has been blocked for your safety.
   ```

### Test Case 5: Model Context Protocol (MCP) Server
1. Let the MCP client launch a private process for the dataset workspace:
   ```bash
   nixtee mcp --transport stdio --workspace /absolute/path/to/workspace
   ```
2. Discover server capabilities through the client. For network transports, configure the required Bearer token; see [MCP security](MCP_SECURITY.md).
3. Verify all six tools are listed: `list_datasets`, `predict_performance`, `search_hf_datasets`, `download_hf_dataset`, `search_kaggle_datasets` and `download_kaggle_dataset`.
4. Call `list_datasets` and compare its absolute file paths with the workspace. Predictions require Nixtee API credentials; provider operations retain their own credential requirements.
5. In Electron, use **Tools → MCP connections** to test external servers for Qwen or select **Connect Codex** for the running Nixtee server. See the [complete MCP guide](documentation.md#mcp-connections-for-qwen-and-codex).

---

## Development & Code Structure

The CLI entry point and supporting MCP modules are:

- [nixtee_cli.py](nixtee_cli.py) - Contains:
  - CLI definition using Click.
  - AST-based code validation logic (`is_code_safe`).
  - Dynamic module loader (`load_model_from_file`).
  - PyTorch trace to GNN-compatible schema translation (`extract_nixtee_graph`).
  - Ollama process synchronization & API communication layers.
  - Interactive chat session handling with tab completion and Rich terminal graphics.
- [nixtee_mcp_client.py](nixtee_mcp_client.py) - External MCP sessions, tool/resource discovery and the Ollama tool-call loop.
- [nixtee_mcp_settings.py](nixtee_mcp_settings.py) - Desktop configuration bridge and connection inspection.

### Adding CLI Commands

Add a new subcommand to the Click group inside [nixtee_cli.py](nixtee_cli.py):

```python
@cli.command()
@click.option('--flag', default=True, help="Description of flag")
def my_command(flag):
    """Help documentation for my new command."""
    click.echo(f"Executed command with flag={flag}")
```

### Customizing the AST Security Engine

The AST filter is a convenience check, not an isolation boundary. MCP model execution uses the Docker sandbox described in [MCP security](MCP_SECURITY.md); do not rely on blacklist changes to safely execute untrusted Python.

You can restrict more functions or modify safety rules in [nixtee_cli.py](nixtee_cli.py). Update the `FORBIDDEN_CALLS` set:

```python
FORBIDDEN_CALLS = {
    'os.system', 'subprocess', 'eval', 'exec', 'open', 
    '__import__', 'compile', 'input', 'shutil.rmtree',
    # Add new blocked operations here:
    'urllib.request', 'socket'
}
```

### Registering Custom MCP Tools

To add tools to the MCP server, register them with the `mcp_server` instance inside the `create_mcp_server()` factory in `nixtee_cli.py`:

```python
@mcp_server.tool()
def get_workspace_info() -> str:
    """Returns directory path info for debugging."""
    return str(os.getcwd())
```

See [bidirectional MCP setup](documentation.md#mcp-connections-for-qwen-and-codex) for Qwen tool calling and connecting Codex to Nixtee.

## MCP security update

MCP model execution now requires an offline Docker sandbox; external tools require approval by default. HTTP servers require authentication, and Codex uses private stdio. Remote connections support OAuth and OS-keychain credentials. See [MCP security and migration](MCP_SECURITY.md) for setup, permissions, budgets and upgrade instructions.

## Local pretrained templates and fine-tuning

Open **Model templates & fine-tuning** to choose among ten on-demand pretrained model links and train on your own labeled text/image CSVs. Weights download only after an explicit action; data and checkpoints remain local. Classification, language modeling and text-to-text tasks include measured validation and resumable epoch checkpoints. See [the fine-tuning guide and CSV examples](examples/fine-tuning/README.md).

### Local runtime measurement and SDSI

`predict` returns scoped accuracy predictions from the server. To measure
forward-pass latency on the current machine, use:

```sh
nixtee measure --model-path ./model.py --input-shape 32,561 --device cpu
```

The command reports p50 and p95 in milliseconds per batch after warmup using a
synthetic zero input. Model loading, input creation and preprocessing are
outside the timed region. Use `--input-dtype int64` for token-ID inputs and
`--device cuda` or `--device mps` to measure an accelerator. The raw samples
and audit manifest are written to `runs/measure-*/` under the project directory.

To try SDSI with the included ASR example:

```sh
cd examples/asr-edge
nixtee nas search --candidates 200
nixtee train-sdsi --candidate <id-from-ranking> --steps 8
nixtee audit <run-id>
```

The SDSI example trains a compact model on synthetic filterbanks. The training
loop duration is measured, WER is a proxy and NAS ranking is heuristic by
default. Existing CSV training remains available through `nixtee train`.
