Langchain 数学問題を解く Math chain

以前に PAL(Program-aided language model chain)を共有しました、今日はそれに似たものを見てみましょう - Math chain。

主に LLM と Python REPL を使用して複雑な数学の応用問題を解決します。

https://twitter.com/LangChainAI/status/1638218812536532992

この vadym.eth (@vadymbarda)氏は、LLMath を最適化しました。

試しに使ってみましたが、かなり使いやすいです:

# 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}")

最後の入力は、このような意味になります:

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