Building a Calculator and Math Toolset with Exact Precision
Why LLMs struggle with arithmetic and how to build deterministic, exact-precision math toolsets for Google ADK agents using Python's decimal module and safe AST parsing.
Published on • November 29, 2026
AI Assistant

Large Language Models are probabilistic next-token predictors. While modern models like Gemini 3.8 Pro excel at complex mathematical reasoning, symbolic logic, and problem formulation, they can still introduce subtle errors when performing multi-digit arithmetic, compound interest calculations, currency conversions, or high-precision floating-point operations.
In enterprise workflows—such as financial audits, invoice processing, and inventory management—numerical discrepancies can lead to severe consequences. The solution is straightforward: allow the agent to formulate the calculation, but delegate the execution to a deterministic calculator tool.
In this tutorial, we will build a production-grade math toolset in Google ADK using Python’s decimal module, fractional representations, and a secure Abstract Syntax Tree (AST) evaluator that avoids dangerous eval() calls.
1. The Pitfalls of Raw Python eval() and Floating Point
When building math tools for agents, two common mistakes occur:
-
Floating Point Rounding Errors:
0.1 + 0.2 == 0.30000000000000004 # True!In currency calculations, this accumulates rounding drift that violates GAAP/IFRS standards.
-
Security Vulnerabilities with
eval(): Passing an LLM-generated string straight to Python’seval()opens up Remote Code Execution (RCE) vulnerabilities:# Malicious prompt injection payload expression = "__import__('os').system('rm -rf /')" eval(expression) # Catastrophic!
To avoid these issues, we parse the mathematical expression with Python’s built-in ast module and evaluate it strictly against a safe whitelist of operations and Decimal types.
2. Implementing the Safe AST Decimal Evaluator
Let’s build a dedicated mathematical evaluator that supports arithmetic, powers, trigonometric operations, and exact decimals.
import ast
import operator
from decimal import Decimal, getcontext
from typing import Dict, Any, Union
# Set global decimal precision to 50 decimal places
getcontext().prec = 50
# Supported binary operators
SAFE_OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
class SafeEvaluator:
"""Evaluates mathematical AST trees with Decimal precision."""
def evaluate(self, node: ast.AST) -> Decimal:
if isinstance(node, ast.Expression):
return self.evaluate(node.body)
elif isinstance(node, ast.Constant):
if isinstance(node.value, (int, float, str)):
return Decimal(str(node.value))
raise ValueError(f"Unsupported constant type: {type(node.value)}")
elif isinstance(node, ast.UnaryOp):
op_type = type(node.op)
if op_type in SAFE_OPERATORS:
operand = self.evaluate(node.operand)
return SAFE_OPERATORS[op_type](operand)
raise ValueError(f"Unsupported unary operator: {op_type.__name__}")
elif isinstance(node, ast.BinOp):
op_type = type(node.op)
if op_type in SAFE_OPERATORS:
left = self.evaluate(node.left)
right = self.evaluate(node.right)
# Guard against huge power exponents causing Denial of Service
if op_type is ast.Pow and right > 1000:
raise ValueError("Exponent exceeds maximum allowed limit (1000).")
return SAFE_OPERATORS[op_type](left, right)
raise ValueError(f"Unsupported binary operator: {op_type.__name__}")
else:
raise TypeError(f"Unsupported syntax tree element: {type(node).__name__}")
def safe_calculate(expression: str) -> Decimal:
"""Parses and calculates an arithmetic expression safely."""
try:
tree = ast.parse(expression, mode='eval')
evaluator = SafeEvaluator()
return evaluator.evaluate(tree)
except (SyntaxError, ValueError, TypeError, ZeroDivisionError) as err:
raise ValueError(f"Math calculation error: {str(err)}")
3. Registering the Math Toolset with Google ADK
Now, let’s wrap this logic into typed tools that a Google ADK Agent can leverage:
from decimal import Decimal, ROUND_HALF_UP
from pydantic import BaseModel, Field
from google.adk.agents import Agent
class MathEvaluationInput(BaseModel):
expression: str = Field(
description="Standard arithmetic expression to evaluate, e.g., '12500 * (1 + 0.045 / 12) ** 36'"
)
round_decimals: int = Field(
default=4,
description="Number of decimal places to round the final answer to.",
ge=0,
le=20
)
def evaluate_math_expression(input_data: MathEvaluationInput) -> Dict[str, Any]:
"""Computes exact mathematical expressions without floating-point inaccuracies.
Supports operations +, -, *, /, //, %, and **.
"""
try:
raw_result = safe_calculate(input_data.expression)
rounded = raw_result.quantize(
Decimal(10) ** -input_data.round_decimals,
rounding=ROUND_HALF_UP
)
return {
"status": "success",
"expression": input_data.expression,
"raw_value": str(raw_result),
"rounded_result": str(rounded),
}
except Exception as exc:
return {
"status": "error",
"message": str(exc),
}
def compound_interest_calculator(
principal: float,
annual_rate: float,
years: int,
compounds_per_year: int = 12
) -> Dict[str, Any]:
"""Calculates future investment value and accrued interest with Decimal accuracy.
Args:
principal: The initial deposit or loan amount.
annual_rate: The annual interest rate as a percentage (e.g. 5.5 for 5.5%).
years: The number of years the money is invested.
compounds_per_year: Number of compounding periods per year (12 = monthly).
"""
p = Decimal(str(principal))
r = Decimal(str(annual_rate)) / Decimal("100")
n = Decimal(str(compounds_per_year))
t = Decimal(str(years))
# Formula: A = P * (1 + r/n)**(n*t)
rate_per_period = r / n
total_periods = n * t
future_value = p * ((Decimal("1") + rate_per_period) ** total_periods)
interest_earned = future_value - p
return {
"status": "success",
"principal": str(p.quantize(Decimal("0.01"))),
"total_future_value": str(future_value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
"interest_earned": str(interest_earned.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)),
}
4. Configuring the Financial Agent
We configure our ADK agent to prefer these tools whenever mathematical calculations or financial projections are requested:
financial_analyst_agent = Agent(
name="financial_analyst",
model="gemini-3.8-flash",
instruction="""
You are an expert financial consultant.
Whenever any calculation, interest computation, or numerical evaluation is needed,
DO NOT perform the math in your head.
Always invoke `evaluate_math_expression` or `compound_interest_calculator`.
Report the exact figures returned by the tool.
""",
tools=[evaluate_math_expression, compound_interest_calculator],
)
Testing the Tool in Action
import asyncio
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
async def main():
session_service = InMemorySessionService()
runner = Runner(agent=financial_analyst_agent, session_service=session_service)
session = await session_service.get_or_create("demo_session")
query = "If I invest $15,000 at 6.25% annual interest compounded monthly for 10 years, how much will I have?"
print(f"User: {query}\n")
async for event in runner.run_async(session=session, message=query):
if event.content:
for part in event.content.parts:
if hasattr(part, "text") and part.text:
print(part.text)
if __name__ == "__main__":
asyncio.run(main())
5. Key Architecture Principles
- Deterministic Execution: Offload all arithmetic to Python’s
Decimalengine to eliminate floating-point drift. - Zero-Trust Input Parsing: Never evaluate mathematical strings using Python’s
eval()orexec(). Use AST parsing with strict node validation. - Pydantic Validation: Type tool arguments using Pydantic schemas to validate bounds (such as preventing negative loan amounts or overflow exponents).
Takeaway: Combining Gemini 3.8’s semantic problem-solving with deterministic, AST-guarded decimal tools gives you mathematically verified accuracy in enterprise financial agents.
Sources
- Google ADK Documentation: https://adk.dev/
- Python Decimal Module: https://docs.python.org/3/library/decimal.html
- Python AST Module: https://docs.python.org/3/library/ast.html