Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,111 +1,94 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from typing import List
|
| 3 |
-
import
|
| 4 |
from openai import OpenAI
|
| 5 |
-
from huggingface_hub import list_repo_files, hf_hub_download
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
if not HF_TOKEN:
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
MODEL_ID = "openai/gpt-oss-20b" # chat model via HF router
|
| 17 |
EMBED_MODEL = "text-embedding-3-small"
|
| 18 |
-
CACHE_FILE = "/tmp/ohamlab_emb_cache.json"
|
| 19 |
-
|
| 20 |
-
client = OpenAI(api_key=HF_TOKEN)
|
| 21 |
-
LOG_FILE = "ohamlab_chat.log"
|
| 22 |
-
|
| 23 |
-
def log(msg: str):
|
| 24 |
-
ts = time.strftime("%Y-%m-%d %H:%M:%S")
|
| 25 |
-
line = f"[{ts}] {msg}"
|
| 26 |
-
print(line)
|
| 27 |
-
try:
|
| 28 |
-
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
| 29 |
-
f.write(line + "\n")
|
| 30 |
-
except Exception:
|
| 31 |
-
pass
|
| 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 |
chunks.append(buf.strip())
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
|
| 69 |
def get_embeddings(texts: List[str]) -> np.ndarray:
|
|
|
|
| 70 |
if not texts:
|
| 71 |
return np.zeros((1, 1536))
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
except Exception:
|
| 90 |
-
pass
|
| 91 |
-
|
| 92 |
-
log("Scanning Markdown files in repo for knowledge base...")
|
| 93 |
-
chunks = load_all_md_from_repo(REPO_ID)
|
| 94 |
-
embs = get_embeddings(chunks)
|
| 95 |
-
try:
|
| 96 |
-
json.dump({"chunks": chunks, "embs": embs.tolist()}, open(CACHE_FILE, "w"))
|
| 97 |
-
except Exception:
|
| 98 |
-
pass
|
| 99 |
-
log(f"Knowledge base ready: {len(chunks)} chunks.")
|
| 100 |
-
return chunks, embs
|
| 101 |
-
|
| 102 |
-
KNOWLEDGE_CHUNKS, KNOWLEDGE_EMBS = load_knowledge_cache()
|
| 103 |
-
|
| 104 |
-
# ==========================================================
|
| 105 |
-
# RETRIEVAL
|
| 106 |
-
# ==========================================================
|
| 107 |
-
def get_relevant_context(query: str, top_k=3) -> str:
|
| 108 |
-
if not KNOWLEDGE_CHUNKS or not query.strip():
|
| 109 |
return ""
|
| 110 |
q_emb = get_embeddings([query])[0]
|
| 111 |
sims = np.dot(KNOWLEDGE_EMBS, q_emb) / (
|
|
@@ -114,85 +97,50 @@ def get_relevant_context(query: str, top_k=3) -> str:
|
|
| 114 |
top_idx = np.argsort(sims)[-top_k:][::-1]
|
| 115 |
return "\n\n".join(KNOWLEDGE_CHUNKS[i] for i in top_idx)
|
| 116 |
|
| 117 |
-
#
|
| 118 |
-
#
|
| 119 |
-
#
|
| 120 |
SYSTEM_PROMPT = (
|
| 121 |
-
"You are OhamLab AI β
|
| 122 |
-
"
|
| 123 |
-
"Never
|
| 124 |
)
|
| 125 |
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
def trim_msgs(msgs, max_chars=MAX_HISTORY_CHARS):
|
| 131 |
-
sys = msgs[0]
|
| 132 |
-
tail, total = [], len(sys["content"])
|
| 133 |
-
for m in reversed(msgs[1:]):
|
| 134 |
-
seg = len(m["content"])
|
| 135 |
-
if total + seg > max_chars: break
|
| 136 |
-
tail.append(m)
|
| 137 |
-
total += seg
|
| 138 |
-
return [sys] + list(reversed(tail))
|
| 139 |
-
|
| 140 |
-
def chat(user_msg, chat_hist):
|
| 141 |
-
global history, chat_ui_history
|
| 142 |
-
user_msg = (user_msg or "").strip()
|
| 143 |
-
if not user_msg:
|
| 144 |
-
return chat_ui_history, ""
|
| 145 |
-
|
| 146 |
-
context = get_relevant_context(user_msg)
|
| 147 |
-
if context:
|
| 148 |
-
user_msg += f"\n\n[Context]\n{context[:1500]}"
|
| 149 |
-
|
| 150 |
-
history.append({"role": "user", "content": user_msg})
|
| 151 |
-
trimmed = trim_msgs(history)
|
| 152 |
|
|
|
|
| 153 |
try:
|
| 154 |
resp = client.chat.completions.create(
|
| 155 |
model=MODEL_ID,
|
| 156 |
-
messages=
|
| 157 |
-
|
| 158 |
-
|
| 159 |
)
|
| 160 |
-
|
| 161 |
except Exception as e:
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
history.append({"role": "assistant", "content": reply})
|
| 166 |
-
chat_ui_history.append((user_msg, reply))
|
| 167 |
-
history[:] = trim_msgs(history)
|
| 168 |
-
|
| 169 |
-
log(f"USER: {user_msg[:60]} | BOT: {reply[:60]}")
|
| 170 |
-
return chat_ui_history, ""
|
| 171 |
-
|
| 172 |
-
def reset():
|
| 173 |
-
global history, chat_ui_history
|
| 174 |
-
history = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 175 |
-
chat_ui_history = []
|
| 176 |
-
log("Chat reset.")
|
| 177 |
-
return []
|
| 178 |
-
|
| 179 |
-
# ==========================================================
|
| 180 |
-
# UI
|
| 181 |
-
# ==========================================================
|
| 182 |
-
def build_ui():
|
| 183 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 184 |
-
gr.Markdown("### π¬ OhamLab AI β Knowledge Chat (Markdown-Aware)")
|
| 185 |
-
chatbot = gr.Chatbot(height=350)
|
| 186 |
-
msg = gr.Textbox(placeholder="Ask anything about OhamLab...", lines=1)
|
| 187 |
-
send = gr.Button("Send", variant="primary")
|
| 188 |
-
clear = gr.Button("Clear")
|
| 189 |
-
|
| 190 |
-
send.click(chat, inputs=[msg, chatbot], outputs=[chatbot, msg])
|
| 191 |
-
msg.submit(chat, inputs=[msg, chatbot], outputs=[chatbot, msg])
|
| 192 |
-
clear.click(reset, None, chatbot)
|
| 193 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
| 194 |
-
return demo
|
| 195 |
|
|
|
|
|
|
|
|
|
|
| 196 |
if __name__ == "__main__":
|
| 197 |
-
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import json
|
| 4 |
+
import numpy as np
|
| 5 |
+
import logging
|
| 6 |
from typing import List
|
| 7 |
+
from huggingface_hub import HfApi, hf_hub_download, list_repo_files
|
| 8 |
from openai import OpenAI
|
|
|
|
| 9 |
|
| 10 |
+
# ---------------------------
|
| 11 |
+
# Logging setup
|
| 12 |
+
# ---------------------------
|
| 13 |
+
logging.basicConfig(level=logging.INFO)
|
| 14 |
+
logger = logging.getLogger("ohamlab_agent")
|
| 15 |
+
|
| 16 |
+
# ---------------------------
|
| 17 |
+
# Config
|
| 18 |
+
# ---------------------------
|
| 19 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY") or os.environ.get("HUGGINGFACE_TOKEN")
|
| 20 |
if not HF_TOKEN:
|
| 21 |
+
logger.critical("Missing HF_TOKEN / OPENAI_API_KEY / HUGGINGFACE_TOKEN environment variable.")
|
| 22 |
+
raise RuntimeError("ERROR: set env var HF_TOKEN or OPENAI_API_KEY with your Hugging Face / Router token.")
|
| 23 |
|
| 24 |
MODEL_ID = "openai/gpt-oss-20b" # chat model via HF router
|
| 25 |
EMBED_MODEL = "text-embedding-3-small"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
HF_REPO = "rahul7star/OhamLab-LLM"
|
| 28 |
+
HF_REPO_DIR = "./hf_capsules" # local cache
|
| 29 |
+
os.makedirs(HF_REPO_DIR, exist_ok=True)
|
| 30 |
+
|
| 31 |
+
# ---------------------------
|
| 32 |
+
# Client (OpenAI router via HF)
|
| 33 |
+
# ---------------------------
|
| 34 |
+
try:
|
| 35 |
+
client = OpenAI(base_url="https://router.huggingface.co/v1", api_key=HF_TOKEN)
|
| 36 |
+
logger.info("β
OpenAI client initialized via HF router.")
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.exception("β Failed initializing OpenAI client: %s", e)
|
| 39 |
+
raise
|
| 40 |
+
|
| 41 |
+
# ---------------------------
|
| 42 |
+
# Knowledge Loader
|
| 43 |
+
# ---------------------------
|
| 44 |
+
def load_markdown_files(repo_id: str, local_dir: str) -> List[str]:
|
| 45 |
+
"""Downloads all .md files from Hugging Face repo."""
|
| 46 |
+
api = HfApi(token=HF_TOKEN)
|
| 47 |
+
files = list_repo_files(repo_id, repo_type="model", token=HF_TOKEN)
|
| 48 |
+
md_files = [f for f in files if f.endswith(".md")]
|
| 49 |
+
logger.info(f"π Found {len(md_files)} markdown files in {repo_id}")
|
| 50 |
+
|
| 51 |
+
chunks = []
|
| 52 |
+
for f in md_files:
|
| 53 |
+
try:
|
| 54 |
+
path = hf_hub_download(repo_id=repo_id, filename=f, local_dir=local_dir, token=HF_TOKEN)
|
| 55 |
+
with open(path, "r", encoding="utf-8") as fh:
|
| 56 |
+
content = fh.read()
|
| 57 |
+
# Split into 400β600 char segments
|
| 58 |
+
buf = ""
|
| 59 |
+
for line in content.splitlines():
|
| 60 |
+
buf += line.strip() + " "
|
| 61 |
+
if len(buf) > 500:
|
| 62 |
chunks.append(buf.strip())
|
| 63 |
+
buf = ""
|
| 64 |
+
if buf:
|
| 65 |
+
chunks.append(buf.strip())
|
| 66 |
+
except Exception as e:
|
| 67 |
+
logger.warning(f"β οΈ Failed loading {f}: {e}")
|
| 68 |
+
logger.info(f"β
Loaded {len(chunks)} knowledge chunks.")
|
| 69 |
+
return chunks
|
| 70 |
|
| 71 |
def get_embeddings(texts: List[str]) -> np.ndarray:
|
| 72 |
+
"""Batch embed text list."""
|
| 73 |
if not texts:
|
| 74 |
return np.zeros((1, 1536))
|
| 75 |
+
res = client.embeddings.create(model=EMBED_MODEL, input=texts)
|
| 76 |
+
return np.array([r.embedding for r in res.data])
|
| 77 |
+
|
| 78 |
+
# ---------------------------
|
| 79 |
+
# Load knowledge and embeddings
|
| 80 |
+
# ---------------------------
|
| 81 |
+
logger.info("π Loading OhamLab knowledge base...")
|
| 82 |
+
KNOWLEDGE_CHUNKS = load_markdown_files(HF_REPO, HF_REPO_DIR)
|
| 83 |
+
logger.info("π Generating embeddings...")
|
| 84 |
+
KNOWLEDGE_EMBS = get_embeddings(KNOWLEDGE_CHUNKS)
|
| 85 |
+
logger.info(f"π§ Knowledge base ready ({len(KNOWLEDGE_CHUNKS)} chunks).")
|
| 86 |
+
|
| 87 |
+
# ---------------------------
|
| 88 |
+
# Retrieval helper
|
| 89 |
+
# ---------------------------
|
| 90 |
+
def get_relevant_context(query: str, top_k: int = 3) -> str:
|
| 91 |
+
if not KNOWLEDGE_CHUNKS or not query:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return ""
|
| 93 |
q_emb = get_embeddings([query])[0]
|
| 94 |
sims = np.dot(KNOWLEDGE_EMBS, q_emb) / (
|
|
|
|
| 97 |
top_idx = np.argsort(sims)[-top_k:][::-1]
|
| 98 |
return "\n\n".join(KNOWLEDGE_CHUNKS[i] for i in top_idx)
|
| 99 |
|
| 100 |
+
# ---------------------------
|
| 101 |
+
# Chat Logic
|
| 102 |
+
# ---------------------------
|
| 103 |
SYSTEM_PROMPT = (
|
| 104 |
+
"You are OhamLab AI β factual, concise, and context-aware.\n"
|
| 105 |
+
"Use OhamLab Markdown knowledge if relevant.\n"
|
| 106 |
+
"Never invent information; be clear and professional."
|
| 107 |
)
|
| 108 |
|
| 109 |
+
def chat(query: str, history: List[dict]) -> str:
|
| 110 |
+
context = get_relevant_context(query)
|
| 111 |
+
user_input = f"{query}\n\n[Context]\n{context[:1500]}" if context else query
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
msgs = history + [{"role": "user", "content": user_input}]
|
| 114 |
try:
|
| 115 |
resp = client.chat.completions.create(
|
| 116 |
model=MODEL_ID,
|
| 117 |
+
messages=msgs,
|
| 118 |
+
temperature=0.5,
|
| 119 |
+
max_tokens=800,
|
| 120 |
)
|
| 121 |
+
return resp.choices[0].message.content.strip()
|
| 122 |
except Exception as e:
|
| 123 |
+
logger.error(f"Chat error: {e}")
|
| 124 |
+
return "Iβm having trouble processing that. Please try again."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
# ---------------------------
|
| 127 |
+
# Example usage
|
| 128 |
+
# ---------------------------
|
| 129 |
if __name__ == "__main__":
|
| 130 |
+
logger.info("π Starting OhamLab AI β Knowledge Mode")
|
| 131 |
+
history = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 132 |
+
while True:
|
| 133 |
+
try:
|
| 134 |
+
q = input("\nπ§ Ask OhamLab β ").strip()
|
| 135 |
+
if not q:
|
| 136 |
+
continue
|
| 137 |
+
if q.lower() in ("exit", "quit"):
|
| 138 |
+
break
|
| 139 |
+
ans = chat(q, history)
|
| 140 |
+
print("\nπ¬", ans)
|
| 141 |
+
history.append({"role": "user", "content": q})
|
| 142 |
+
history.append({"role": "assistant", "content": ans})
|
| 143 |
+
except KeyboardInterrupt:
|
| 144 |
+
break
|
| 145 |
+
except Exception as e:
|
| 146 |
+
logger.exception(f"Main loop error: {e}")
|