harsh-dev commited on
Commit
3ece01c
·
unverified ·
1 Parent(s): 8421463
Files changed (3) hide show
  1. README.md +60 -7
  2. app.py +404 -0
  3. requirements.txt +9 -0
README.md CHANGED
@@ -1,13 +1,66 @@
1
  ---
2
- title: K2zon
3
- emoji: 🔥
4
- colorFrom: purple
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 6.26.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: K2 Horizon CPU Agent
3
+ emoji: 🌐
4
+ colorFrom: gray
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.50.0
8
+ python_version: 3.12
9
  app_file: app.py
10
  pinned: false
11
+ models:
12
+ - NANI-Nithin/K2-Horizon-0.9B-GGUF
13
  ---
14
 
15
+ # K2 Horizon CPU Agent
16
+
17
+ A minimal CPU-only Gradio Space powered by:
18
+
19
+ - `NANI-Nithin/K2-Horizon-0.9B-GGUF`
20
+ - `K2-Horizon-0.9B-Q4_K_M.gguf`
21
+ - `llama-cpp-python`
22
+ - `smolagents`
23
+ - DuckDuckGo search without an API key
24
+
25
+ ## Deploy
26
+
27
+ 1. Create a new Hugging Face **Gradio** Space.
28
+ 2. Attach persistent storage and mount it at `/data` in the Space settings.
29
+ 3. Upload `app.py`, `requirements.txt`, and this `README.md` to the repository root.
30
+ 4. Let the Space build and start.
31
+
32
+ No API key or secret is required. The first chat request downloads the approximately 666 MB GGUF file to `/data/models`. Later restarts reuse the persisted model and Hugging Face cache.
33
+
34
+ ## Persistent paths
35
+
36
+ - Model: `/data/models/K2-Horizon-0.9B-Q4_K_M.gguf`
37
+ - Hugging Face cache: `/data/huggingface`
38
+
39
+ If `/data` is unavailable, the app automatically falls back to a local `data` directory.
40
+
41
+ ## Optional Space variables
42
+
43
+ Configure these under **Settings → Variables and secrets** if needed:
44
+
45
+ | Variable | Default | Purpose |
46
+ |---|---:|---|
47
+ | `N_CTX` | `4096` | Context size; use `2048` for less RAM. |
48
+ | `N_THREADS` | available CPUs minus one | Generation threads. |
49
+ | `N_THREADS_BATCH` | available CPUs | Prompt-processing threads. |
50
+ | `N_BATCH` | `256` | Prompt batch size. |
51
+ | `MAX_NEW_TOKENS` | `700` | Maximum tokens per model call. |
52
+ | `TEMPERATURE` | `0.2` | Sampling temperature. |
53
+ | `AGENT_MAX_STEPS` | `5` | Maximum smolagents tool steps. |
54
+
55
+ ## Included tools
56
+
57
+ - DuckDuckGo web search
58
+ - Public webpage text extraction
59
+ - Safe arithmetic calculator
60
+ - Current date and time
61
+
62
+ The Space binds to `0.0.0.0:7860`, keeps public Gradio sharing disabled, and processes one generation at a time for stable CPU memory usage.
63
+
64
+ ## Safety
65
+
66
+ `smolagents.CodeAgent` executes model-generated Python in its restricted local executor. Do not expose the Space to untrusted users without reviewing the risk and configuring Space access controls. Search results and webpage content are untrusted and should be verified for important decisions.
app.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import ipaddress
5
+ import operator
6
+ import os
7
+ import re
8
+ import socket
9
+ import threading
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urljoin, urlparse
14
+
15
+ from dotenv import load_dotenv
16
+
17
+
18
+ load_dotenv()
19
+
20
+ PERSISTENT_ROOT = Path(os.getenv("PERSISTENT_ROOT", "/data")).expanduser()
21
+ try:
22
+ PERSISTENT_ROOT.mkdir(parents=True, exist_ok=True)
23
+ except OSError:
24
+ PERSISTENT_ROOT = Path("data")
25
+ PERSISTENT_ROOT.mkdir(parents=True, exist_ok=True)
26
+
27
+ os.environ.setdefault("HF_HOME", str(PERSISTENT_ROOT / "huggingface"))
28
+ os.environ.setdefault("HF_HUB_CACHE", str(PERSISTENT_ROOT / "huggingface" / "hub"))
29
+
30
+ import gradio as gr
31
+ import requests
32
+ from bs4 import BeautifulSoup
33
+ from ddgs import DDGS
34
+ from huggingface_hub import hf_hub_download
35
+ from llama_cpp import Llama
36
+ from smolagents import ChatMessage, CodeAgent, Model, Tool
37
+
38
+
39
+ MODEL_REPO = os.getenv("MODEL_REPO", "NANI-Nithin/K2-Horizon-0.9B-GGUF")
40
+ MODEL_FILE = os.getenv("MODEL_FILE", "K2-Horizon-0.9B-Q4_K_M.gguf")
41
+ MODEL_DIR = Path(os.getenv("MODEL_DIR", str(PERSISTENT_ROOT / "models"))).expanduser()
42
+
43
+
44
+ def env_int(name: str, default: int) -> int:
45
+ try:
46
+ return int(os.getenv(name, str(default)))
47
+ except ValueError:
48
+ return default
49
+
50
+
51
+ def env_float(name: str, default: float) -> float:
52
+ try:
53
+ return float(os.getenv(name, str(default)))
54
+ except ValueError:
55
+ return default
56
+
57
+
58
+ def content_to_text(content: Any) -> str:
59
+ if isinstance(content, str):
60
+ return content
61
+ if isinstance(content, list):
62
+ parts: list[str] = []
63
+ for item in content:
64
+ if isinstance(item, dict):
65
+ parts.append(str(item.get("text", item.get("content", ""))))
66
+ else:
67
+ parts.append(str(item))
68
+ return "\n".join(part for part in parts if part)
69
+ return str(content or "")
70
+
71
+
72
+ class LlamaCppModel(Model):
73
+ def __init__(self, llama: Llama, max_tokens: int, temperature: float) -> None:
74
+ super().__init__()
75
+ self.llama = llama
76
+ self.max_tokens = max_tokens
77
+ self.temperature = temperature
78
+
79
+ @staticmethod
80
+ def _normalize_messages(messages: list[Any]) -> list[dict[str, str]]:
81
+ normalized: list[dict[str, str]] = []
82
+ for message in messages:
83
+ if isinstance(message, dict):
84
+ role = message.get("role", "user")
85
+ content = message.get("content", "")
86
+ else:
87
+ role = getattr(message, "role", "user")
88
+ content = getattr(message, "content", "")
89
+ if hasattr(role, "value"):
90
+ role = role.value
91
+ role = str(role).lower()
92
+ if role not in {"system", "user", "assistant"}:
93
+ role = "user"
94
+ normalized.append({"role": role, "content": content_to_text(content)})
95
+ return normalized
96
+
97
+ def generate(
98
+ self,
99
+ messages: list[Any],
100
+ stop_sequences: list[str] | None = None,
101
+ response_format: dict[str, Any] | None = None,
102
+ tools_to_call_from: list[Tool] | None = None,
103
+ **kwargs: Any,
104
+ ) -> ChatMessage:
105
+ del response_format, tools_to_call_from
106
+ result = self.llama.create_chat_completion(
107
+ messages=self._normalize_messages(messages),
108
+ max_tokens=int(kwargs.get("max_tokens", self.max_tokens)),
109
+ temperature=float(kwargs.get("temperature", self.temperature)),
110
+ top_p=float(kwargs.get("top_p", 0.9)),
111
+ repeat_penalty=float(kwargs.get("repeat_penalty", 1.1)),
112
+ stop=stop_sequences or None,
113
+ )
114
+ content = result["choices"][0]["message"].get("content", "")
115
+ return ChatMessage(role="assistant", content=content)
116
+
117
+ def __call__(self, messages: list[Any], **kwargs: Any) -> ChatMessage:
118
+ return self.generate(messages, **kwargs)
119
+
120
+ def direct_chat(self, messages: list[dict[str, str]]) -> str:
121
+ result = self.llama.create_chat_completion(
122
+ messages=messages,
123
+ max_tokens=self.max_tokens,
124
+ temperature=self.temperature,
125
+ top_p=0.9,
126
+ repeat_penalty=1.1,
127
+ )
128
+ return str(result["choices"][0]["message"].get("content", "")).strip()
129
+
130
+
131
+ class DuckDuckGoSearchTool(Tool):
132
+ name = "web_search"
133
+ description = "Search the public web with DuckDuckGo. Use it for current facts and external information."
134
+ inputs = {
135
+ "query": {"type": "string", "description": "A focused web search query."},
136
+ "max_results": {
137
+ "type": "integer",
138
+ "description": "Number of results from 1 to 8.",
139
+ "nullable": True,
140
+ },
141
+ }
142
+ output_type = "string"
143
+
144
+ def forward(self, query: str, max_results: int | None = None) -> str:
145
+ limit = max(1, min(int(max_results or 5), 8))
146
+ results = list(DDGS().text(query, max_results=limit))
147
+ if not results:
148
+ return "No search results found."
149
+ rows = []
150
+ for index, item in enumerate(results, 1):
151
+ title = item.get("title", "Untitled")
152
+ url = item.get("href", item.get("url", ""))
153
+ body = item.get("body", "")
154
+ rows.append(f"{index}. {title}\nURL: {url}\nSnippet: {body}")
155
+ return "\n\n".join(rows)
156
+
157
+
158
+ def ensure_public_url(url: str) -> str:
159
+ parsed = urlparse(url)
160
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:
161
+ raise ValueError("Only public http/https URLs are allowed.")
162
+ addresses = socket.getaddrinfo(parsed.hostname, parsed.port or 80, proto=socket.IPPROTO_TCP)
163
+ for address in addresses:
164
+ ip = ipaddress.ip_address(address[4][0])
165
+ if not ip.is_global:
166
+ raise ValueError("Private, loopback, and local network addresses are blocked.")
167
+ return url
168
+
169
+
170
+ class ReadWebpageTool(Tool):
171
+ name = "read_webpage"
172
+ description = "Download and extract readable text from a public web page URL."
173
+ inputs = {
174
+ "url": {"type": "string", "description": "The full public http or https URL."},
175
+ }
176
+ output_type = "string"
177
+
178
+ def forward(self, url: str) -> str:
179
+ current_url = url
180
+ response = None
181
+ for _ in range(4):
182
+ safe_url = ensure_public_url(current_url)
183
+ response = requests.get(
184
+ safe_url,
185
+ timeout=12,
186
+ allow_redirects=False,
187
+ headers={"User-Agent": "Mozilla/5.0 (compatible; K2-Horizon-Agent/1.0)"},
188
+ )
189
+ if response.status_code not in {301, 302, 303, 307, 308}:
190
+ break
191
+ location = response.headers.get("location")
192
+ if not location:
193
+ break
194
+ current_url = urljoin(current_url, location)
195
+ assert response is not None
196
+ response.raise_for_status()
197
+ content_type = response.headers.get("content-type", "")
198
+ if "text/html" not in content_type and "text/plain" not in content_type:
199
+ return f"Unsupported content type: {content_type}"
200
+ soup = BeautifulSoup(response.text[:2_000_000], "html.parser")
201
+ for node in soup(["script", "style", "noscript", "svg"]):
202
+ node.decompose()
203
+ text = re.sub(r"\n{3,}", "\n\n", soup.get_text("\n", strip=True))
204
+ return text[:12_000] or "No readable text found."
205
+
206
+
207
+ _BINARY_OPERATORS = {
208
+ ast.Add: operator.add,
209
+ ast.Sub: operator.sub,
210
+ ast.Mult: operator.mul,
211
+ ast.Div: operator.truediv,
212
+ ast.FloorDiv: operator.floordiv,
213
+ ast.Mod: operator.mod,
214
+ ast.Pow: operator.pow,
215
+ }
216
+ _UNARY_OPERATORS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
217
+
218
+
219
+ def evaluate_expression(node: ast.AST) -> float | int:
220
+ if isinstance(node, ast.Expression):
221
+ return evaluate_expression(node.body)
222
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
223
+ return node.value
224
+ if isinstance(node, ast.BinOp) and type(node.op) in _BINARY_OPERATORS:
225
+ left = evaluate_expression(node.left)
226
+ right = evaluate_expression(node.right)
227
+ if isinstance(node.op, ast.Pow) and abs(right) > 100:
228
+ raise ValueError("Exponent is too large.")
229
+ return _BINARY_OPERATORS[type(node.op)](left, right)
230
+ if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPERATORS:
231
+ return _UNARY_OPERATORS[type(node.op)](evaluate_expression(node.operand))
232
+ raise ValueError("Only numeric arithmetic is supported.")
233
+
234
+
235
+ class CalculatorTool(Tool):
236
+ name = "calculator"
237
+ description = "Safely evaluate a numeric arithmetic expression."
238
+ inputs = {"expression": {"type": "string", "description": "Arithmetic expression to evaluate."}}
239
+ output_type = "string"
240
+
241
+ def forward(self, expression: str) -> str:
242
+ if len(expression) > 200:
243
+ raise ValueError("Expression is too long.")
244
+ value = evaluate_expression(ast.parse(expression, mode="eval"))
245
+ return str(value)
246
+
247
+
248
+ class CurrentTimeTool(Tool):
249
+ name = "current_time"
250
+ description = "Get the current system date and time, including timezone."
251
+ inputs = {}
252
+ output_type = "string"
253
+
254
+ def forward(self) -> str:
255
+ return datetime.now().astimezone().isoformat(timespec="seconds")
256
+
257
+
258
+ class AppRuntime:
259
+ def __init__(self) -> None:
260
+ self.lock = threading.Lock()
261
+ self.model: LlamaCppModel | None = None
262
+ self.agent: CodeAgent | None = None
263
+ self.model_path: Path | None = None
264
+
265
+ def load(self) -> None:
266
+ if self.model is not None:
267
+ return
268
+ with self.lock:
269
+ if self.model is not None:
270
+ return
271
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
272
+ local_path = hf_hub_download(
273
+ repo_id=MODEL_REPO,
274
+ filename=MODEL_FILE,
275
+ local_dir=str(MODEL_DIR),
276
+ )
277
+ self.model_path = Path(local_path)
278
+ llama = Llama(
279
+ model_path=str(self.model_path),
280
+ n_ctx=env_int("N_CTX", 4096),
281
+ n_threads=env_int("N_THREADS", max(1, (os.cpu_count() or 4) - 1)),
282
+ n_threads_batch=env_int("N_THREADS_BATCH", os.cpu_count() or 4),
283
+ n_batch=env_int("N_BATCH", 256),
284
+ n_gpu_layers=0,
285
+ use_mmap=True,
286
+ verbose=os.getenv("LLAMA_VERBOSE", "0") == "1",
287
+ )
288
+ self.model = LlamaCppModel(
289
+ llama=llama,
290
+ max_tokens=env_int("MAX_NEW_TOKENS", 700),
291
+ temperature=env_float("TEMPERATURE", 0.2),
292
+ )
293
+ self.agent = CodeAgent(
294
+ tools=[
295
+ DuckDuckGoSearchTool(),
296
+ ReadWebpageTool(),
297
+ CalculatorTool(),
298
+ CurrentTimeTool(),
299
+ ],
300
+ model=self.model,
301
+ max_steps=env_int("AGENT_MAX_STEPS", 5),
302
+ add_base_tools=False,
303
+ additional_authorized_imports=[],
304
+ code_block_tags="markdown",
305
+ )
306
+
307
+ def reply(self, message: str, history: list[dict[str, str]], use_tools: bool) -> str:
308
+ self.load()
309
+ assert self.model is not None
310
+ if use_tools:
311
+ assert self.agent is not None
312
+ transcript = "\n".join(
313
+ f"{item.get('role', 'user')}: {content_to_text(item.get('content', ''))}"
314
+ for item in history[-6:]
315
+ if item.get("role") in {"user", "assistant"}
316
+ )
317
+ task = message
318
+ if transcript:
319
+ task = f"Conversation context:\n{transcript}\n\nCurrent user request:\n{message}"
320
+ return str(self.agent.run(task, reset=True)).strip()
321
+ system = {
322
+ "role": "system",
323
+ "content": "You are K2 Horizon, a concise and helpful local assistant.",
324
+ }
325
+ context = [system]
326
+ for item in history[-10:]:
327
+ if item.get("role") in {"user", "assistant"}:
328
+ context.append({"role": item["role"], "content": content_to_text(item.get("content", ""))})
329
+ context.append({"role": "user", "content": message})
330
+ return self.model.direct_chat(context)
331
+
332
+
333
+ runtime = AppRuntime()
334
+
335
+
336
+ def respond(message: str, history: list[dict[str, str]], use_tools: bool):
337
+ if not message.strip():
338
+ return "", history
339
+ updated = history + [{"role": "user", "content": message}]
340
+ try:
341
+ answer = runtime.reply(message.strip(), history, use_tools)
342
+ except Exception as exc:
343
+ answer = f"Error: {type(exc).__name__}: {exc}"
344
+ updated.append({"role": "assistant", "content": answer})
345
+ return "", updated
346
+
347
+
348
+ CSS = """
349
+ .gradio-container { max-width: 860px !important; margin: 0 auto !important; }
350
+ #app-shell { min-height: 100vh; padding: 32px 12px 20px; }
351
+ #title { text-align: center; margin-bottom: 2px; }
352
+ #subtitle { text-align: center; color: var(--body-text-color-subdued); margin-bottom: 18px; }
353
+ #chat { border: 1px solid var(--border-color-primary); border-radius: 18px; overflow: hidden; }
354
+ #composer { gap: 10px; align-items: stretch; margin-top: 12px; }
355
+ #prompt textarea { border-radius: 14px !important; }
356
+ #send { min-width: 92px; border-radius: 14px !important; }
357
+ #controls { align-items: center; margin-top: 8px; }
358
+ #note { color: var(--body-text-color-subdued); font-size: 12px; text-align: right; }
359
+ footer { display: none !important; }
360
+ """
361
+
362
+
363
+ with gr.Blocks(
364
+ title="K2 Horizon",
365
+ theme=gr.themes.Base(primary_hue="slate", neutral_hue="slate"),
366
+ css=CSS,
367
+ ) as demo:
368
+ with gr.Column(elem_id="app-shell"):
369
+ gr.Markdown("# K2 Horizon", elem_id="title")
370
+ gr.Markdown("Private CPU inference with optional web tools", elem_id="subtitle")
371
+ chatbot = gr.Chatbot(
372
+ type="messages",
373
+ height=570,
374
+ show_copy_button=True,
375
+ placeholder="Ask anything",
376
+ elem_id="chat",
377
+ )
378
+ with gr.Row(elem_id="composer"):
379
+ prompt = gr.Textbox(
380
+ placeholder="Message K2 Horizon…",
381
+ show_label=False,
382
+ scale=9,
383
+ lines=1,
384
+ max_lines=5,
385
+ elem_id="prompt",
386
+ )
387
+ send = gr.Button("Send", variant="primary", scale=1, elem_id="send")
388
+ with gr.Row(elem_id="controls"):
389
+ use_tools = gr.Checkbox(value=True, label="Web tools", scale=1)
390
+ clear = gr.Button("Clear", variant="secondary", size="sm", scale=0)
391
+ gr.Markdown("Model loads on the first message", elem_id="note")
392
+
393
+ send.click(respond, [prompt, chatbot, use_tools], [prompt, chatbot])
394
+ prompt.submit(respond, [prompt, chatbot, use_tools], [prompt, chatbot])
395
+ clear.click(lambda: ("", []), outputs=[prompt, chatbot], queue=False)
396
+
397
+
398
+ if __name__ == "__main__":
399
+ demo.queue(default_concurrency_limit=1).launch(
400
+ server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
401
+ server_port=env_int("GRADIO_SERVER_PORT", 7860),
402
+ share=os.getenv("GRADIO_SHARE", "0") == "1",
403
+ show_error=True,
404
+ )
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
2
+ gradio==5.50.0
3
+ huggingface-hub>=0.31.2
4
+ llama-cpp-python==0.3.35
5
+ smolagents==1.26.0
6
+ ddgs==9.16.0
7
+ beautifulsoup4>=4.13
8
+ requests>=2.32
9
+ python-dotenv>=1.0