rahul7star commited on
Commit
3cca735
Β·
verified Β·
1 Parent(s): cdde93e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -166
app.py CHANGED
@@ -1,111 +1,94 @@
1
- import os, re, time, json, textwrap, traceback, numpy as np
 
 
 
 
2
  from typing import List
3
- import gradio as gr
4
  from openai import OpenAI
5
- from huggingface_hub import list_repo_files, hf_hub_download
6
 
7
- # ==========================================================
8
- # CONFIG
9
- # ==========================================================
10
- REPO_ID = "rahul7star/OhamLab-LLM"
11
- API_KEY_ENV = "OPENAI_API_KEY"
12
- HF_TOKEN = os.getenv(API_KEY_ENV)
 
 
 
 
13
  if not HF_TOKEN:
14
- raise RuntimeError(f"Missing {API_KEY_ENV}")
 
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
- # KNOWLEDGE SCANNER + EMBEDDINGS
35
- # ==========================================================
36
- def load_all_md_from_repo(repo_id: str) -> List[str]:
37
- """Scan all .md files in the repo and return concatenated chunks."""
38
- try:
39
- files = list_repo_files(repo_id=repo_id, repo_type="model", token=HF_TOKEN)
40
- md_files = [f for f in files if f.lower().endswith(".md")]
41
- if not md_files:
42
- log("⚠️ No markdown files found.")
43
- return []
44
-
45
- chunks = []
46
- for fname in md_files:
47
- try:
48
- local_path = hf_hub_download(repo_id, filename=fname, token=HF_TOKEN)
49
- with open(local_path, "r", encoding="utf-8") as f:
50
- text = f.read()
51
- text = re.sub(r"<[^>]+>", "", text) # strip HTML
52
- # Split into ~500 char chunks
53
- buf = ""
54
- for line in text.splitlines():
55
- buf += line.strip() + " "
56
- if len(buf) > 500:
57
- chunks.append(buf.strip())
58
- buf = ""
59
- if buf:
 
 
 
 
 
 
 
 
60
  chunks.append(buf.strip())
61
- log(f"Loaded {fname} ({len(text)} chars β†’ {len(chunks)} chunks)")
62
- except Exception as e:
63
- log(f"⚠️ Failed to load {fname}: {e}")
64
- return chunks
65
- except Exception as e:
66
- log(f"⚠️ Repo scan failed: {e}")
67
- return []
68
 
69
  def get_embeddings(texts: List[str]) -> np.ndarray:
 
70
  if not texts:
71
  return np.zeros((1, 1536))
72
- try:
73
- res = client.embeddings.create(model=EMBED_MODEL, input=texts)
74
- return np.array([r.embedding for r in res.data])
75
- except Exception as e:
76
- log(f"Embedding error: {e}")
77
- return np.zeros((len(texts), 1536))
78
-
79
- def load_knowledge_cache() -> tuple[list[str], np.ndarray]:
80
- """Load embeddings from cache or regenerate from repo."""
81
- if os.path.exists(CACHE_FILE):
82
- try:
83
- with open(CACHE_FILE, "r", encoding="utf-8") as f:
84
- data = json.load(f)
85
- chunks = data["chunks"]
86
- embs = np.array(data["embs"])
87
- log(f"Loaded cached embeddings: {len(chunks)} chunks.")
88
- return chunks, embs
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
- # CHAT ENGINE
119
- # ==========================================================
120
  SYSTEM_PROMPT = (
121
- "You are OhamLab AI β€” a concise, factual chat assistant.\n"
122
- "When relevant, use the OhamLab knowledge base provided in context.\n"
123
- "Never show code unless explicitly requested. Keep tone professional and calm."
124
  )
125
 
126
- history = [{"role": "system", "content": SYSTEM_PROMPT}]
127
- chat_ui_history = []
128
- MAX_HISTORY_CHARS = 3000
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=trimmed,
157
- max_tokens=600,
158
- temperature=0.6,
159
  )
160
- reply = resp.choices[0].message.content.strip()
161
  except Exception as e:
162
- log(f"Chat error: {e}")
163
- reply = "I'm experiencing a temporary issue. Please try again shortly."
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
- log("Starting OhamLab AI Chat Agent (Markdown Knowledge)...")
198
- build_ui()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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}")