Autonomous-Agent-local
This agent is like a helpful assistant that works entirely on your computer, without sending any information outside. It can tackle complex tasks by breaking them down into smaller steps and using various tools to achieve the desired outcome. This is useful for businesses or individuals who need to automate tasks like finding information online or organizing files, but want to keep their data private and secure. Unlike other similar tools, it’s built from the ground up, allowing it to fix its own mistakes and adapt to specific project rules. The agent is particularly valuable for those who want a powerful AI solution without relying on external services or worrying about data security.
README
# 🌟 Sunny AI v5.1 — Local Autonomous Agent
> Một AI agent tự chủ chạy hoàn toàn local trên máy tính của bạn.
> Không cloud. Không API key. Không gửi dữ liệu ra ngoài.
---
## Demo thực tế (Tested trên RTX 3050 6GB)
**Self-Healing** — Tự sửa code khi lỗi:
```
🔧 python_exec(print((a + 100))) → [Error] NameError
[SELF_HEAL attempt 1]
🔧 python_exec(a = 0\nprint(a + 100)) → [Output]: 100 ✅
```
**Task Decomposition** — Tự chia task phức tạp:
```
User: "Tìm RTX 3060 trên web rồi lưu vào file result.txt"
→ Subtask 1/2: 🔧 web_search → 🔧 visit_url
→ Subtask 2/2: 🔧 python_exec (ghi file) ✅
```
**Tool Guard** — Block hành vi sai logic:
```
read_file(C:\file.txt) → [TOOL_ERROR]
model muốn web_search("C:\file.txt")
→ ⚠️ Blocked: Đường dẫn file local không tìm được trên web
→ 🔧 scan_folder(.) ✅
```
---
## Giới thiệu
Sunny AI v5.1 là một **autonomous agent** chạy local dựa trên LLM mã nguồn mở. Điểm khác biệt so với wrapper LangChain/AutoGen: toàn bộ planner, memory, sandbox, tool system, self-healer đều tự build từ đầu.
**Hardware tối thiểu:** GPU 6GB VRAM (tested RTX 3050 6GB)
---
## Models
| Nút | Model | Dùng khi |
|-----|-------|---------|
| **[Llama]** | Llama 3.2 3B Instruct (4-bit) | Chat thông thường |
| **[Qwen]** | Qwen 2.5 3B Instruct (4-bit) | Tool calling, Lv4/Lv5 |
| **[8B]** | Hermes 3 8B (4-bit) | Reasoning phức tạp (cần đủ VRAM) |
> Qwen 2.5 3B giỏi JSON/tool calling hơn Llama 3B dù cùng kích thước.
> Điểm khác biệt không phải độ thông minh tổng thể mà là khả năng follow format.
---
## Tính năng
### 🧠 Brain
- **ReAct Loop** — Thought → Action → Observe → Critic → lặp cho đến khi xong
- **Task Decomposition (Lv5)** — Tự chia task thành subtask, mỗi subtask chạy ReAct riêng. Thực chất là simulate multi-agent (planner + worker) trên 1 model 3B
- **Self-Healing** — Khi `python_exec` fail, LLM tự đọc error message và viết lại code (tối đa 2 lần). Không phải lúc nào cũng sửa đúng — tỷ lệ thành công đủ cao để giảm đáng kể số lần can thiệp thủ công
- **Self-Refine** — Draft → Critic → Rewrite
- **Workspace Context** — Đọc `sunny_rules.md` để follow luật riêng của project
- **Auto Chat Template** — Tự nhận diện Llama 3 vs ChatML (Qwen/Hermes) khi switch model
### 📋 Planner
- **Stateful Replan** — Merge alt-plan vào plan chính khi step fail — không mất context
- **Failed History** — Inject lịch sử thất bại vào replan prompt, tránh lặp lỗi cũ
- **Tool Rate Limit** — Mỗi tool tối đa 5 lần/run
- **Tool Output Truncation** — Giới hạn output dài trước khi lưu vào observation
- **Goal Completion Check** — Dừng sớm khi goal đã đạt, không chạy hết plan
- **State Summary** — Compress observations sau mỗi 5 steps để tránh context drift
### 🛡️ Tool Guard (System Rules)
LLM không có khái niệm "an toàn" — nó chỉ tối ưu để hoàn thành yêu cầu, kể cả khi yêu cầu đó là nguy hiểm. Tool Guard là layer system rule độc lập với model:
| Rule | Mô tả |
|------|-------|
| R1 | `web_search` với đường dẫn local → block ngay |
| R2 | Query web quá ngắn → block |
| R3 | `scan_folder`/`read_file` với URL → block, gợi ý `visit_url` |
| R4 | `visit_url` với path local → block, gợi ý `read_file` |
| R5 | `python_exec` khi task không liên quan code/file → block |
| R6 | `shell_run` với pattern nguy hiểm → block |
| R7 | `phone_control` với lệnh không hợp lệ → block |
### 🔧 Self Healer (System-Level)
Khác với prompt-based retry — self_healer classify lỗi rồi sửa plan mà không hỏi model:
| Lỗi | Action |
|-----|--------|
| `FILE_NOT_FOUND` | `scan_folder` → `shell_run find` tìm đúng path |
| `PERMISSION_DENIED` | Skip, thông báo user |
| `TIMEOUT` (web) | Retry với query ngắn hơn |
| `SANDBOX_BLOCK` | Skip, không retry |
### 🔧 Tools (10 tools)
| Tool | Chức năng |
|------|-----------|
| `web_search` | Tìm kiếm DuckDuckGo |
| `visit_url` | Đọc trang web (stream, giới hạn 1MB) |
| `read_file` | Đọc file (PDF/DOCX/XLSX/TXT) |
| `scan_folder` | Quét file trong thư mục |
| `scan_temp` | Quét file rác trong temp |
| `delete_temp` | Xóa file rác |
| `python_exec` | Chạy Python (subprocess, check_code sandbox) |
| `shell_run` | Chạy shell command (whitelist + default deny) |
| `read_diary` | Đọc nhật ký cá nhân |
| `phone_control` | Điều khiển Android qua ADB |
### 🧩 Memory
- **VectorMemory (FAISS)** — Hybrid scoring: Similarity×0.7 + Importance×0.2 + Recency×0.1
- **SemanticCache** — Cache câu hỏi tương tự, skip inference (threshold 0.92)
- **ToolErrorMemory** — Nhớ tool fail để tránh lặp lỗi
- **DynamicToolRegistry** — Đăng ký tool mới với AST check, persist qua session
- **ConversationManager** — Lịch sử hội thoại (tối đa 6 turns)
### 🛡️ Bảo mật
- **Sandbox Python** — `check_code()` block `import os/sys/subprocess`, `eval`, `exec`, `__import__`, `getattr`, `__class__`... trước khi execute
- **subprocess isolation** — `python_exec` chạy qua subprocess với `cwd=tempdir`, fix WinError 6 trên Windows + FastAPI
- **AST Check** — Kiểm tra code trước khi đăng ký dynamic tool
- **Shell Whitelist** — Default deny, block chaining (`&&`, `||`, `;`)
- **Path Traversal** — `commonpath + os.sep`, block symlink, `find` chỉ cho phép `find .`
- **SSRF Protection** — Block IP nội bộ, DNS rebinding check qua `getaddrinfo`
- **Observation Guard** — Tool output là "untrusted data" trong prompt
---
## Cấu trúc thư mục
```
SunnyV5/
├── core/
│ ├── brain.py # LLM inference, ReAct loop, Self-Healing
│ ├── planner.py # Plan execution, tool dispatch, replan
│ ├── memory.py # VectorMemory, SemanticCache, ToolErrorMemory
│ ├── sandbox.py # Path/code/shell/URL security
│ ├── tool_guard.py # System rules — block sai tool độc lập với model
│ ├── self_healer.py # Classify lỗi + sửa plan không qua model
│ ├── config.py # Cấu hình toàn hệ thống
│ ├── logger.py # Singleton logger thread-safe
│ └── embedding.py # Singleton SentenceTransformer
├── tools/
│ ├── executor.py # python_exec (subprocess), shell_run
│ ├── web.py # web_search, visit_url
│ ├── reader.py # read_file
│ ├── scanner.py # scan_folder, scan_temp, delete_temp
│ ├── phone.py # phone_control (ADB)
│ └── voice.py # voice input/output
├── sunny_web.py # FastAPI server + WebSocket UI
├── sunny_rules.md # (tùy chọn) Luật riêng cho project
├── test_sunny.py # Integration test suite
└── run.bat # Launcher Windows
```
---
## Cài đặt
```bash
# PyTorch với CUDA 12.1
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121
# Model & inference
pip install transformers accelerate bitsandbytes unsloth
# Memory
pip install faiss-gpu sentence-transformers
# Web server
pip install fastapi uvicorn websockets aiofiles
# Tools
pip install requests beautifulsoup4 duckduckgo-search psutil
```
---
## Chạy
```bash
# Windows
run.bat
# Hoặc trực tiếp
python -m uvicorn sunny_web:app --host 0.0.0.0 --port 7860
```
Mở trình duyệt: `http://localhost:7860`
---
## Cấu hình
Chỉnh `core/config.py`:
```python
MODEL_NAME = "unsloth/Qwen2.5-3B-Instruct-bnb-4bit"
MAX_NEW_TOKENS = 512
PLAN_MAX_STEPS = 5
TOOL_RATE_LIMIT = 5
MAX_TOOL_OUTPUT = 1500
ENABLE_LV5 = True
```
### Workspace Rules
Tạo `sunny_rules.md` trong thư mục project:
```markdown
- Code phải có type hint
- Dùng multiprocessing thay threading cho tác vụ nặng
- Biến viết snake_case
- Comment bằng tiếng Việt
```
---
## Level
| Nút | Chế độ | Phù hợp |
|-----|--------|---------|
| **[🔄 Lv4]** | ReAct Loop | Task đơn giản, câu hỏi nhanh |
| **[⚡ Lv5]** | Task Decomposition + Multi-ReAct | Task phức tạp, multi-step |
> Với model 3B, Lv4 ổn định hơn Lv5. Lv5 tốt nhất khi dùng với [8B].
---
## Kiến trúc
```
User Input
↓
Prompt Injection Filter
↓
Semantic Cache ──hit──→ Trả lời ngay
↓ miss
Memory Search (FAISS hybrid scoring)
↓
Brain / Planner
↓
Tool Guard (System Rules) → Block nếu sai logic
↓
Tool Execute (subprocess sandbox)
↓
Self
[truncated…]PUBLIC HISTORY
IDENTITY
Identity inferred from code signals. No PROVENANCE.yml found.
Is this yours? Claim it →METADATA
README BADGE
Add to your README:
