You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
AI is pretty bad at Math but Python is good at it. So let's make it a Function Calling.
Code
importast# To parse the expresion to an ASTimportmath# To embed in execution context of the equationfrominstructorimportOpenAISchema# Required for SGPT Function Calling definitionfrompydanticimportField# Required for SGPT Function Callings argument definitionclassFunction(OpenAISchema):
""" Resolve a Mathematical expresion with Python. Only functions in the math module are allowed. Do not use other module. """expression: str=Field(
...,
example="10 + 0x2c * sqrt(25) - 8",
description="Matematical equation to solve",
)
format_output: str=Field(
None,
example=".4e",
description="Optional Python integer format for the output (e.g., '.4e' for scientific notation)"
)
classConfig:
title="solve_mathematical_equation"@classmethoddefexecute(cls, expression: str, format_output: str=None) ->str:
try:
parsed=ast.parse(expression, mode='eval')
fornodeinast.walk(parsed):
ifisinstance(node, ast.Call):
ifnotisinstance(node.func, ast.Name) ornode.func.idnotindir(math):
returnf"Error: Failed to solve equation {expression}: Invalid function used {node.func}"code=compile(parsed, filename='', mode='eval')
result=eval(
code,
{'__builtins__': math}, # GlobalsNone# Locals
)
ifformat_output:
result=format(result, format_output)
returnstr(result)
exceptExceptionase:
returnstr(result)
exceptExceptionase:
returnf"Error: Failled to solve equation {expression}: {e}"
Example
sgpt "10 + 0x2c * sqrt(25) - 8"
@FunctionCall solve_mathematical_equation(expression="10 + 0x2c * sqrt(25) - 8")
222.0
The result of the expression (10 + 0x2c \times \sqrt{25} - 8) is (222.0).
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
AI is pretty bad at Math but Python is good at it. So let's make it a Function Calling.
Code
Example
Beta Was this translation helpful? Give feedback.
All reactions