"""Sentinel-7B-Tools (Sentovara): answer one request, letting the model call its built-in tools and reading the results back.
The model is allenai/Olmo-3-7B-Instruct with Sentovara's tools add-on folded into the weights (no add-on to load).
Tools (all plain Python in this folder, no internet): Sudoku solver, calculator, date maths, Caesar / Base64 decoders
(sa5_tools.py), money maths - interest, loans, percentages, statistics (money_tools.py), UK tax - VAT, stamp duty, income tax,
National Insurance, corporation tax, rates lookup (tax_tools.py + tax_rates.json).
Needs: torch, transformers (tested with 5.22.1). Usage: python run.py "How many days are there between 2024-03-01 and 2025-01-17?"
You can also pass your own tools in Olmo's tool format; the model only calls a tool when one fits the question."""
import ast, json, os, re, sys
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)
import sa5_tools, money_tools, tax_tools
MODEL = os.environ.get("SENTINEL_MODEL", "Sentovara/Sentinel-7B-Tools")
ALL_TOOLS = sa5_tools.TOOLS + money_tools.MONEY_TOOLS + tax_tools.TAX_TOOLS
_STR = re.compile(r'"(?:\\.|[^"\\])*"')
def _pyfy(s): # JSON literals -> Python literals, outside strings only
parts, last = [], 0
fix = lambda x: re.sub(r"\btrue\b", "True", re.sub(r"\bfalse\b", "False", re.sub(r"\bnull\b", "None", x)))
for m in _STR.finditer(s): parts.append(fix(s[last:m.start()])); parts.append(m.group(0)); last = m.end()
parts.append(fix(s[last:])); return "".join(parts)
def parse_calls(text):
"""Olmo-3 calls look like \nname(key=value, ...)\n, one call per line."""
out = []
for blk in re.findall(r"(.*?)", text, re.S):
for line in [x.strip() for x in blk.strip().splitlines() if x.strip()]:
try:
node = ast.parse(_pyfy(line), mode="eval").body
out.append({"name": node.func.id, "arguments": {k.arg: ast.literal_eval(k.value) for k in node.keywords}})
except Exception: out.append({"name": "", "arguments": {}})
return out
def run_tool(name, args):
try:
if name in tax_tools.FUNCS: return str(tax_tools.FUNCS[name](**args))
if name in money_tools.FUNCS: return str(money_tools.FUNCS[name](**args))
return str(sa5_tools.run(name, args))
except Exception as ex: return f"error: {ex}"
class Sentinel:
def __init__(self, model=MODEL, device=None):
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
self.tok = AutoTokenizer.from_pretrained(model)
self.model = AutoModelForCausalLM.from_pretrained(model, dtype=torch.bfloat16 if self.device == "cuda" else torch.float32).to(self.device).eval()
def _gen(self, msgs, tools, max_new_tokens):
p = self.tok.apply_chat_template(msgs, tools=tools, tokenize=False, add_generation_prompt=True)
ids = self.tok(p, return_tensors="pt", add_special_tokens=False).to(self.device)
with torch.no_grad(): o = self.model.generate(**ids, max_new_tokens=max_new_tokens, do_sample=False)
return self.tok.decode(o[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()
def answer(self, messages, tools=None, max_new_tokens=1024):
"""messages: chat messages. tools: tool list (default: the built-in tools). Returns (reply, tool calls made)."""
tools = ALL_TOOLS if tools is None else tools
conv, calls = list(messages), []
for _ in range(3): # call tools, read results, answer (at most 3 rounds)
t = self._gen(conv, tools, max_new_tokens); cs = parse_calls(t)
if not cs: return t, calls
conv.append({"role": "assistant", "content": t}); res = []
for c in cs:
r = run_tool(c["name"], c["arguments"]); calls.append({**c, "result": r}); res.append(r)
conv.append({"role": "tool", "content": "\n".join(res)}) # the chat template shows tool results as "environment"
return t, calls
if __name__ == "__main__":
q = " ".join(sys.argv[1:]) or "What day of the week was 2024-02-29?"
reply, calls = Sentinel().answer([{"role": "user", "content": q}])
for c in calls: print(f"[tool] {c['name']}({json.dumps(c['arguments'])}) -> {c['result']}")
print(reply)