Metadata-Version: 2.5
Name: cokgine
Version: 0.1.2
Summary: Standalone Ollama-like LLM engine on Apple Silicon (MLX) with built-in genetic AI
Author: Kridho Cokro
License-Expression: LicenseRef-Proprietary
Keywords: apple-silicon,genetic-algorithm,llm,mlx,ollama
Requires-Python: <3.13,>=3.12
Requires-Dist: fastapi>=0.115
Requires-Dist: huggingface-hub>=0.33
Requires-Dist: mlx-lm<0.32,>=0.31
Requires-Dist: mlx>=0.26
Requires-Dist: rich>=13.9
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn>=0.32
Description-Content-Type: text/markdown

# cokgine

Engine AI mandiri ala Ollama untuk Apple Silicon — load model LLM dari HuggingFace,
jalankan in-process via [MLX](https://github.com/ml-explore/mlx), dan evolusi prompt
dengan algoritma genetika bawaan. Tanpa Ollama, tanpa llama.cpp server, tanpa perantara.

```
┌─────────────┐   ┌──────────────────────────────────────────┐
│ CLI / REST  │──▶│ EngineService ──▶ MlxBackend (mlx-lm)     │
│ Open WebUI  │   │      │                                    │
│ Genetics    │───┘      └──▶ FakeBackend (--fake, tanpa GPU) │
└─────────────┘   └──────────────────────────────────────────┘
```

- **Cepat di Apple Silicon** — MLX memakai GPU Metal langsung; Llama-3.2-1B berjalan ~50 tok/dtk di M4 Max.
- **REST kompatibel Ollama** — aplikasi eksternal tinggal ganti base URL ke `http://localhost:11435`.
- **Genetic AI bawaan** — algoritma genetika yang memakai inferensi engine sendiri sebagai mutator dan penilai fitness.

## Instalasi

Butuh macOS Apple Silicon dan [uv](https://docs.astral.sh/uv/).

Dari PyPI (pengguna):

```bash
uv tool install cokgine
```

Dari source (pengembang — lihat [DEVELOPING.md](DEVELOPING.md)):

```bash
uv sync
uv run cokgine --help
```

Model tersimpan di `~/.cokgine/models/` (ubah via `COKGINE_HOME`).

Ketik `cokgine` tanpa perintah untuk melihat status server, model yang
ter-install, dan daftar perintah.

## Quickstart

```bash
# ambil model uji (~0.7 GB)
cokgine pull llama3.2-1b

# tanya langsung dari CLI
cokgine generate llama3.2-1b "What is the capital of France?"

# REPL interaktif
cokgine run llama3.2-1b

# jalankan server REST (port 11435)
cokgine serve
```

Model 7–8B (butuh ~5 GB RAM untuk 4-bit):

```bash
cokgine pull llama3.1-8b        # mlx-community/Meta-Llama-3.1-8B-Instruct-4bit
cokgine pull qwen2.5-7b
cokgine pull qwen3-8b
```

Model coding 30B MoE (17 GB, cocok untuk agentic coding via Cline; set
`COKGINE_MAX_LOADED=1` di RAM 36 GB):

```bash
cokgine pull qwen3-coder-30b    # mlx-community/Qwen3-Coder-30B-A3B-Instruct-4bit
```

## Model apa pun dari HuggingFace

Tidak ada daftar model yang dikunci di kode. Semua repo `mlx-community/...`
(atau repo MLX apa pun) bisa ditarik langsung dengan repo id-nya:

```bash
cokgine pull mlx-community/Llama-3.1-8B-Instruct-4bit
```

Alias bawaan hanyalah kenyamanan: `llama3.2-1b`, `llama3.1-8b`, `qwen2.5-7b`,
`qwen3-8b`, `qwen3-coder-30b`. Buat alias pribadi sendiri — tersimpan di
`~/.cokgine/aliases.json`, tanpa mengubah kode:

```bash
cokgine alias add deepseek mlx-community/DeepSeek-R1-Distill-Qwen-7B-4bit
cokgine pull deepseek
cokgine alias list          # alias -> repo id, plus status sudah/belum ditarik
cokgine alias rm deepseek   # hapus alias; file model (jika ada) tetap utuh
```

`cokgine pull <nama> --alias <nama-baru>` juga menyimpan alias saat selesai
mengunduh.

## REST API (kompatibel Ollama)

Semua endpoint streaming memakai NDJSON — satu objek JSON per baris
(`Content-Type: application/x-ndjson`), sama seperti Ollama. Set `stream: false`
untuk satu respons buffered.

| Endpoint | Fungsi |
|---|---|
| `GET /` | heartbeat |
| `GET /api/version` | versi server |
| `POST /api/generate` | generate satu prompt |
| `POST /api/chat` | chat multi-turn dengan chat template |
| `GET /api/tags` | daftar model lokal |
| `POST /api/pull` | unduh model dari HuggingFace |
| `POST /api/show` | detail model |
| `DELETE /api/delete` | hapus model lokal |

```bash
curl --json '{"model":"llama3.2-1b","prompt":"Say OK","stream":false}' \
     http://localhost:11435/api/generate

curl -sN --json '{"model":"llama3.2-1b","messages":[{"role":"user","content":"Say OK"}]}' \
     http://localhost:11435/api/chat
```

Open WebUI: tambahkan koneksi OpenAI/Ollama ke `http://localhost:11435` — CORS terbuka.

### Options yang dikenali

`options` map Ollama diterjemahkan ke sampler MLX:

| Ollama | cokgine |
|---|---|
| `temperature`, `top_p`, `top_k` | sampler MLX |
| `repeat_penalty` | logits processor repetition penalty |
| `num_predict` | `max_tokens` (default 512; -1 → 8192) |
| `num_ctx` | `max_kv_size` (default 8192; **per-request** — tidak memicu reload) |
| `stop` | pemotongan stream sisi klien |
| `seed` | `mx.random.seed` |

Opsi lain diabaikan.

## Genetic AI

`cokgine evolve` menjalankan algoritma genetika di atas inferensi engine sendiri:
setiap individu adalah **prompt-genome** (system prompt + instruction template
dengan placeholder `{input}`), dievolusi lewat seleksi tournament, crossover,
mutasi string deterministik, dan mutasi berbantuan LLM (temperature 0.9).

```bash
cokgine evolve --config examples/evolve_capitals.json
cokgine evolve --task "answer in rhymes" --model llama3.2-1b
cokgine evolve --resume <RUN_ID>          # lanjut dari checkpoint
```

Contoh config:

```json
{
  "task": "answer world capital-city questions accurately and concisely",
  "samples": [
    { "input": "What is the capital of France?", "expected": "Paris" }
  ],
  "target_model": "llama3.2-1b",
  "fitness": { "strategy": "contains" },
  "population": 6,
  "generations": 5,
  "llm_mutation_rate": 0.3
}
```

Strategi fitness:

- `contains` / `exact` / `regex` — deterministik terhadap `expected`.
- `llm_judge` — engine menilai jawaban kandidatnya sendiri (rubrik bisa dikustom via `"rubric"`).

Checkpoint atomik per generasi tersimpan di `~/.cokgine/evolve/<run_id>/state.json`;
run bisa dilanjutkan dengan `--resume`. Seed RNG dikonfigurasi (`"seed": 42`) agar
run reproducible.

Seam arsitektur untuk masa depan: `WeightGenome` (evolusi bobot/LoRA) — parameter
`adapter` sudah mengalir dari options → cache key → `mlx_lm.load(adapter_path=...)`,
jadi evolusi adapter bisa ditambahkan tanpa menyentuh core.

## Mode tanpa GPU / demo

Seluruh stack (CLI, REST, evolve) bisa dijalankan tanpa model dan tanpa jaringan:

```bash
cokgine serve --fake
cokgine evolve --fake --config examples/evolve_capitals.json
# atau: export COKGINE_FAKE=1
```

## Memori (M-series 36 GB)

- LRU cache memuat maksimal 2 model sekaligus (`COKGINE_MAX_LOADED`); evict memanggil `gc.collect()` + `mx.clear_cache()`.
- `num_ctx` besar menaikkan pemakaian KV-cache per request — 8192 aman untuk model 8B-4bit.
- Untuk headroom lebih saat load 2 model 8B: `sudo sysctl iogpu.wired_limit_mb=28000`.

Lisensi: proprietary — semua hak dilindungi. Penggunaan kembali atau redistribusi
source code tidak diizinkan tanpa izin tertulis dari pemilik.
