How in python to create an math equation evaluator agent
This python code demonstrates the power of agents to use tools too do work. I used the pydantic pattern to create a class called CalculatorSchema which I use to define my schema. I then unpack the dictionary into the class schema and call the ai agent with the schema. This feature is a lifesaver. It sets the pattern for building complex tool agents in the future. the calculator is defined as a tool for the agent to use. Agent programming is the next big thing in ai. The key is to build an useful set of tools that can do real work. genuine-friend. I can now build an app where you input a function y=f(x) as a parameter to an agent and it will give me a list of values that I can plot. My strategy is to build the idea in python then migrate the idea to c# on the backend and flutter for the mobile app. (genuine-friend.com)
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI,OpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.agents import tool, AgentType, Tool,initialize_agent,load_tools
from langchain.memory import ConversationBufferMemory
SystemMessagePromptTemplate,HumanMessagePromptTemplate
from py_expression_eval import Parser
from pydantic import ValidationError
from pydantic import BaseModel, ValidationError
parser = Parser()
class CalculatorSchema(BaseModel):
formula: str
x: str
#@tool
def calculator(data:CalculatorSchema):
""" Evaluates a mathematical formula using the provided data.
Parameters:
data (CalculatorSchema): CalculatorSchema for data.
Returns:
float: The result of evaluating the formula with the given value of 'x'.
"""
#validated_data = CalculatorSchema(**data)
formula = validated_data.formula
start, end = map(int, validated_data.x.split(':'))
x = range(start,end)
lstData=[]
for i in x:
lstData.append(parser.parse(formula).evaluate({"x":i}) )
return lstData
#return 0
llm = OpenAI(model_name="gpt-3.5-turbo-instruct", temperature=0, openai_api_key=key)
tools =[
Tool(
name="Parabola"
,func=calculator
,description="parse an equation"
)]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
formula="x^2 + 1"
mydict = {
"formula":formula,
"x": "-10:10"
}
validated_data = CalculatorSchema(**mydict)
agent.invoke(input=validated_data)