Mr-MIXITOSIK commited on
Commit ·
c2e57d7
0
Parent(s):
1.0
Browse files- .gitignore +15 -0
- README.md +66 -0
- api.py +80 -0
- brand_data/about.txt +13 -0
- main.py +171 -0
- memory_db.py +122 -0
- model_loader.py +58 -0
- requirements.txt +12 -0
- search.py +32 -0
.gitignore
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv/
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
models/*.gguf
|
| 7 |
+
models/*.pt
|
| 8 |
+
models/.cache/
|
| 9 |
+
|
| 10 |
+
rayseek_faiss.index
|
| 11 |
+
rayseek_faiss_meta.json
|
| 12 |
+
rayseek_chroma/
|
| 13 |
+
|
| 14 |
+
*.log
|
| 15 |
+
.env
|
README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RaySeek
|
| 2 |
+
|
| 3 |
+
Local AI assistant powered by llama.cpp, Meta FAISS vector memory, live web search, and symbolic math solving.
|
| 4 |
+
|
| 5 |
+
## Installation
|
| 6 |
+
|
| 7 |
+
```bash
|
| 8 |
+
git clone https://github.com/Raytolfas/RaySeek.git
|
| 9 |
+
cd RaySeek
|
| 10 |
+
python -m venv .venv
|
| 11 |
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 12 |
+
pip install -r requirements.txt
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
> Model weights (`Qwen2.5-3B-Instruct-GGUF`) download automatically from Hugging Face Hub on first run.
|
| 16 |
+
|
| 17 |
+
## CLI Usage
|
| 18 |
+
|
| 19 |
+
```bash
|
| 20 |
+
python main.py
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
### Commands
|
| 24 |
+
- `/web <query>` — search the web in real-time
|
| 25 |
+
- `/translate <text>` — translate text RU <-> EN
|
| 26 |
+
- `/info` — system status and context statistics
|
| 27 |
+
- `/help` — display commands list
|
| 28 |
+
- `/exit` — terminate session
|
| 29 |
+
|
| 30 |
+
## API Usage
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python api.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
The server starts on `http://127.0.0.1:8000`.
|
| 37 |
+
|
| 38 |
+
### Endpoints
|
| 39 |
+
|
| 40 |
+
#### POST `/api/chat`
|
| 41 |
+
Send a message to the assistant.
|
| 42 |
+
|
| 43 |
+
Request:
|
| 44 |
+
```json
|
| 45 |
+
{
|
| 46 |
+
"message": "Hello, who are you?",
|
| 47 |
+
"history": []
|
| 48 |
+
}
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Response:
|
| 52 |
+
```json
|
| 53 |
+
{
|
| 54 |
+
"response": "..."
|
| 55 |
+
}
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
#### GET `/api/health`
|
| 59 |
+
Health check.
|
| 60 |
+
|
| 61 |
+
Response:
|
| 62 |
+
```json
|
| 63 |
+
{
|
| 64 |
+
"status": "ok"
|
| 65 |
+
}
|
| 66 |
+
```
|
api.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Raytolfas
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from fastapi import FastAPI
|
| 16 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
+
from pydantic import BaseModel
|
| 18 |
+
from model_loader import load_engine
|
| 19 |
+
from memory_db import query_texts, index_local_files
|
| 20 |
+
|
| 21 |
+
app = FastAPI()
|
| 22 |
+
|
| 23 |
+
app.add_middleware(
|
| 24 |
+
CORSMiddleware,
|
| 25 |
+
allow_origins=["*"],
|
| 26 |
+
allow_credentials=True,
|
| 27 |
+
allow_methods=["*"],
|
| 28 |
+
allow_headers=["*"],
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
llm = None
|
| 32 |
+
index_local_files()
|
| 33 |
+
|
| 34 |
+
def get_llm():
|
| 35 |
+
global llm
|
| 36 |
+
if llm is None:
|
| 37 |
+
llm = load_engine()
|
| 38 |
+
return llm
|
| 39 |
+
|
| 40 |
+
SYSTEM_PROMPT = """Ты — RaySeek 1.0, интеллектуальный ассистент от Raytolfas.
|
| 41 |
+
Ты точный, универсальный и лаконичный помощник в программировании, анализе, решении задач и диалоге.
|
| 42 |
+
Всегда отвечай строго по существу. Код оформляй в блоки ```язык ... ```."""
|
| 43 |
+
|
| 44 |
+
class ChatRequest(BaseModel):
|
| 45 |
+
message: str
|
| 46 |
+
history: list = []
|
| 47 |
+
|
| 48 |
+
@app.post("/api/chat")
|
| 49 |
+
def chat_endpoint(req: ChatRequest):
|
| 50 |
+
cmd = req.message.strip()
|
| 51 |
+
engine = get_llm()
|
| 52 |
+
|
| 53 |
+
memory_facts = query_texts(cmd, n_results=1)
|
| 54 |
+
context_snippet = ""
|
| 55 |
+
if memory_facts:
|
| 56 |
+
context_snippet = f"\nКонтекст: {memory_facts[0]}"
|
| 57 |
+
|
| 58 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT + context_snippet}]
|
| 59 |
+
for turn in req.history[-16:]:
|
| 60 |
+
messages.append(turn)
|
| 61 |
+
messages.append({"role": "user", "content": cmd})
|
| 62 |
+
|
| 63 |
+
resp = engine.create_chat_completion(
|
| 64 |
+
messages=messages,
|
| 65 |
+
max_tokens=1024,
|
| 66 |
+
temperature=0.6,
|
| 67 |
+
top_p=0.9,
|
| 68 |
+
repeat_penalty=1.15
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
reply = resp["choices"][0]["message"]["content"].strip()
|
| 72 |
+
return {"response": reply}
|
| 73 |
+
|
| 74 |
+
@app.get("/api/health")
|
| 75 |
+
def health():
|
| 76 |
+
return {"status": "ok"}
|
| 77 |
+
|
| 78 |
+
if __name__ == "__main__":
|
| 79 |
+
import uvicorn
|
| 80 |
+
uvicorn.run(app, host="127.0.0.1", port=8000)
|
brand_data/about.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[EN]
|
| 2 |
+
Raytolfas is an independent ecosystem of high-performance software, system utilities, and local AI tools.
|
| 3 |
+
The primary focus of Raytolfas is maximum performance, clean code, privacy, and complete independence from third-party cloud services.
|
| 4 |
+
|
| 5 |
+
Key focus areas and projects within the ecosystem:
|
| 6 |
+
- RaySeek: A local AI assistant that runs directly on the user's hardware without external APIs, subscriptions, or transmitting data to third-party servers.
|
| 7 |
+
|
| 8 |
+
[RU]
|
| 9 |
+
Raytolfas — это независимая экосистема высокопроизводительного программного обеспечения, системных утилит и локальных ИИ-инструментов.
|
| 10 |
+
Главный фокус Raytolfas — максимальная скорость работы, чистота кода, конфиденциальность и полная независимость от сторонних облачных сервисов.
|
| 11 |
+
|
| 12 |
+
Ключевые направления и проекты экосистемы:
|
| 13 |
+
- RaySeek: Локальный ИИ-ассистент, работающий напрямую на железе пользователя без внешних API, подписок и передачи данных на сторонние серверы.
|
main.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Raytolfas
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
import re
|
| 17 |
+
import random
|
| 18 |
+
import sympy
|
| 19 |
+
from model_loader import load_engine
|
| 20 |
+
from memory_db import query_texts, get_doc_count, index_local_files
|
| 21 |
+
from search import web_search
|
| 22 |
+
from deep_translator import GoogleTranslator
|
| 23 |
+
|
| 24 |
+
SYSTEM_PROMPT = """Ты — RaySeek 1.0, интеллектуальный ассистент от Raytolfas.
|
| 25 |
+
Ты точный, универсальный и лаконичный помощник в программировании, анализе, решении задач и диалоге.
|
| 26 |
+
Всегда отвечай строго по существу. Код оформляй в блоки ```язык ... ```."""
|
| 27 |
+
|
| 28 |
+
def format_math_response(text):
|
| 29 |
+
clean_text = text.replace("^", "**")
|
| 30 |
+
match = re.search(r"([\d\+\-\*\/\(\)\s\.\,\^]|sqrt|sin|cos|tan|log|pi|e)+", clean_text)
|
| 31 |
+
if not match:
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
candidate = match.group(0).strip()
|
| 35 |
+
candidate = re.sub(r"^[\+\-\*\/\s\.\,\^]+", "", candidate)
|
| 36 |
+
candidate = re.sub(r"[\+\-\*\/\s\.\,\^\=\?]+$", "", candidate)
|
| 37 |
+
|
| 38 |
+
if not re.search(r"[\+\-\*\/\(\)\^]|sqrt|sin|cos|tan|log", candidate):
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
expr = sympy.sympify(candidate)
|
| 43 |
+
res = expr.evalf()
|
| 44 |
+
if res == int(res):
|
| 45 |
+
res = int(res)
|
| 46 |
+
else:
|
| 47 |
+
res = round(float(res), 4)
|
| 48 |
+
|
| 49 |
+
templates = [
|
| 50 |
+
f"{candidate} = {res}",
|
| 51 |
+
f"Ответ: {res}",
|
| 52 |
+
f"{res}"
|
| 53 |
+
]
|
| 54 |
+
return random.choice(templates)
|
| 55 |
+
except Exception:
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
def translate_text(text):
|
| 59 |
+
has_cyrillic = bool(re.search(r"[а-яА-ЯёЁ]", text))
|
| 60 |
+
target_lang = "en" if has_cyrillic else "ru"
|
| 61 |
+
try:
|
| 62 |
+
return GoogleTranslator(source="auto", target=target_lang).translate(text)
|
| 63 |
+
except Exception as e:
|
| 64 |
+
return f"Error: {e}"
|
| 65 |
+
|
| 66 |
+
def print_help():
|
| 67 |
+
print("Commands:")
|
| 68 |
+
print(" /web <query> Search the web in real-time")
|
| 69 |
+
print(" /translate <text> Translate RU <-> EN")
|
| 70 |
+
print(" /info System info")
|
| 71 |
+
print(" /help Show this help")
|
| 72 |
+
print(" /exit Exit session")
|
| 73 |
+
|
| 74 |
+
def main():
|
| 75 |
+
try:
|
| 76 |
+
index_local_files()
|
| 77 |
+
llm = load_engine()
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Init error: {e}")
|
| 80 |
+
sys.exit(1)
|
| 81 |
+
|
| 82 |
+
ctx_size = getattr(llm, "n_ctx", lambda: 8192)() if callable(getattr(llm, "n_ctx", None)) else 8192
|
| 83 |
+
print(f"RaySeek 1.0 (Context: {ctx_size} tokens)")
|
| 84 |
+
print("Type /help for commands, /exit to quit.\n")
|
| 85 |
+
|
| 86 |
+
history = []
|
| 87 |
+
|
| 88 |
+
while True:
|
| 89 |
+
try:
|
| 90 |
+
line = input("> ").strip()
|
| 91 |
+
if not line:
|
| 92 |
+
continue
|
| 93 |
+
|
| 94 |
+
low = line.lower()
|
| 95 |
+
|
| 96 |
+
if low in ("/exit", "/quit", "exit", "quit"):
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
if low == "/help":
|
| 100 |
+
print_help()
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
if low == "/info":
|
| 104 |
+
docs = get_doc_count()
|
| 105 |
+
print("Model: Qwen2.5-3B-Instruct (GGUF Q4_K_M)")
|
| 106 |
+
print("Engine: llama.cpp")
|
| 107 |
+
print(f"Context window: {ctx_size} tokens")
|
| 108 |
+
print(f"Memory: Meta FAISS ({docs} items)")
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
if low.startswith("/translate "):
|
| 112 |
+
text = line[11:].strip()
|
| 113 |
+
if not text:
|
| 114 |
+
continue
|
| 115 |
+
res = translate_text(text)
|
| 116 |
+
print(res)
|
| 117 |
+
continue
|
| 118 |
+
|
| 119 |
+
if low.startswith("/web "):
|
| 120 |
+
query = line[5:].strip()
|
| 121 |
+
res = web_search(query, max_results=3)
|
| 122 |
+
web_context = "\n".join([f"- {r['title']}: {r['body']}" for r in res]) if res else "No results."
|
| 123 |
+
line = f"Question: {query}\nWeb search:\n{web_context}"
|
| 124 |
+
|
| 125 |
+
math_response = format_math_response(line)
|
| 126 |
+
if math_response:
|
| 127 |
+
print(math_response)
|
| 128 |
+
history.append({"role": "user", "content": line})
|
| 129 |
+
history.append({"role": "assistant", "content": math_response})
|
| 130 |
+
continue
|
| 131 |
+
|
| 132 |
+
memory_facts = query_texts(line, n_results=2)
|
| 133 |
+
context_snippet = ""
|
| 134 |
+
if memory_facts:
|
| 135 |
+
context_snippet = "\n\nFacts:\n" + "\n".join(memory_facts)
|
| 136 |
+
|
| 137 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT + context_snippet}]
|
| 138 |
+
for turn in history[-16:]:
|
| 139 |
+
messages.append(turn)
|
| 140 |
+
messages.append({"role": "user", "content": line})
|
| 141 |
+
|
| 142 |
+
stream = llm.create_chat_completion(
|
| 143 |
+
messages=messages,
|
| 144 |
+
max_tokens=1024,
|
| 145 |
+
temperature=0.65,
|
| 146 |
+
top_p=0.9,
|
| 147 |
+
repeat_penalty=1.18,
|
| 148 |
+
stream=True
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
full_reply = ""
|
| 152 |
+
for chunk in stream:
|
| 153 |
+
delta = chunk["choices"][0].get("delta", {})
|
| 154 |
+
content = delta.get("content", "")
|
| 155 |
+
if content:
|
| 156 |
+
print(content, end="", flush=True)
|
| 157 |
+
full_reply += content
|
| 158 |
+
|
| 159 |
+
print()
|
| 160 |
+
|
| 161 |
+
history.append({"role": "user", "content": line})
|
| 162 |
+
history.append({"role": "assistant", "content": full_reply})
|
| 163 |
+
|
| 164 |
+
except KeyboardInterrupt:
|
| 165 |
+
print("\nExiting.")
|
| 166 |
+
break
|
| 167 |
+
except Exception as e:
|
| 168 |
+
print(f"Error: {e}")
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
main()
|
memory_db.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Raytolfas
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import json
|
| 17 |
+
import faiss
|
| 18 |
+
import numpy as np
|
| 19 |
+
from transformers import AutoTokenizer, AutoModel, logging as tf_logging
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
tf_logging.set_verbosity_error()
|
| 23 |
+
|
| 24 |
+
FAISS_INDEX_FILE = "rayseek_faiss.index"
|
| 25 |
+
METADATA_FILE = "rayseek_faiss_meta.json"
|
| 26 |
+
EMBED_MODEL_NAME = "cointegrated/rubert-tiny2"
|
| 27 |
+
|
| 28 |
+
_tokenizer = None
|
| 29 |
+
_model = None
|
| 30 |
+
_index = None
|
| 31 |
+
_documents = []
|
| 32 |
+
|
| 33 |
+
def _get_embed_model():
|
| 34 |
+
global _tokenizer, _model
|
| 35 |
+
if _tokenizer is None:
|
| 36 |
+
_tokenizer = AutoTokenizer.from_pretrained(EMBED_MODEL_NAME)
|
| 37 |
+
_model = AutoModel.from_pretrained(EMBED_MODEL_NAME)
|
| 38 |
+
_model.eval()
|
| 39 |
+
return _tokenizer, _model
|
| 40 |
+
|
| 41 |
+
def _embed_texts(texts):
|
| 42 |
+
tok, mod = _get_embed_model()
|
| 43 |
+
inputs = tok(texts, padding=True, truncation=True, max_length=128, return_tensors="pt")
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
out = mod(**inputs)
|
| 46 |
+
embeddings = out.last_hidden_state[:, 0, :]
|
| 47 |
+
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
|
| 48 |
+
return embeddings.numpy().astype("float32")
|
| 49 |
+
|
| 50 |
+
def _init_storage():
|
| 51 |
+
global _index, _documents
|
| 52 |
+
if _index is None:
|
| 53 |
+
dim = 312
|
| 54 |
+
if os.path.exists(FAISS_INDEX_FILE) and os.path.exists(METADATA_FILE):
|
| 55 |
+
_index = faiss.read_index(FAISS_INDEX_FILE)
|
| 56 |
+
with open(METADATA_FILE, "r", encoding="utf-8") as f:
|
| 57 |
+
_documents = json.load(f)
|
| 58 |
+
else:
|
| 59 |
+
_index = faiss.IndexFlatIP(dim)
|
| 60 |
+
_documents = []
|
| 61 |
+
|
| 62 |
+
def save_index():
|
| 63 |
+
global _index, _documents
|
| 64 |
+
if _index is not None:
|
| 65 |
+
faiss.write_index(_index, FAISS_INDEX_FILE)
|
| 66 |
+
with open(METADATA_FILE, "w", encoding="utf-8") as f:
|
| 67 |
+
json.dump(_documents, f, ensure_ascii=False)
|
| 68 |
+
|
| 69 |
+
def add_texts(texts, metadatas=None):
|
| 70 |
+
global _index, _documents
|
| 71 |
+
_init_storage()
|
| 72 |
+
if not texts:
|
| 73 |
+
return
|
| 74 |
+
vectors = _embed_texts(texts)
|
| 75 |
+
_index.add(vectors)
|
| 76 |
+
for i, t in enumerate(texts):
|
| 77 |
+
meta = metadatas[i] if metadatas and i < len(metadatas) else {}
|
| 78 |
+
_documents.append({"text": t, "meta": meta})
|
| 79 |
+
save_index()
|
| 80 |
+
|
| 81 |
+
def query_texts(query, n_results=2):
|
| 82 |
+
global _index, _documents
|
| 83 |
+
_init_storage()
|
| 84 |
+
if _index.ntotal == 0:
|
| 85 |
+
return []
|
| 86 |
+
vec = _embed_texts([query])
|
| 87 |
+
k = min(n_results, _index.ntotal)
|
| 88 |
+
distances, indices = _index.search(vec, k)
|
| 89 |
+
results = []
|
| 90 |
+
for idx in indices[0]:
|
| 91 |
+
if idx != -1 and idx < len(_documents):
|
| 92 |
+
results.append(_documents[idx]["text"])
|
| 93 |
+
return results
|
| 94 |
+
|
| 95 |
+
def get_doc_count():
|
| 96 |
+
_init_storage()
|
| 97 |
+
return _index.ntotal if _index is not None else 0
|
| 98 |
+
|
| 99 |
+
def index_local_files():
|
| 100 |
+
if not os.path.exists("brand_data"):
|
| 101 |
+
os.makedirs("brand_data")
|
| 102 |
+
return
|
| 103 |
+
_init_storage()
|
| 104 |
+
known_texts = {d["text"] for d in _documents}
|
| 105 |
+
new_texts = []
|
| 106 |
+
new_metas = []
|
| 107 |
+
for filename in os.listdir("brand_data"):
|
| 108 |
+
if filename.endswith(".txt"):
|
| 109 |
+
filepath = os.path.join("brand_data", filename)
|
| 110 |
+
try:
|
| 111 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 112 |
+
content = f.read()
|
| 113 |
+
paragraphs = [p.strip() for p in content.split("\n") if len(p.strip()) > 10]
|
| 114 |
+
for p in paragraphs:
|
| 115 |
+
if p not in known_texts:
|
| 116 |
+
new_texts.append(p)
|
| 117 |
+
new_metas.append({"source": filename})
|
| 118 |
+
known_texts.add(p)
|
| 119 |
+
except Exception:
|
| 120 |
+
pass
|
| 121 |
+
if new_texts:
|
| 122 |
+
add_texts(new_texts, new_metas)
|
model_loader.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Raytolfas
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import psutil
|
| 17 |
+
from llama_cpp import Llama
|
| 18 |
+
from huggingface_hub import hf_hub_download
|
| 19 |
+
|
| 20 |
+
REPO_ID = "Qwen/Qwen2.5-3B-Instruct-GGUF"
|
| 21 |
+
FILENAME = "qwen2.5-3b-instruct-q4_k_m.gguf"
|
| 22 |
+
MODEL_DIR = "models"
|
| 23 |
+
GGUF_PATH = os.path.join(MODEL_DIR, FILENAME)
|
| 24 |
+
|
| 25 |
+
def get_optimal_context(target_ctx=8192):
|
| 26 |
+
try:
|
| 27 |
+
mem = psutil.virtual_memory()
|
| 28 |
+
available_mb = mem.available / (1024 * 1024)
|
| 29 |
+
if available_mb < 2000:
|
| 30 |
+
return 2048
|
| 31 |
+
elif available_mb < 4000:
|
| 32 |
+
return 4096
|
| 33 |
+
return min(target_ctx, 16384)
|
| 34 |
+
except Exception:
|
| 35 |
+
return 4096
|
| 36 |
+
|
| 37 |
+
def load_engine(n_ctx=None):
|
| 38 |
+
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 39 |
+
if not os.path.exists(GGUF_PATH):
|
| 40 |
+
hf_hub_download(
|
| 41 |
+
repo_id=REPO_ID,
|
| 42 |
+
filename=FILENAME,
|
| 43 |
+
local_dir=MODEL_DIR,
|
| 44 |
+
local_dir_use_symlinks=False
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if n_ctx is None:
|
| 48 |
+
n_ctx = get_optimal_context(8192)
|
| 49 |
+
|
| 50 |
+
threads = max(1, os.cpu_count() - 1)
|
| 51 |
+
llm = Llama(
|
| 52 |
+
model_path=GGUF_PATH,
|
| 53 |
+
n_ctx=n_ctx,
|
| 54 |
+
n_threads=threads,
|
| 55 |
+
n_gpu_layers=-1,
|
| 56 |
+
verbose=False
|
| 57 |
+
)
|
| 58 |
+
return llm
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
llama-cpp-python
|
| 2 |
+
huggingface-hub
|
| 3 |
+
torch
|
| 4 |
+
transformers
|
| 5 |
+
faiss-cpu
|
| 6 |
+
deep-translator
|
| 7 |
+
ddgs
|
| 8 |
+
sympy
|
| 9 |
+
psutil
|
| 10 |
+
fastapi
|
| 11 |
+
uvicorn
|
| 12 |
+
pydantic
|
search.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Raytolfas
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from ddgs import DDGS
|
| 16 |
+
|
| 17 |
+
def web_search(query, max_results=5):
|
| 18 |
+
try:
|
| 19 |
+
with DDGS() as ddgs:
|
| 20 |
+
results = list(ddgs.text(query, max_results=max_results))
|
| 21 |
+
if not results:
|
| 22 |
+
return []
|
| 23 |
+
return [
|
| 24 |
+
{
|
| 25 |
+
"title": r.get("title", ""),
|
| 26 |
+
"body": r.get("body", ""),
|
| 27 |
+
"href": r.get("href", "")
|
| 28 |
+
}
|
| 29 |
+
for r in results
|
| 30 |
+
]
|
| 31 |
+
except Exception:
|
| 32 |
+
return []
|