Skip to main content
`Ctrl`+`K`

# LLM Math

This notebook showcases using LLMs and Python REPLs to do complex word math problems.

    from langchain import OpenAI, LLMMathChain

    llm = OpenAI(temperature=0)
    llm_math = LLMMathChain(llm=llm, verbose=True)

    llm_math.run("What is 13 raised to the .3432 power?")

    > Entering new LLMMathChain chain...
    What is 13 raised to the .3432 power?
    ```python
    import math
    print(math.pow(13, .3432))
    ```

    Answer: 2.4116004626599237

    > Finished chain.

    'Answer: 2.4116004626599237\n'

## Customize Prompt

You can also customize the prompt that is used. Here is an example prompting it to use numpy

    from langchain.prompts.prompt import PromptTemplate

    _PROMPT_TEMPLATE = """You are GPT-3, and you can't do math.

    You can do basic math, and your memorization abilities are impressive, but you can't do any complex calculations that a human could not do in their head. You also have an annoying tendency to just make up highly specific, but wrong, answers.

    So we hooked you up to a Python 3 kernel, and now you can execute code. If you execute code, you must print out the final answer using the print function. You MUST use the python package numpy to answer your question. You must import numpy as np.

    Question: ${{Question with hard calculation.}}
    ```python
    ${{Code that prints what you need to know}}
    print(${{code}})
    ```
    ```output
    ${{Output of your code}}
    ```
    Answer: ${{Answer}}

    Begin.

    Question: What is 37593 * 67?

    ```python
    import numpy as np
    print(np.multiply(37593, 67))
    ```
    ```output
    2518731
    ```
    Answer: 2518731

    Question: {question}"""

    PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE)

    llm_math = LLMMathChain(llm=llm, prompt=PROMPT, verbose=True)

    llm_math.run("What is 13 raised to the .3432 power?")

    > Entering new LLMMathChain chain...
    What is 13 raised to the .3432 power?

    ```python
    import numpy as np
    print(np.power(13, .3432))
    ```

    Answer: 2.4116004626599237

    > Finished chain.

    'Answer: 2.4116004626599237\n'