import reimport ioimport contextlib math_sys = ( "You are a quantitative financial assistant. For any calculation, write a <python>...</python> block, " "read the exact <output>...</output>, and state the final answer.") def ask_with_python_tool(question, show_code=False): messages = [ {"role": "system", "content": math_sys}, {"role": "user", "content": question}, ] prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tokenizer(prompt, return_tensors="pt").to("cuda") # Pass 1: Generate <python> block with torch.no_grad(): out1 = model.generate( **inputs, max_new_tokens=160, do_sample=False, pad_token_id=tokenizer.eos_token_id ) reply1 = tokenizer.decode(out1[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True) match = re.search(r"<python>(.*?)</python>", reply1, re.DOTALL) if not match: return reply1.strip() # Execute Python safely in a restricted namespace code = match.group(1).strip() buf = io.StringIO() safe_builtins = {"round": round, "print": print, "abs": abs, "min": min, "max": max, "sum": sum, "pow": pow} try: with contextlib.redirect_stdout(buf): exec(code, {"__builtins__": safe_builtins}) real_output = buf.getvalue().strip() except Exception as e: real_output = f"Error: {e}" # Pass 2: Inject verified <output> and generate final answer continued_prompt = f"{prompt}<python>\n{code}\n</python>\n<output>\n{real_output}\n</output>\n" inputs2 = tokenizer(continued_prompt, return_tensors="pt").to("cuda") with torch.no_grad(): out2 = model.generate( **inputs2, max_new_tokens=80, do_sample=False, pad_token_id=tokenizer.eos_token_id ) final_answer = tokenizer.decode(out2[0][inputs2["input_ids"].shape[1]:], skip_special_tokens=True).strip() if show_code: return f"[Executed Python]\n{code}\n\n[Real Output]: {real_output}\n\n[Final Answer]: {final_answer}" return final_answer q = "Apex Corp reported revenue of $1,347.8M last year and $1,612.4M this year. Calculate the YoY revenue growth rate (%)."print(ask_with_python_tool(q, show_code=False))