"""Aurelis 2B with transformers: the same prompt and probabilities as Ollama's /v1/systemone endpoint. from aurelis import Aurelis decide = Aurelis("MrScratchcat/Aurelis-2B") decide("Customer: my card was charged twice for one order.", {"route": {"type": "choice", "instructions": "Which team handles this?", "criteria": {"billing": "Billing", "technical": "Technical support", "account": "Account"}}, "urgent": {"type": "noul", "instructions": "Is this urgent?"}}) # {"route": {"type": "choice", "choice": "billing", "probabilities": {...}}, "urgent": {"type": "noul", "noul": 0.71}} Each question is its own forward pass over one JSON prompt {"state", "question", "options"}, answered with the option's letter; the probability of an option is the softmax over the option letters at the answer position. A `noul` question is No (A) / Yes (B) and returns the probability of yes. At most 24 options per question, as in Ollama. """ import json import torch LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" PREFIX, SUFFIX = "<|im_start|>user\n", "<|im_end|>\n<|im_start|>assistant\n\n\n\n\n" def _text(x): return x if isinstance(x, str) else json.dumps(x, separators=(",", ":"), ensure_ascii=False) class Aurelis: def __init__(self, repo="MrScratchcat/Aurelis-2B", device=None, dtype=torch.bfloat16): from transformers import AutoModelForCausalLM, AutoTokenizer self.tok = AutoTokenizer.from_pretrained(repo) device = device or ("cuda" if torch.cuda.is_available() else "cpu") self.model = AutoModelForCausalLM.from_pretrained(repo, dtype=dtype).to(device).eval() enc = lambda t: self.tok(t, add_special_tokens=False)["input_ids"] base = enc(PREFIX + "x" + SUFFIX) self.letters = [] for L in LETTERS: # the token each letter becomes right after the assistant prefix ids = enc(PREFIX + "x" + SUFFIX + L) if len(ids) != len(base) + 1 or ids[:len(base)] != base: raise RuntimeError(f"letter {L} is not one token after the prompt") self.letters.append(ids[-1]) @staticmethod def prompt(state, question, pairs): state = "(no state)" if state is None or (isinstance(state, str) and not state.strip()) or state in ({}, []) else _text(state) options = [{"label": LETTERS[i], "key": k, "description": d} for i, (k, d) in enumerate(pairs)] return PREFIX + json.dumps({"state": state, "question": _text(question), "options": options}, ensure_ascii=False) + SUFFIX @torch.no_grad() def __call__(self, state, questions): out = {} for name, q in questions.items(): if q["type"] == "noul": pairs = [("false", "No"), ("true", "Yes")] else: pairs = [(k, k if d is None or (isinstance(d, str) and not d.strip()) else _text(d)) for k, d in q["criteria"].items()] if len(pairs) > 24: raise ValueError(f"{name}: at most 24 options per question") question = q.get("instructions") question = name if question is None or (isinstance(question, str) and not question.strip()) else question ids = self.tok(self.prompt(state, question, pairs), return_tensors="pt", add_special_tokens=False)["input_ids"].to(self.model.device) logits = self.model(input_ids=ids, logits_to_keep=1).logits[0, -1, self.letters[:len(pairs)]].float() p = torch.softmax(logits, -1).tolist() if q["type"] == "noul": out[name] = {"type": "noul", "noul": p[1]} else: probs = {k: v for (k, _), v in zip(pairs, p)} out[name] = {"type": "choice", "choice": max(probs, key=probs.get), "probabilities": probs} return out