I previously shared PAL (Program-aided language model chain), and today let's look at a similar one - Math chain.
It mainly solves complex math word problems through LLMs and Python REPLs.
https://twitter.com/LangChainAI/status/1638218812536532992
This guy, vadym.eth (@vadymbarda), has optimized LLMMath.
I tried it out, and it works pretty well:
# Installing necessary libraries
!pip -q install google.generativeai langchain
# Import necessary libraries
import os
import google.generativeai as palm
from langchain.llms import GooglePalm
from langchain.chains import LLMMathChain
# Configure API key for Google PaLM
os.environ["GOOGLE_API_KEY"] = “API_KEY”
# Initialize GooglePalm with default settings
llm = GooglePalm()
# Set up the math solver using the GooglePalm instance
llm_math = LLMMathChain.from_llm(llm, verbose=True)
# Introduction message for the math solver
print("Agent: I'd be happy to help you with your math problems. Could you please show me the word problem?")
# Get the user's math problem
user_input = input('User: ')
# Solve the provided math problem
answer = llm_math.run(user_input)
print(f"Agent: {answer}")
The final input is something like this:
Agent: I'd be happy to help you with your math problems. Could you please show me the word problem?
User: I have 77 houses, each with 31 cats. Each cat owns 14 mittens and 6 hats. Each mitten was knit from 141m of yarn, each hat from 55m. How much yarn was needed to make all the items?
Entering new LLMMathChain chain...
I have 77 houses, each with 31 cats. Each cat owns 14 mittens and 6 hats. Each mitten was knit from 141m of yarn, each hat from 55m. How much yarn was needed to make all the items?
141 * 14 * 31 * 77 + 55 * 6 * 31 * 77
...numexpr.evaluate("141 * 14 * 31 * 77 + 55 > * 6 * 31 * 77")...Answer: 5499648
Finished chain.Agent: Answer: 5499648