import reimport mathimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLM model_path = "pvlabs/Hlupak-2-13M-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_path)model = AutoModelForCausalLM.from_pretrained(model_path, dtype=torch.float16)model.eval()END = [tokenizer.convert_tokens_to_ids("<|end|>"), tokenizer.convert_tokens_to_ids("<|end_of_text|>")] def calc(expr): # numbers, + - * / ^ ( ) and sqrt() only if not re.fullmatch(r"(sqrt|[\d.+\-*/^() ])+", expr): return "Error: bad expression." v = eval(expr.replace("^", "**").replace("sqrt", "math.sqrt"), {"__builtins__": {}, "math": math}) return str(int(v)) if v == int(v) else f"{v:.6f}".rstrip("0") def search(query): # plug in a real search here; the model expects up to 3 numbered results return "[1] Paris: Paris is the capital and largest city of France." def reply(chat): """chat: the conversation so far as one string, ending with <|assistant|>""" for _ in range(3): # at most 2 tool calls per reply inputs = tokenizer(chat, return_tensors="pt", add_special_tokens=False) with torch.no_grad(): out = model.generate(**inputs, max_new_tokens=200, do_sample=True, temperature=0.5, top_k=40, top_p=0.9, eos_token_id=END, pad_token_id=tokenizer.pad_token_id) text = tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=False) text = text.replace("<|end_of_text|>", "<|end|>") chat += text if text.endswith("<|end|>") else text + "<|end|>" call = re.search(r'<\|tool_call\|>(search|calc)\("(.*?)"\)', text) if not call: return chat result = calc(call[2]) if call[1] == "calc" else search(call[2]) chat += f"<|tool_result|>{result}<|end|><|assistant|>" return chat chat = reply("<|user|>whats the square root of 16<|end|><|assistant|>")chat = reply(chat + "<|user|>and of 64<|end|><|assistant|>")print(chat)