A robust Python library for parsing and executing nested mathematical function calls from Large Language Model (LLM) outputs. Designed specifically for financial analysis and mathematical computations where models need to perform complex calculations without hallucination.
Large Language Models often hallucinate when performing mathematical calculations, especially after function calls. This library prevents hallucination by:
- Static Parsing: Executes only the first valid function call found
- Immediate Results: Returns numerical results immediately without allowing continued generation
- Nested Support: Handles complex nested function expressions
- Error Prevention: Robust error handling for malformed expressions
- Nested Function Calls: Support for complex expressions like
add(multiply(2, 3), divide(8, 2)) - Mathematical Functions: Comprehensive set of mathematical and statistical functions
- Pattern Recognition: Intelligent extraction of function calls from natural language
- Type Safety: Full type hints and comprehensive error handling
- Zero Dependencies: Only uses Python standard library
git clone https://github.com/your-username/static-function-parser.git
cd static-function-parserNo additional dependencies required - uses only Python standard library.
from static_function_parser import StaticFunctionParser
# Initialize parser
parser = StaticFunctionParser()
# Parse model output containing function calls
model_output = """
To calculate the total revenue, I need to multiply price by quantity and add the bonus.
FUNCTION: add(multiply(25, 4), 100)
This gives us the final answer.
"""
# Execute and get result
result = parser.execute_from_text(model_output)
print(result['result']) # Output: 200.0add(a, b, ...)- Addition of multiple numberssubtract(a, b)- Subtraction (a - b)multiply(a, b, ...)- Multiplication of multiple numbersdivide(a, b)- Division (a / b)
average(a, b, ...)- Arithmetic meansum(a, b, ...)- Sum of multiple numbersmax(a, b, ...)- Maximum valuemin(a, b, ...)- Minimum value
percentage(part, whole)- Calculate percentagepercentage_change(old, new)- Calculate percentage changeratio(a, b)- Calculate ratio a:b
round(number, decimals)- Round to specified decimal places
parser = StaticFunctionParser()
result = parser.execute_from_text("FUNCTION: add(10, 20)")
print(result['result']) # 30.0result = parser.execute_from_text("FUNCTION: percentage(multiply(3, 4), 60)")
print(result['result']) # 20.0 (12 is 20% of 60)# Calculate percentage change in revenue
text = "FUNCTION: percentage_change(add(100, 50), multiply(200, 0.8))"
result = parser.execute_from_text(text)
print(result['result']) # -6.25 (percentage change from 150 to 160)model_response = """
Based on the financial data, I need to calculate the growth rate.
The revenue increased from $1M to $1.2M.
FUNCTION: percentage_change(1000000, 1200000)
Therefore, the growth rate is 20%.
"""
result = parser.execute_from_text(model_response)
print(result['result']) # 20.0Main method to parse and execute function calls from text.
Parameters:
text: Input text containing function callsverbose: Enable debug output (default: False)
Returns: Dictionary with:
success: Boolean indicating success/failureresult: Numerical result (if successful)function_call: Extracted function call stringerror: Error message (if failed)
Returns list of all available function names.
Creates a prompt template for LLMs to generate proper function calls.
Run the built-in tests:
python static_function_parser.pyThis will run comprehensive tests covering:
- Basic arithmetic operations
- Nested function calls
- Error handling
- Natural language extraction
static-function-parser/
βββ static_function_parser.py # Main parser implementation
βββ README.md # This file
βββ requirements.txt # Dependencies (none currently)
βββ examples/ # Usage examples
To add a new mathematical function:
- Add the function to the
functionsdictionary in__init__ - Implement the function with prefix
_function_name - Add appropriate error handling
- Update documentation
Example:
def __init__(self):
self.functions = {
# ... existing functions ...
"power": self._power,
}
def _power(self, base, exponent) -> float:
"""Calculate base raised to the power of exponent."""
return float(base) ** float(exponent)- Revenue calculations with multiple components
- Percentage change analysis
- Ratio calculations for financial metrics
- Statistical analysis of financial data
- Mathematical expression evaluation
- Step-by-step calculation verification
- Safe execution of student-generated expressions
- Preventing mathematical hallucination
- Standardizing numerical outputs
- Enabling reliable quantitative reasoning
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Developed for CS221 Project on LLM Mathematical Reasoning
- Inspired by the need for reliable mathematical computation in AI systems
- Built to solve hallucination problems in financial analysis applications
This library addresses the hallucination problem identified in:
- LLM mathematical reasoning research
- Financial AI applications
- Tool-augmented language models
For academic use, please cite:
@misc{static-function-parser,
title={Static Function Parser for LLM Mathematical Reasoning},
author={CS221 Project Team},
year={2024},
url={https://github.com/your-username/static-function-parser}
}