ram1234598766 commited on
Commit
5dc616d
verified
1 Parent(s): 4b54568

Add cesium2 terminal CLI (live web data) to tools/

Browse files
Files changed (2) hide show
  1. tools/cesium2.cmd +2 -0
  2. tools/cesium2.py +169 -0
tools/cesium2.cmd ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ @echo off
2
+ python "%~dp0cesium2.py" %*
tools/cesium2.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """cesium2 - terminal chat with MORPH-AI v6 (Cesium2) via Ollama, with live web data.
3
+
4
+ Usage:
5
+ cesium2 "what is todays popular news" one-shot answer
6
+ cesium2 interactive chat (/exit to quit, /new resets)
7
+ """
8
+ import json
9
+ import os
10
+ import re
11
+ import sys
12
+ import urllib.parse
13
+ import urllib.request
14
+ from datetime import datetime
15
+
16
+ try:
17
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
18
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
19
+ except Exception:
20
+ pass
21
+
22
+ HOST = os.environ.get("OLLAMA_HOST", "http://localhost:11434").rstrip("/")
23
+ MODEL = os.environ.get("CESIUM2_MODEL", "ram1234598766/Cesium2")
24
+
25
+ SYSTEM = (
26
+ "You are MORPH-AI v6 (Cesium2), a helpful assistant with advanced reasoning. "
27
+ "Your training data has a cutoff; rely ONLY on the [LIVE CONTEXT] block for "
28
+ "time-sensitive facts - it contains the real current date and fresh web results. "
29
+ "Think step by step and be concise."
30
+ )
31
+
32
+ LIVE_RE = re.compile(
33
+ r"\b(news|today|todays|current|currently|latest|recent|now|breaking|price|prices|"
34
+ r"weather|forecast|score|scores|who won|stock|stocks|market|election|update|"
35
+ r"2024|2025|2026|this week|this month|yesterday)\b",
36
+ re.I,
37
+ )
38
+
39
+
40
+ def google_news(query, limit=5):
41
+ def fetch(qs):
42
+ url = f"https://news.google.com/rss/search?q={urllib.parse.quote(qs)}&hl=en-US&gl=US&ceid=US:en"
43
+ req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
44
+ xml = urllib.request.urlopen(req, timeout=20).read().decode("utf-8", "ignore")
45
+ titles = re.findall(r"<item><title>(.*?)</title>", xml)
46
+ dates = re.findall(r"<pubDate>(.*?)</pubDate>", xml)
47
+ return list(zip(titles, dates))
48
+
49
+ cleaned = re.sub(r"\b(what|is|are|the|of|and|today'?s?|date|for|me|tell|about)\b", " ",
50
+ query, flags=re.I)
51
+ candidates = [
52
+ " ".join(cleaned.split())[:80],
53
+ "top news today",
54
+ "breaking news",
55
+ ]
56
+ best = []
57
+ for qs in candidates:
58
+ if not qs.strip():
59
+ continue
60
+ try:
61
+ got = fetch(qs)
62
+ except Exception:
63
+ continue
64
+ if len(got) > len(best):
65
+ best = got
66
+ if len(best) >= limit:
67
+ break
68
+ return "\n".join(
69
+ f"{i+1}. {t} [{d}]" for i, (t, d) in enumerate(best[:limit])
70
+ )
71
+
72
+
73
+ def build_live(prompt):
74
+ block = f"[LIVE CONTEXT - current date & time: {datetime.now()}]\n\n"
75
+ try:
76
+ news = google_news(prompt)
77
+ block += ("Fresh web results (Google News):\n" + news) if news else "No fresh results found."
78
+ except Exception as e:
79
+ block += f"(web search unavailable: {e})"
80
+ block += "\n\nUse this LIVE CONTEXT as ground truth for time-sensitive facts."
81
+ return block
82
+
83
+
84
+ def stream_chat(messages):
85
+ body = json.dumps({
86
+ "model": MODEL,
87
+ "messages": messages,
88
+ "stream": True,
89
+ "options": {"temperature": 0.7, "num_ctx": 8192},
90
+ }).encode()
91
+ req = urllib.request.Request(
92
+ HOST + "/api/chat", data=body, headers={"Content-Type": "application/json"}
93
+ )
94
+ resp = urllib.request.urlopen(req, timeout=600)
95
+ full = []
96
+ dec = json.JSONDecoder()
97
+ buf = ""
98
+ while True:
99
+ chunk = resp.read(1)
100
+ if not chunk:
101
+ break
102
+ buf += chunk.decode("utf-8", "ignore")
103
+ while "\n" in buf:
104
+ line, buf = buf.split("\n", 1)
105
+ line = line.strip()
106
+ if not line:
107
+ continue
108
+ try:
109
+ obj = dec.raw_decode(line)[0]
110
+ except Exception:
111
+ continue
112
+ tok = obj.get("message", {}).get("content", "")
113
+ if tok:
114
+ full.append(tok)
115
+ print(tok, end="", flush=True)
116
+ if obj.get("done"):
117
+ print()
118
+ return "".join(full)
119
+ print()
120
+ return "".join(full)
121
+
122
+
123
+ def answer(prompt, history):
124
+ msgs = [{"role": "system", "content": SYSTEM}]
125
+ if LIVE_RE.search(prompt):
126
+ print("[searching the web...]", file=sys.stderr, flush=True)
127
+ msgs.append({"role": "system", "content": build_live(prompt)})
128
+ msgs += history + [{"role": "user", "content": prompt}]
129
+ reply = stream_chat(msgs)
130
+ history.extend([
131
+ {"role": "user", "content": prompt},
132
+ {"role": "assistant", "content": reply},
133
+ ])
134
+ if len(history) > 24:
135
+ del history[:-24]
136
+
137
+
138
+ def main():
139
+ args = sys.argv[1:]
140
+ if args:
141
+ answer(" ".join(args), [])
142
+ return
143
+ print(f"MORPH-AI Cesium2 terminal 路 model={MODEL} 路 /new reset 路 /exit quit")
144
+ history = []
145
+ while True:
146
+ try:
147
+ prompt = input("\nyou > ").strip()
148
+ except (EOFError, KeyboardInterrupt):
149
+ print()
150
+ break
151
+ if not prompt:
152
+ continue
153
+ if prompt.lower() in ("/exit", "/quit"):
154
+ break
155
+ if prompt.lower() == "/new":
156
+ history.clear()
157
+ print("[conversation cleared]")
158
+ continue
159
+ try:
160
+ answer(prompt, history)
161
+ except Exception as e:
162
+ msg = str(e)
163
+ if "ConnectionRefused" in msg or "URLError" in msg:
164
+ msg = f"cannot reach Ollama at {HOST} - start it first ('ollama serve')"
165
+ print(f"\n[error] {msg}", file=sys.stderr)
166
+
167
+
168
+ if __name__ == "__main__":
169
+ main()