Upload 2 files
Browse files- main.py +137 -0
- requirements.txt +9 -0
main.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import torch
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from duckduckgo_search import ddg
|
| 6 |
+
import chromadb
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 9 |
+
|
| 10 |
+
# ===============================
|
| 11 |
+
# 1️⃣ Load Model (Llama-3-8B-Instruct)
|
| 12 |
+
# ===============================
|
| 13 |
+
MODEL_ID = "meta-llama/Meta-Llama-3-8B-Instruct"
|
| 14 |
+
|
| 15 |
+
print("🚀 Loading Billy AI model...")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 17 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 18 |
+
MODEL_ID,
|
| 19 |
+
torch_dtype=torch.float32, # CPU-friendly
|
| 20 |
+
device_map="auto"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def generate_text(prompt: str, max_tokens: int = 512) -> str:
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 25 |
+
output = model.generate(
|
| 26 |
+
**inputs,
|
| 27 |
+
max_new_tokens=max_tokens,
|
| 28 |
+
do_sample=True,
|
| 29 |
+
temperature=0.7,
|
| 30 |
+
top_p=0.9
|
| 31 |
+
)
|
| 32 |
+
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 33 |
+
|
| 34 |
+
# ===============================
|
| 35 |
+
# 2️⃣ Setup RAG (Memory + Search)
|
| 36 |
+
# ===============================
|
| 37 |
+
db = chromadb.PersistentClient(path="./billy_rag_db")
|
| 38 |
+
try:
|
| 39 |
+
collection = db.get_collection("billy_rag")
|
| 40 |
+
except:
|
| 41 |
+
collection = db.create_collection("billy_rag")
|
| 42 |
+
|
| 43 |
+
embedder = SentenceTransformer("all-MiniLM-L6-v2")
|
| 44 |
+
|
| 45 |
+
def search_web(query: str):
|
| 46 |
+
try:
|
| 47 |
+
results = ddg(query, max_results=3)
|
| 48 |
+
return [r.get("body") or r.get("snippet") or "" for r in results if r]
|
| 49 |
+
except:
|
| 50 |
+
return []
|
| 51 |
+
|
| 52 |
+
def store_knowledge(text: str):
|
| 53 |
+
vec = embedder.encode(text).tolist()
|
| 54 |
+
try:
|
| 55 |
+
collection.add(documents=[text], embeddings=[vec], ids=[str(abs(hash(text)))])
|
| 56 |
+
except:
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
def retrieve_knowledge(query: str) -> str:
|
| 60 |
+
vec = embedder.encode(query).tolist()
|
| 61 |
+
results = collection.query(query_embeddings=[vec], n_results=3)
|
| 62 |
+
return " ".join(results["documents"][0]) if results and results["documents"] else ""
|
| 63 |
+
|
| 64 |
+
# ===============================
|
| 65 |
+
# 3️⃣ Tool Functions
|
| 66 |
+
# ===============================
|
| 67 |
+
def summarize_text(text: str) -> str:
|
| 68 |
+
prompt = f"Summarize the following text in simple terms:\n\n{text}\n\nSummary:"
|
| 69 |
+
return generate_text(prompt, max_tokens=200)
|
| 70 |
+
|
| 71 |
+
def translate_text(text: str, lang: str) -> str:
|
| 72 |
+
prompt = f"Translate the following text to {lang}:\n\n{text}\n\nTranslation:"
|
| 73 |
+
return generate_text(prompt, max_tokens=200)
|
| 74 |
+
|
| 75 |
+
def explain_code(code: str) -> str:
|
| 76 |
+
prompt = f"Explain the following code in simple terms:\n\n```{code}```\n\nExplanation:"
|
| 77 |
+
return generate_text(prompt, max_tokens=300)
|
| 78 |
+
|
| 79 |
+
# ===============================
|
| 80 |
+
# 4️⃣ FastAPI App
|
| 81 |
+
# ===============================
|
| 82 |
+
app = FastAPI(title="Billy AI - Free Chatbot")
|
| 83 |
+
|
| 84 |
+
class Query(BaseModel):
|
| 85 |
+
message: str
|
| 86 |
+
user_id: str = "anonymous"
|
| 87 |
+
|
| 88 |
+
@app.post("/chat")
|
| 89 |
+
def chat(req: Query):
|
| 90 |
+
user_msg = req.message.strip()
|
| 91 |
+
|
| 92 |
+
# --- Special Commands ---
|
| 93 |
+
if user_msg.lower().startswith("/summarize "):
|
| 94 |
+
return {"response": summarize_text(user_msg[11:])}
|
| 95 |
+
|
| 96 |
+
if user_msg.lower().startswith("/translate "):
|
| 97 |
+
try:
|
| 98 |
+
lang, text = user_msg[10:].split(" ", 1)
|
| 99 |
+
return {"response": translate_text(text, lang)}
|
| 100 |
+
except:
|
| 101 |
+
return {"response": "Format: /translate <language> <text>"}
|
| 102 |
+
|
| 103 |
+
if user_msg.lower().startswith("/explaincode "):
|
| 104 |
+
return {"response": explain_code(user_msg[13:])}
|
| 105 |
+
|
| 106 |
+
# --- Search & RAG ---
|
| 107 |
+
local_knowledge = retrieve_knowledge(user_msg)
|
| 108 |
+
|
| 109 |
+
if not local_knowledge:
|
| 110 |
+
web_results = search_web(user_msg)
|
| 111 |
+
for r in web_results:
|
| 112 |
+
if r.strip():
|
| 113 |
+
store_knowledge(r)
|
| 114 |
+
local_knowledge = " ".join(web_results)
|
| 115 |
+
|
| 116 |
+
# --- Personality & Context ---
|
| 117 |
+
context = (
|
| 118 |
+
"You are Billy AI — a helpful, witty, and slightly funny AI assistant. "
|
| 119 |
+
"You are a bit smarter than GPT-3.5, but not too advanced. "
|
| 120 |
+
"When answering, be friendly, concise, and give useful info. "
|
| 121 |
+
f"Use this info if helpful: {local_knowledge}\n\n"
|
| 122 |
+
f"User: {user_msg}\nAssistant:"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
reply = generate_text(context)
|
| 126 |
+
return {"response": reply.strip()}
|
| 127 |
+
|
| 128 |
+
@app.get("/")
|
| 129 |
+
def home():
|
| 130 |
+
return {"message": "Billy AI is running and ready to chat!"}
|
| 131 |
+
|
| 132 |
+
# ===============================
|
| 133 |
+
# 5️⃣ Run
|
| 134 |
+
# ===============================
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
import uvicorn
|
| 137 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn
|
| 3 |
+
torch
|
| 4 |
+
transformers
|
| 5 |
+
sentence-transformers
|
| 6 |
+
chromadb
|
| 7 |
+
duckduckgo-search
|
| 8 |
+
pydantic
|
| 9 |
+
huggingface_hub
|