A simple AI-powered math assistant using LangChain and OpenAI, capable of handling basic arithmetic operations and natural conversation.
- Conversational AI: Chat with the assistant in plain English.
- Math Tools: Perform addition, subtraction, multiplication, division, square roots, exponents, and more.
- Real-Time Streaming: See responses as they are generated.
- OpenAI Integration: Powered by OpenAI’s API via LangChain for flexible language understanding.
- Environment Variables: Secure usage of API keys with
.envfile.
- How It Works
- Quick Start
- Adding More Math Tools
- Understanding the Components
- Lowering OpenAI Costs
- FAQ / Further Reading
- The assistant listens to your input.
- It uses LangChain agents to reason about your question.
- If your input matches a tool (like math operations), it calls the corresponding Python function.
- The result is streamed to your terminal in real time.
-
Clone the repository:
git clone https://github.com/rohanpandavv/MathBuddy.git cd MathBuddy -
Install uv (if you don’t have it):
pip install uv
-
Install dependencies with uv:
uv pip install -r requirements.txt
-
Set up your
.envfile:OPENAI_API_KEY=sk-xxxxxx -
Activate the virtual environment:
source .venv/bin/activateor
venv\Scripts\activate.bat -
Run the assistant:
python main.py
-
Example Usage:
You: What is 12 times 9? Assistant: The product of 12 and 9 is 108 You: Square root of 16? Assistant: The square root of 16 is 4.0 You: quit
You can add any math operation by creating a new function and decorating it with @tool.
Example:
import math
@tool
def factorial(a: float) -> str:
"""Useful for finding out the factorial of a number."""
return f"The factorial of {a} is {math.factorial(a)}"Add your newly created tools to the tools list.
tools = [addition, subtraction, division, multiplication, remainder, root, factorial]- ChatOpenAI: A wrapper to access OpenAI’s language models. You can set the temperature parameter (randomness) and model (e.g., gpt-3.5-turbo for lower cost).
- HumanMessage: Used to represent user input as part of a message sequence for the agent.
- @tool Decorator: Converts a Python function into a “tool” that the agent can use, guided by the function’s docstring.
- create_react_agent: Instantiates a LangChain ReAct agent which can REason and ACT (call tools) based on user input.
- agent_executor.stream: Streams the assistant’s response in real time, providing a conversational experience.
- Keep prompts concise.
- Don't add unnecessary history to the prompt.
- NEVER PUSH .ENV FILES ON ANY VERSION CONTROL
- MAKE SURE YOU SAFEGUARD YOUR OPENAI SECRET KEY