atomzero 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- atomzero/__init__.py +8 -0
- atomzero/agent_runtime.py +225 -0
- atomzero/chat_human.py +486 -0
- atomzero/chat_server.py +2494 -0
- atomzero/curiosity.py +66 -0
- atomzero/doc_ingest.py +312 -0
- atomzero/doc_memory.py +1112 -0
- atomzero/feedback.py +188 -0
- atomzero/knowledge_gaps.py +157 -0
- atomzero/lora.py +140 -0
- atomzero/ml_safety.py +165 -0
- atomzero/neural_embedder.py +108 -0
- atomzero/research_queue.py +330 -0
- atomzero/safety.py +226 -0
- atomzero/teacher_notes.py +78 -0
- atomzero/teacher_provider.py +104 -0
- atomzero/tool_planner.py +207 -0
- atomzero/transformer.py +102 -0
- atomzero/web_research.py +165 -0
- atomzero-0.1.0.dist-info/METADATA +96 -0
- atomzero-0.1.0.dist-info/RECORD +26 -0
- atomzero-0.1.0.dist-info/WHEEL +5 -0
- atomzero-0.1.0.dist-info/entry_points.txt +2 -0
- atomzero-0.1.0.dist-info/licenses/LICENSE +202 -0
- atomzero-0.1.0.dist-info/licenses/NOTICE +24 -0
- atomzero-0.1.0.dist-info/top_level.txt +1 -0
atomzero/__init__.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Session-based agent runtime around the tiny model and local tools."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import ast
|
|
5
|
+
import operator
|
|
6
|
+
import re
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from atomzero.doc_memory import add_citation_source, format_citation
|
|
11
|
+
from atomzero.knowledge_gaps import KnowledgeGapError
|
|
12
|
+
from atomzero.web_research import wikipedia_research
|
|
13
|
+
|
|
14
|
+
from atomzero.chat_human import ChatHuman
|
|
15
|
+
|
|
16
|
+
_BIN_OPS = {
|
|
17
|
+
ast.Add: operator.add,
|
|
18
|
+
ast.Sub: operator.sub,
|
|
19
|
+
ast.Mult: operator.mul,
|
|
20
|
+
ast.Div: operator.truediv,
|
|
21
|
+
ast.FloorDiv: operator.floordiv,
|
|
22
|
+
ast.Mod: operator.mod,
|
|
23
|
+
ast.Pow: operator.pow,
|
|
24
|
+
}
|
|
25
|
+
_UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg}
|
|
26
|
+
_MATH_PREFIX = re.compile(
|
|
27
|
+
r"^(?:what\s+is|what's|calculate|compute|calc)\s+", re.IGNORECASE)
|
|
28
|
+
_MATH_CHARS = re.compile(r"[0-9+\-*/().%\s]+")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _eval_math(node):
|
|
32
|
+
if isinstance(node, ast.Expression):
|
|
33
|
+
return _eval_math(node.body)
|
|
34
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
|
35
|
+
return node.value
|
|
36
|
+
if isinstance(node, ast.BinOp) and type(node.op) in _BIN_OPS:
|
|
37
|
+
left = _eval_math(node.left)
|
|
38
|
+
right = _eval_math(node.right)
|
|
39
|
+
if isinstance(node.op, ast.Pow) and (abs(left) > 1e6 or abs(right) > 100):
|
|
40
|
+
raise ValueError("exponent is too large")
|
|
41
|
+
value = _BIN_OPS[type(node.op)](left, right)
|
|
42
|
+
if abs(value) > 10**12:
|
|
43
|
+
raise ValueError("result is too large")
|
|
44
|
+
return value
|
|
45
|
+
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPS:
|
|
46
|
+
return _UNARY_OPS[type(node.op)](_eval_math(node.operand))
|
|
47
|
+
raise ValueError("unsupported expression")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def calculate(expression: str) -> str:
|
|
51
|
+
"""Evaluate a small arithmetic expression without eval()."""
|
|
52
|
+
expr = expression.strip().rstrip("=?").strip()
|
|
53
|
+
if not expr or len(expr) > 80:
|
|
54
|
+
raise ValueError("invalid expression")
|
|
55
|
+
if not _MATH_CHARS.fullmatch(expr):
|
|
56
|
+
raise ValueError("only numbers and + - * / % ** are allowed")
|
|
57
|
+
value = _eval_math(ast.parse(expr, mode="eval"))
|
|
58
|
+
if isinstance(value, float) and value.is_integer():
|
|
59
|
+
value = int(value)
|
|
60
|
+
return str(value)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def math_query(text: str) -> str | None:
|
|
64
|
+
candidate = _MATH_PREFIX.sub("", text.strip()).strip()
|
|
65
|
+
candidate = candidate.rstrip("=?").strip()
|
|
66
|
+
if not candidate or not re.search(r"\d", candidate):
|
|
67
|
+
return None
|
|
68
|
+
if not _MATH_CHARS.fullmatch(candidate):
|
|
69
|
+
return None
|
|
70
|
+
if not re.search(r"[+\-*/%]", candidate):
|
|
71
|
+
return None
|
|
72
|
+
return candidate
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AgentSession:
|
|
76
|
+
def __init__(self, session_id: str, memory_path: str | Path,
|
|
77
|
+
model=None, tokenizer=None, device=None, docs=None,
|
|
78
|
+
wiki_lang: str = "en", gap_store=None, safety=None,
|
|
79
|
+
generator=None, allow_general_chat=False):
|
|
80
|
+
if not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", session_id):
|
|
81
|
+
raise ValueError("invalid session id")
|
|
82
|
+
self.id = session_id
|
|
83
|
+
self.docs = docs
|
|
84
|
+
self.wiki_lang = wiki_lang
|
|
85
|
+
self.gap_store = gap_store
|
|
86
|
+
self.safety = safety
|
|
87
|
+
self.human = ChatHuman(memory_path, model, tokenizer, device,
|
|
88
|
+
"transformer", docs, on_gap=self._record_gap,
|
|
89
|
+
generator=generator,
|
|
90
|
+
allow_general_chat=allow_general_chat)
|
|
91
|
+
|
|
92
|
+
def _record_gap(self, text: str) -> None:
|
|
93
|
+
if self.gap_store is None:
|
|
94
|
+
return
|
|
95
|
+
try:
|
|
96
|
+
self.gap_store.add(text, session_id=self.id)
|
|
97
|
+
except (KnowledgeGapError, OSError):
|
|
98
|
+
pass
|
|
99
|
+
|
|
100
|
+
def forget(self, text: str = "") -> dict:
|
|
101
|
+
"""Delete matching session memory, or all of it when text is empty."""
|
|
102
|
+
return self.human.forget(text)
|
|
103
|
+
|
|
104
|
+
def export_memory(self) -> dict:
|
|
105
|
+
return self.human.export_memory()
|
|
106
|
+
|
|
107
|
+
def import_memory(self, data: dict) -> dict:
|
|
108
|
+
return self.human.import_memory(data)
|
|
109
|
+
|
|
110
|
+
def _research(self, query: str, limit: int = 2) -> dict:
|
|
111
|
+
if self.docs is None:
|
|
112
|
+
raise ValueError("no document memory configured")
|
|
113
|
+
pages = wikipedia_research(self.docs, query, self.wiki_lang, limit)
|
|
114
|
+
if not pages:
|
|
115
|
+
return {"reply": "I could not find a useful page.",
|
|
116
|
+
"tool_calls": [{"name": "research", "query": query}],
|
|
117
|
+
"sources": []}
|
|
118
|
+
lines = "\n".join(
|
|
119
|
+
f"- {p['title']} ({p['source']})" for p in pages)
|
|
120
|
+
return {
|
|
121
|
+
"reply": f"I indexed these pages:\n{lines}\n\n"
|
|
122
|
+
"Ask me about them and I will quote the notes.",
|
|
123
|
+
"tool_calls": [{"name": "research", "query": query}],
|
|
124
|
+
"sources": [{"source": p["source"], "title": p["title"]}
|
|
125
|
+
for p in pages],
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
def _search_docs(self, query: str) -> dict:
|
|
129
|
+
hits = self.docs.search(query, k=3) if self.docs else []
|
|
130
|
+
if not hits:
|
|
131
|
+
return {"reply": "I found no matching local notes.",
|
|
132
|
+
"tool_calls": [{"name": "search_docs", "query": query}],
|
|
133
|
+
"sources": []}
|
|
134
|
+
lines = []
|
|
135
|
+
source_map = {}
|
|
136
|
+
unverified = False
|
|
137
|
+
for hit in hits:
|
|
138
|
+
teacher = hit.get("kind") == "teacher"
|
|
139
|
+
verified = bool(hit.get("verified", True))
|
|
140
|
+
if teacher and not verified:
|
|
141
|
+
label = "teacher note, unverified"
|
|
142
|
+
elif teacher:
|
|
143
|
+
reviewer = str(hit.get("reviewer", "")).strip()
|
|
144
|
+
label = (f"teacher note, verified by {reviewer}"
|
|
145
|
+
if reviewer else "teacher note, verified")
|
|
146
|
+
else:
|
|
147
|
+
label = "source"
|
|
148
|
+
location = format_citation(hit)
|
|
149
|
+
lines.append(f"- {hit['chunk']} ({label}: {location})")
|
|
150
|
+
add_citation_source(source_map, hit)
|
|
151
|
+
if not verified:
|
|
152
|
+
unverified = True
|
|
153
|
+
reply = (f"I found these notes:\n" + "\n".join(lines) + "\n\n"
|
|
154
|
+
"This is a local note, not professional advice.")
|
|
155
|
+
if unverified:
|
|
156
|
+
reply += "\n\nThis includes an unverified teacher-derived note."
|
|
157
|
+
return {
|
|
158
|
+
"reply": reply,
|
|
159
|
+
"tool_calls": [{"name": "search_docs", "query": query}],
|
|
160
|
+
"sources": list(source_map.values()),
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
def chat(self, text: str) -> dict:
|
|
164
|
+
if self.safety is not None:
|
|
165
|
+
verdict = self.safety.check(text)
|
|
166
|
+
if verdict is not None:
|
|
167
|
+
return {
|
|
168
|
+
"reply": self.safety.refusal(verdict["category"]),
|
|
169
|
+
"tool_calls": [], "sources": [], "safety": verdict,
|
|
170
|
+
}
|
|
171
|
+
result = self._chat(text)
|
|
172
|
+
if self.safety is not None:
|
|
173
|
+
safe, verdict = self.safety.filter_reply(
|
|
174
|
+
result.get("reply", ""))
|
|
175
|
+
if verdict is not None:
|
|
176
|
+
result = {**result, "reply": safe, "safety": verdict}
|
|
177
|
+
return result
|
|
178
|
+
|
|
179
|
+
def _chat(self, text: str) -> dict:
|
|
180
|
+
low = text.lower().strip()
|
|
181
|
+
if low in ("what time is it", "what time is it?", "time"):
|
|
182
|
+
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
183
|
+
return {"reply": f"It is {now}.", "tool_calls": [
|
|
184
|
+
{"name": "time"}], "sources": []}
|
|
185
|
+
if low in ("what can you do", "what can you do?", "help"):
|
|
186
|
+
return {
|
|
187
|
+
"reply": ("I can keep short personal notes, manage tasks, "
|
|
188
|
+
"search your local documents, look up Wikipedia "
|
|
189
|
+
"with sources, calculate simple arithmetic, and "
|
|
190
|
+
"tell the time. I am a small local model, so I am "
|
|
191
|
+
"not a general reasoning or coding assistant."),
|
|
192
|
+
"tool_calls": [{"name": "help"}], "sources": [],
|
|
193
|
+
}
|
|
194
|
+
expression = math_query(text)
|
|
195
|
+
if expression is not None:
|
|
196
|
+
try:
|
|
197
|
+
result = calculate(expression)
|
|
198
|
+
except (ValueError, SyntaxError, ZeroDivisionError,
|
|
199
|
+
OverflowError) as exc:
|
|
200
|
+
return {
|
|
201
|
+
"reply": f"I could not calculate that: {exc}.",
|
|
202
|
+
"tool_calls": [{"name": "calculator",
|
|
203
|
+
"expression": expression}],
|
|
204
|
+
"sources": [],
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
"reply": f"{expression} = {result}",
|
|
208
|
+
"tool_calls": [{"name": "calculator",
|
|
209
|
+
"expression": expression,
|
|
210
|
+
"result": result}],
|
|
211
|
+
"sources": [],
|
|
212
|
+
}
|
|
213
|
+
research = re.match(
|
|
214
|
+
r"^(?:research|look up|search the web for|web search)\s*:?\s*(.+)$",
|
|
215
|
+
text, re.IGNORECASE)
|
|
216
|
+
if research:
|
|
217
|
+
return self._research(research.group(1).strip())
|
|
218
|
+
if (low.startswith("search docs ") or low.startswith("search my notes ")
|
|
219
|
+
or low.startswith("search documents ")):
|
|
220
|
+
query = re.sub(r"^search (docs|my notes|documents)\s*:?\s*", "",
|
|
221
|
+
text, flags=re.IGNORECASE)
|
|
222
|
+
return self._search_docs(query)
|
|
223
|
+
reply = self.human.respond(text)
|
|
224
|
+
return {"reply": reply, "tool_calls": [],
|
|
225
|
+
"sources": list(getattr(self.human, "last_sources", []))}
|