Metadata-Version: 2.4
Name: phx-ashborn
Version: 2.0.0
Summary: Advanced AI Infrastructure SDK for Agentic Applications
Author: blackeagle686
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: requests>=2.28.0
Requires-Dist: openai>=1.0.0
Requires-Dist: pydantic
Requires-Dist: httpx>=0.24.0
Requires-Dist: numpy
Provides-Extra: agent
Requires-Dist: pydantic; extra == "agent"
Requires-Dist: redis>=4.5.0; extra == "agent"
Requires-Dist: celery>=5.3.0; extra == "agent"
Requires-Dist: duckduckgo-search; extra == "agent"
Requires-Dist: chromadb>=0.4.0; extra == "agent"
Requires-Dist: qdrant-client>=1.6.0; extra == "agent"
Provides-Extra: chatbot
Requires-Dist: markdown>=3.4.0; extra == "chatbot"
Requires-Dist: beautifulsoup4>=4.11.0; extra == "chatbot"
Requires-Dist: pypdf>=3.10.0; extra == "chatbot"
Requires-Dist: python-docx>=0.8.11; extra == "chatbot"
Requires-Dist: sqlalchemy>=2.0.0; extra == "chatbot"
Requires-Dist: django>=5.0.0; extra == "chatbot"
Requires-Dist: pandas; extra == "chatbot"
Requires-Dist: openpyxl; extra == "chatbot"
Requires-Dist: Pillow; extra == "chatbot"
Requires-Dist: fastapi; extra == "chatbot"
Requires-Dist: uvicorn; extra == "chatbot"
Requires-Dist: python-multipart; extra == "chatbot"
Provides-Extra: sensorium
Requires-Dist: pyserial>=3.5; extra == "sensorium"
Requires-Dist: paho-mqtt>=1.6.0; extra == "sensorium"
Requires-Dist: psutil; extra == "sensorium"
Provides-Extra: local
Requires-Dist: torch; extra == "local"
Requires-Dist: transformers; extra == "local"
Requires-Dist: accelerate; extra == "local"
Requires-Dist: bitsandbytes; extra == "local"
Requires-Dist: sentence-transformers>=2.2.0; extra == "local"
Provides-Extra: audio
Requires-Dist: gTTS; extra == "audio"
Requires-Dist: SpeechRecognition; extra == "audio"
Requires-Dist: pydub; extra == "audio"
Provides-Extra: vector
Requires-Dist: chromadb>=0.4.0; extra == "vector"
Requires-Dist: qdrant-client>=1.6.0; extra == "vector"
Provides-Extra: rag
Requires-Dist: chromadb>=0.4.0; extra == "rag"
Requires-Dist: sentence-transformers>=2.2.0; extra == "rag"
Requires-Dist: pypdf>=3.10.0; extra == "rag"
Requires-Dist: python-docx>=0.8.11; extra == "rag"
Requires-Dist: beautifulsoup4>=4.11.0; extra == "rag"
Requires-Dist: sqlalchemy>=2.0.0; extra == "rag"
Requires-Dist: httpx>=0.24.0; extra == "rag"
Requires-Dist: google-api-python-client>=2.0.0; extra == "rag"
Requires-Dist: google-auth-oauthlib>=1.0.0; extra == "rag"
Requires-Dist: redis>=4.5.0; extra == "rag"
Provides-Extra: brain
Requires-Dist: maturin>=1.0.0; extra == "brain"
Provides-Extra: ml
Requires-Dist: scikit-learn>=1.3.0; extra == "ml"
Requires-Dist: scipy>=1.10.0; extra == "ml"
Requires-Dist: joblib>=1.3.0; extra == "ml"
Requires-Dist: lightgbm>=4.0.0; extra == "ml"
Requires-Dist: onnxruntime>=1.16.0; extra == "ml"
Provides-Extra: cv
Provides-Extra: cv-gguf
Requires-Dist: llama-cpp-python>=0.2.85; extra == "cv-gguf"
Provides-Extra: full
Requires-Dist: pydantic; extra == "full"
Requires-Dist: redis>=4.5.0; extra == "full"
Requires-Dist: celery>=5.3.0; extra == "full"
Requires-Dist: duckduckgo-search; extra == "full"
Requires-Dist: chromadb>=0.4.0; extra == "full"
Requires-Dist: qdrant-client>=1.6.0; extra == "full"
Requires-Dist: markdown>=3.4.0; extra == "full"
Requires-Dist: beautifulsoup4>=4.11.0; extra == "full"
Requires-Dist: pypdf>=3.10.0; extra == "full"
Requires-Dist: python-docx>=0.8.11; extra == "full"
Requires-Dist: sqlalchemy>=2.0.0; extra == "full"
Requires-Dist: django>=5.0.0; extra == "full"
Requires-Dist: pandas; extra == "full"
Requires-Dist: openpyxl; extra == "full"
Requires-Dist: Pillow; extra == "full"
Requires-Dist: fastapi; extra == "full"
Requires-Dist: uvicorn; extra == "full"
Requires-Dist: python-multipart; extra == "full"
Requires-Dist: pyserial>=3.5; extra == "full"
Requires-Dist: paho-mqtt>=1.6.0; extra == "full"
Requires-Dist: psutil; extra == "full"
Requires-Dist: torch; extra == "full"
Requires-Dist: transformers; extra == "full"
Requires-Dist: accelerate; extra == "full"
Requires-Dist: bitsandbytes; extra == "full"
Requires-Dist: sentence-transformers>=2.2.0; extra == "full"
Requires-Dist: gTTS; extra == "full"
Requires-Dist: SpeechRecognition; extra == "full"
Requires-Dist: pydub; extra == "full"
Requires-Dist: httpx>=0.24.0; extra == "full"
Requires-Dist: google-api-python-client>=2.0.0; extra == "full"
Requires-Dist: google-auth-oauthlib>=1.0.0; extra == "full"
Requires-Dist: maturin>=1.0.0; extra == "full"
Dynamic: author
Dynamic: requires-python

# Phoenix AI

<p align="center">
  <img src="https://raw.githubusercontent.com/blackeagle686/phoenix-ai/master/docs/statics/images/phx-light-circle.png" alt="Phoenix AI Logo" width="500">
</p>

<p align="center">
  <strong>Advanced AI Infrastructure SDK for Autonomous Agents, Chatbots, and Production Backend Services.</strong>
</p>

<p align="center">
  <img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python 3.10+">
  <img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT">
  <img src="https://img.shields.io/badge/framework-FastAPI%20%7C%20Django-red.svg" alt="Frameworks">
  <img src="https://img.shields.io/badge/AI-Agents%20%7C%20RAG-orange.svg" alt="AI SDK">
</p>

---

Whether you are building with FastAPI, Django, or a custom event-driven service, **Phoenix AI** eliminates repetitive backend setup and provides a highly-optimized orchestration layer for large language models, computer vision, and physical hardware.

## Why Phoenix AI?

- **Autonomous Agents**: Single-line creation of thinking, planning, and executing AI agents.
- **Micron CV Agent (`CVAgent`)**: Ultra-low-RAM edge/phone agent built to run side-by-side with Computer Vision systems (YOLO, OpenCV, ONNX) using strictly `<= 1B` MoE models, user-modifiable CV tools, alerts, local files, and local SQLite databases.
- **High-Level ChatBot**: Turnkey conversational AI with native RAG, Vision, and Memory.
- **"Everything as a Service"**: A unified Dependency Injection container handles Vector DBs, Redis caching, and LLMs seamlessly.
- **Fail-Loud & Recover**: Auto-fallbacks from Local (Ollama/Transformers) to Cloud (OpenAI) to prevent system crashes.
- **Native PyTorch & 4-bit Quantization**: Run local models directly on your GPU without external servers, automatically optimized for low-VRAM machines.
- **Sensorium (Embodied AI)**: Plug your AI directly into the physical world via IoT, MQTT, and Arduino plugins.

---

## 📦 Installation

Choose the installation tier that matches your project needs:

```bash
# Micron CV Agent ONLY — Standalone Zero-Dependency Package (Recommended for Phone CPU / Low RAM)
# Download Size: ~25 KB | 0 Dependencies (pure Python stdlib, < 2 MB RAM)
pip install "git+https://github.com/blackeagle686/phoenix-ai.git#subdirectory=phoenix/framework/cv_agent"

# Micron CV Agent via phx-ashborn lightweight extra (skips torch, chromadb, fastapi, rag, ml)
pip install "phx-ashborn[cv]"          # or "phx-ashborn[cv-gguf]" for quantized <=1B MoE GGUF CPU inference

# Core Backend Framework
# Download Size: ~5.2 MB (Verified)
# Installed Size on Disk: ~15 MB
pip install phx-ashborn

# Core + ChatBot & Conversation Memory
# Download Size: ~35 MB (Estimated)
# Installed Size on Disk: ~90 MB
pip install "phx-ashborn[chatbot]"

# Core + Advanced RAG Frameworks (Qdrant, ChromaDB, Web/API Ingestion)
# Download Size: ~45 MB
# Installed Size on Disk: ~110 MB
pip install "phx-ashborn[rag]"

# Core + Autonomous Agents & Planners
# Download Size: ~107 MB (Verified)
# Installed Size on Disk: ~200 MB
pip install "phx-ashborn[agent]"

# Full Suite (Everything including Local AI Inference)
# ⚠️ Download Size: ~2.2 GB - 2.5 GB (Estimated)
# ⚠️ Installed Size on Disk: ~5.5 GB - 6.0 GB
pip install "phx-ashborn[full]"
```

> [!NOTE]
> If you're running locally, copy the `.env.example` to `.env` and configure your API keys (e.g., `OPENAI_API_KEY`). For full system deployment (including Redis setup), use the provided `./install.sh` or `install.bat` scripts.

---

##  Quickstarts & Core Features

### 1.  Autonomous Agents
The Phoenix Agent is a high-speed cognitive engine capable of understanding complex problems, scanning codebases, planning multi-step solutions, and executing parallel tools.

```python
import asyncio
from phoenix import Agent

async def agent_demo():
    # Initialize a high-speed Agent with default tools and memory
    agent = Agent()
    
    # Or inject custom tools instantly!
    from phoenix.framework.agent import tool
    
    @tool(name="custom_math", description="Calculates squares. Input: 'number' (int)")
    def math_tool(number: int):
        return f"The square is {number ** 2}"
        
    agent.register_tool(math_tool)
    
    # Run a complex engineering task
    # The agent will: Think -> Analyze -> Plan -> Execute Tools -> Reflect
    result = await agent.run(
        "Find the redundant code in the memory module and optimize it.", 
        mode="plan"
    )
    
    print(f"Agent Execution Report: {result}")

asyncio.run(agent_demo())
```

> [!TIP]
> Phoenix Agents feature **Intelligent Auto-Routing**. By default (`mode="auto"`), the agent analyzes your prompt to decide whether to give a blazing-fast direct answer or spin up its heavy planning loop for complex operations!

### 2. Multi-Modal ChatBot
Need a powerful conversational interface without the complexity of building agent loops? The `ChatBot` builder abstracts away RAG, Vision (VLM), and Session Memory into a fluent API.

```python
from phoenix import ChatBot
import asyncio

async def chatbot_demo():
    # Build a complete AI ChatBot in one line
    bot = (ChatBot(local=False, vlm=True)
           .with_rag(["./docs", "./src"])       # Ingest folders automatically
           .with_memory()                       # Enable conversation history
           .with_security(mode="strict")        # Prompt-injection protection
           .with_system_prompt("You are a helpful Python expert.")
           .build())

    # Multi-modal interaction out of the box
    response = await bot.chat(
        prompt="Explain this architecture diagram.", 
        image_path="architecture.png"
    )
    print(response)

asyncio.run(chatbot_demo())
```

### 3. Advanced RAG Frameworks
The new object-oriented RAG framework provides scalable `RAG`, `CAG` (Cache-Augmented Generation), `AgenticRAG`, and `MultiModalRAG` systems out of the box with unified multi-source ingestion.

```python
import asyncio
from phoenix.framework.rag import RAG, AgenticRAG

async def rag_demo():
    # Initialize standard RAG (ChromaDB is default)
    rag = RAG()

    # Unified Multi-Source Ingestion
    await rag.ingest_multi([
        {"type": "folder", "path": "./my_project"},
        {"type": "github", "repo_url": "https://github.com/blackeagle686/phoenix-ai.git"},
        {"type": "url", "url": "https://example.com/api-docs"},
        {"type": "sql", "connection_string": "sqlite:///data.db", "table": "docs"}
    ])

    # Query with automatic context compression and MMR reranking
    answer = await rag.query("How do I extend the caching layer?")
    print(answer)
    
    # Or upgrade to AgenticRAG to let the AI verify its own answers and rewrite poor queries!
    # agentic = AgenticRAG(max_retries=3, verify_answer=True)

asyncio.run(rag_demo())
```

### 4. Micron CV Agent (Phone CPU / Edge Computer Vision)
Built to run side-by-side with Computer Vision detectors (YOLO, OpenCV, ONNX, TFLite) on **phone CPUs and very low-RAM devices**. Uses zero heavy startup imports, bounded sliding-window memory, strictly **`<= 1B` MoE models only** (e.g. `ibm-granite/granite-3.1-1b-a400m-instruct`), user-modifiable CV tools, alerts with cooldown, local file read/write, and local SQLite record lookups.

```python
from phoenix.framework.cv_agent import CVAgent, CVAgentConfig, CVEvent, Detection

# Strictly enforces MoE models <= 1B (or model=None for <2 MB RAM deterministic mode)
agent = CVAgent(
    model="ibm-granite/granite-3.1-1b-a400m-instruct",  # alias: "granite-1b-moe" (400M active)
    config=CVAgentConfig(workspace_root="./cv_edge", auto_log_file="logs/decisions.jsonl"),
    db_path="./cv_edge/security.db",
    on_alert=lambda a: print(f"[ALERT][{a['severity']}] {a['message']}"),
)

# Users can freely add or modify tools for CV events
@agent.tool(name="lock_gate", description="Engage physical barrier lock on intrusion.")
def lock_gate(zone: str):
    return {"locked": zone}

# Connect local SQLite records to enrich every CV event context
agent.set_db_enricher(
    lambda ev, db: db.read_records("plates", where={"plate": ev.metadata["plate"]}, limit=3)["records"]
    if ev.metadata.get("plate") else []
)

# Handle events from YOLO (`CVEvent.from_yolo`), OpenCV (`CVEvent.from_boxes`), or dicts
event = CVEvent(
    event_type="vehicle_plate_detected",
    camera_id="cam_gate_1",
    zone="north_gate",
    detections=[Detection(label="car", confidence=0.95, track_id="v_7")],
    metadata={"plate": "BAD-999"},
)
res = agent.handle_event_sync(event)  # or `await agent.handle_event(event)` in async/notebooks
print(res.decision_group.to_dict())
```

> [!TIP]
> See the full **[Micron CV Agent Documentation](docs/micron_cv/README.md)**, **[Supported `<= 1B` MoE Model IDs](docs/micron_cv/01_supported_models.md)**, and **[Real-World CV Scenarios](docs/micron_cv/03_real_world_scenarios.md)**.

---

## 🏗️ Advanced Architecture

### Multi-Agent Orchestration
Define dynamic teams of specialized agents (e.g., Coder, Reviewer, Security Expert) and coordinate them through parallel broadcasting or sequenced pipelines.

```python
from phoenix.framework import MultiAgentManager, MultiAgentConfig, AgentConfig

config = MultiAgentConfig(
    team_name="Engineering Task Force",
    agents=[
        AgentConfig(name="Giyu_Coder", profile="profiles/coder.json"),
        AgentConfig(name="Shinobu_Reviewer", profile="profiles/reviewer.json")
    ]
)

manager = MultiAgentManager(config)
report = await manager.run_pipeline(
    prompt="Implement a thread-safe cache system",
    agent_sequence=["Giyu_Coder", "Shinobu_Reviewer"]
)
```

### 🦾 Sensorium (Hardware SDK)
Connect your Phoenix Agents to the physical world using an async, zero-latency plugin architecture. Build Smart Home routines, Robotics controllers, or Drone surveillance systems!

```python
from phoenix.framework.sensorium.core.manager import DeviceManager
from phoenix.framework.sensorium.plugins.mock_plugin import MockSensorPlugin
from phoenix.framework.agent import tool

manager = DeviceManager()
await manager.add_device("living_room_temp", MockSensorPlugin())

@tool(name="get_temperature", description="Reads current room temp.")
async def read_temp():
    return await manager.get_device("living_room_temp").read()
```

---

## ⚠️ Local Inference Requirements

If you run Phoenix using **Local LLMs/VLMs** (via Ollama or native Transformers), ensure your machine meets the following specifications to prevent system instability:

- **Full Local Agents / VLMs**: 8GB RAM minimum (16GB+ recommended), 4GB+ VRAM for Vision/VLM models, 10GB+ disk space.
- **Micron CV Agent (`phoenix.framework.cv_agent`)**: Designed for **Phone CPUs & Low-RAM Edge devices** — core footprint is `< 2 MB` RAM (stdlib only, `model=None`), or `~220–780 MB` RAM when running quantized `<= 1B` MoE GGUF models (`ibm-granite/granite-3.1-1b-a400m-instruct`, `micro-moe-500m-a150m`, `micro-moe-300m-a100m`). See [Supported Models](docs/micron_cv/01_supported_models.md).

> [!WARNING]
> High-resource models may cause system crashes on CPU-only devices. The SDK prioritizes stability and will pause to prompt for user confirmation in the terminal before booting large local providers.

---

##  Comprehensive Documentation

Ready to dive deeper? Explore our dedicated guides to master the Phoenix ecosystem:

###  Core Architecture
- **[Main Framework Guide](docs/GUIDE.md)** ([Arabic Version](docs/GUIDE.ar.md))
###  Data & Retrieval
- **[Advanced RAG Frameworks (CAG, Agentic, MultiModal)](docs/rag_framework.md)**
- **[Data Pipelines & Legacy RAG](docs/PIPELINES.md)** ([Arabic Version](docs/PIPELINES.ar.md))
- **[Model Training & Finetuning](docs/TRAINING.md)** ([Arabic Version](docs/TRAINING.ar.md))

###  Autonomous Agents
- **[Agent Framework Architecture](docs/AGENT_GUIDE.md)**
- **[Micron CV Agent (Edge/Phone `<= 1B` MoE)](docs/micron_cv/README.md)**
  - **[Supported `<= 1B` MoE Model IDs](docs/micron_cv/01_supported_models.md)**
  - **[Tools, Alerts, Local Files & SQLite DB](docs/micron_cv/02_tools_database_and_files.md)**
  - **[Real-World CV Scenarios & Code Recipes](docs/micron_cv/03_real_world_scenarios.md)**
- **[Multi-Agent Teams](docs/framework/multi_agent.md)**
- **[The Phoenix Tool Bank](docs/tool_bank_usage.md)**
- **[Custom Specialized Agents](docs/different_scenarios_usage.md)**

###  Integrations & Extensions
- **[Django Integration](docs/DJANGO_INTEGRATION.md)**
- **[FastAPI / Backend Integration](docs/API_INTEGRATION.md)**
- **[GUI App Integration](docs/GUI_INTEGRATION.md)**
- **[Sensorium Embodied AI (Hardware)](docs/sensorium.md)**

---

## ⚡ BrainMemory Core (Rust Backend)

<p align="center">
  <a href="phoenix/brain_memory/README.md">
    <img src="https://raw.githubusercontent.com/blackeagle686/phoenix-ai/master/docs/statics/images/brain_memory_cover.png" alt="Brain Memory Core" width="800">
  </a>
</p>

Phoenix AI ships with an ultra-fast, lock-free memory engine written entirely in Rust, accessible seamlessly from Python. It features a custom-built, embedded Hierarchical Navigable Small World (HNSW) Vector Database for sub-millisecond multi-modal context retrieval.

### Performance Benchmarks

#### Methodology
*All benchmarks were executed using `cargo bench` in release mode. Each benchmark was warmed up before measurement and repeated multiple times by Criterion to reduce statistical noise. Reported values are the benchmark mean.*

**Hardware Specifications & Parameters:**
- **CPU:** Intel Core i5-1135G7
- **RAM:** 12 GB
- **OS:** Ubuntu 24.04 (Linux)
- **Rust Version:** Stable (1.80+)
- **Embedding Size:** 384 dimensions
- **HNSW Configurations:** M = 16, ef_construction = 100, ef_search = 50

#### Results

- **Neural Bus (Event Ingestion):** `~4.39 ms` per event spike.
  - *What we benchmarked:* Pushing a memory spike through a lock-free `crossbeam` channel and actively inserting a 384-dimensional embedding directly into the HNSW graph collection.
- **Fractal Compressor:** `~2.46 ms` per 1,000 events.
  - *What we benchmarked:* Scanning an array of 1,000 artificially aged memory events, calculating their Exponential Time-Decay coefficients (halflife factor = 0.5), and applying hierarchical compression to prevent memory bloat.
- **Retrieval Pipeline Overhead:** `~1.01 µs` (microseconds).
  - *What we benchmarked:* Utilizing a `tokio` async runtime to safely acquire read-locks on the memory core, querying 3 distinct vector collections simultaneously, and compiling the result. *(Note: This `1.01 µs` metric specifically captures the pipeline's async lock acquisition and traversal overhead on empty/cold collections, proving zero systemic bottleneck before the raw HNSW traversal phase).*
  - **The Output (`WorkingMemory`):** A synthesis of *(Top Semantic Events + Recent Episodic Sequences + Relevant Knowledge Nodes)* passed directly to the LLM.
