File size: 9,785 Bytes
38b4eff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# neuralai_engine.py - NeuralAI Engine v2.0
# Local model + Tools (terminal, code, images) + Streaming

import asyncio
import torch
from typing import AsyncGenerator, Dict, Any, List, Tuple
import aiohttp
import asyncio.subprocess as asp
import os
import sys
from pathlib import Path
import json
import time
import subprocess

# CPU optimization
torch.set_num_threads(4)

# Import tools
PROJECT_ROOT = str(Path(__file__).resolve().parent.parent.parent)
if PROJECT_ROOT not in sys.path:
    sys.path.append(PROJECT_ROOT)

try:
    from tools.code_sandbox import CodeSandbox
    from tools.file_manager import FileManager
    from tools.web_fetcher import WebFetcher
    from tools.db_connector import DatabaseConnector
    from tools.git_assistant import GitAssistant
    
    code_sandbox = CodeSandbox()
    file_manager = FileManager()
    web_fetcher = WebFetcher()
    db_connector = DatabaseConnector()
    git_assistant = GitAssistant()
except ImportError as e:
    print(f"[NeuralAI Engine] Import Error: {e}")
    code_sandbox = None
    file_manager = None
    web_fetcher = None
    db_connector = None
    git_assistant = None

# Uplink ports
UPLINK_BASE = "http://localhost"
DIALOG_PORT = 7101
DATA_PORT = 7102
OPS_PORT = 7103
WORLD_PORT = 7104

# Model globals
model = None
tokenizer = None
model_error = None


def load_local_model():
    global model, tokenizer, model_error
    if model is not None or model_error:
        return
    try:
        from transformers import AutoModelForCausalLM, AutoTokenizer
        from peft import PeftModel
        
        base_model = "HuggingFaceTB/SmolLM2-360M-Instruct"
        adapter_path = Path(__file__).resolve().parent.parent.parent / "checkpoints" / "v2_model"
        
        tokenizer = AutoTokenizer.from_pretrained(base_model)
        tokenizer.pad_token = tokenizer.eos_token
        
        base = AutoModelForCausalLM.from_pretrained(
            base_model, torch_dtype=torch.float32, device_map=None, low_cpu_mem_usage=True
        )
        
        adapter_file = adapter_path / "adapter_model.safetensors"
        if adapter_path.exists() and adapter_file.exists():
            model = PeftModel.from_pretrained(base, str(adapter_path))
        else:
            model = base
        
        model.eval()
        model_error = None
        print("[NeuralAI] Model loaded")
    except Exception as e:
        model = tokenizer = None
        model_error = str(e)
        print(f"[NeuralAI] Model error: {e}")


class LocalModel:
    def generate_sync_stream(self, prompt: str, max_new_tokens: int = 256):
        load_local_model()
        if model is None or tokenizer is None:
            for ch in "[Model] Not loaded":
                yield ch
            return
        try:
            from transformers import TextIteratorStreamer
            import threading
            
            full_prompt = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
            inputs = tokenizer(full_prompt, return_tensors="pt")
            streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
            
            thread = threading.Thread(target=model.generate, kwargs={
                **inputs, "streamer": streamer, "max_new_tokens": max_new_tokens,
                "do_sample": True, "temperature": 0.7, "top_p": 0.95,
                "pad_token_id": tokenizer.eos_token_id
            })
            thread.start()
            for text in streamer:
                yield text
        except Exception as e:
            yield f"[Error] {e}"

    async def generate(self, prompt: str, max_new_tokens: int = 256):
        load_local_model()
        if model is None or tokenizer is None:
            for ch in "[Model] Not loaded":
                yield ch
            return
        try:
            full_prompt = f"<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
            inputs = tokenizer(full_prompt, return_tensors="pt")
            with torch.no_grad():
                outputs = model.generate(**inputs, max_new_tokens=max_new_tokens,
                    do_sample=True, temperature=0.7, top_p=0.95, pad_token_id=tokenizer.eos_token_id)
            text = tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
            for ch in text:
                yield ch
        except Exception as e:
            for ch in f"[Error] {e}":
                yield ch


local_model = LocalModel()


def neuralai_route(msg: str) -> Tuple[str, str | None]:
    try:
        from neuralai_router import neuralai_route as _route
        return _route(msg)
    except:
        lower = msg.lower()
        if any(k in lower for k in ["research", "analyze", "debug"]):
            return ("uplink", None)
        return ("local", None)


async def neuralai_local(prompt: str):
    async for token in local_model.generate(prompt):
        yield token


async def neuralai_uplink(prompt: str) -> str:
    async with aiohttp.ClientSession() as session:
        tasks = [
            session.post(f"{UPLINK_BASE}:{p}/task", json={"goal": prompt}, timeout=aiohttp.ClientTimeout(total=30))
            for p in [DIALOG_PORT, DATA_PORT, OPS_PORT, WORLD_PORT]
        ]
        results = await asyncio.gather(*tasks, return_exceptions=True)
    return "[Uplink] Processing..."


async def neuralai_tool_call(tool: str, msg: str):
    from neuralai_router import extract_tool_params
    params = extract_tool_params(msg, tool)
    
    # Image generation
    if tool == "image_gen":
        prompt = params.get("prompt", msg)
        style = params.get("style", "realistic")
        aspect = params.get("aspect_ratio", "1:1")
        
        yield f"🎨 **Generating: {prompt}**\n\n"
        
        output_dir = "/home/workspace/NeuralAI/images"
        os.makedirs(output_dir, exist_ok=True)
        
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        file_stem = f"neuralai_{timestamp}"
        full_prompt = f"{prompt}, {style} style" if style else prompt
        
        try:
            result = subprocess.run([
                "python3", "-c",
                f'''
import sys
sys.path.insert(0, "/home/.z/tools")
from generate_image import generate_image as gen
r = gen(prompt="{full_prompt.replace(chr(34), chr(92)+chr(34))}", file_stem="{file_stem}", output_dir="{output_dir}", aspect_ratio="{aspect}")
print("OK" if r else "FAIL")
'''
            ], capture_output=True, text=True, timeout=120)
            
            if "OK" in result.stdout:
                yield f"![{prompt}](/neuralai/images/{file_stem}_1.png)\n\n"
                yield f"✅ Saved to `/NeuralAI/images/`\n"
            else:
                yield "❌ Generation failed\n"
        except Exception as e:
            yield f"❌ Error: {e}\n"
        return
    
    # Terminal
    if tool == "terminal":
        cmd = msg
        for p in ["run ", "execute ", "shell "]:
            if msg.lower().startswith(p):
                cmd = msg[len(p):]
                break
        yield "```bash\n"
        proc = await asp.create_subprocess_shell(cmd, stdout=asp.PIPE, stderr=asp.PIPE)
        while True:
            line = await proc.stdout.readline()
            if not line: break
            yield line.decode()
        yield "```\n"
        return
    
    # Code execution
    if tool == "code_exec" and code_sandbox:
        code = params.get("code", msg)
        yield "[Sandbox] Running...\n```"
        loop = asyncio.get_event_loop()
        result = await loop.run_in_executor(None, code_sandbox.run_python, code)
        yield result.get("output", result.get("error", "No output"))
        yield "\n```\n"
        return
    
    # Code generation
    if tool == "code_gen" and code_sandbox:
        yield "[NeuralAI] Writing code...\n"
        code_text = ""
        async for c in local_model.generate(f"Write Python for: {msg}", max_new_tokens=512):
            code_text += c
        import re
        m = re.search(r"```python\s*([\s\S]*?)```", code_text)
        if m:
            code = m.group(1).strip()
            yield f"```python\n{code}\n```\n"
            result = await asyncio.get_event_loop().run_in_executor(None, code_sandbox.run_python, code)
            yield "Output:\n```\n" + (result.get("output") or result.get("error")) + "\n```\n"
        return
    
    # File manager
    if tool == "file_manager" and file_manager:
        query = params.get("query", msg)
        result = await asyncio.get_event_loop().run_in_executor(None, file_manager.search, query)
        if result.get("success"):
            for r in result.get("results", [])[:5]:
                yield f"- {r['path']}\n"
        return
    
    # Git
    if tool == "git" and git_assistant:
        git_assistant.repo_path = Path("/home/workspace/Projects/NeuralAI")
        result = await asyncio.get_event_loop().run_in_executor(None, git_assistant.status)
        if result.get("success"):
            yield f"Branch: {result['branch']}\n"
        return
    
    yield f"[Tool] {tool} pending"


async def stream_text(text: str):
    for ch in text:
        yield ch


async def neuralai_chat(msg: str):
    route, tool = neuralai_route(msg)
    if route == "local":
        async for t in neuralai_local(msg):
            yield t
    elif route == "uplink":
        yield "[Uplink] Connecting...\n"
        resp = await neuralai_uplink(msg)
        async for t in stream_text(resp):
            yield t
    elif route == "tool":
        async for t in neuralai_tool_call(tool, msg):
            yield t
    else:
        async for t in stream_text(f"[NeuralAI] {msg}"):
            yield t


# Warmup
if os.environ.get("NEURALAI_WARMUP", "true") != "false":
    try:
        load_local_model()
    except:
        pass