Loop based Math Chat Agent in Python
print("🤖 Simple AI Chat Agent")
print("Type 'exit' anytime to stop\n")
#creating empty list to store the chats later
chat_history = []
#creating function for mathematical calculations since its a math chat agent
def calculations(expression):
try:
result = eval(expression)
return f"The answer is {result}"
except:
return "I couldn’t understand that.please use numbers instead of letters"
#creating function for storing message, how and what to respond
def chatrespond(usermessage):
usrmsg = usermessage.lower()
chat_history.append(usermessage)
# Greetings - when user says hello
if "hello" in usrmsg or "hi" in usrmsg:
return "Hello! How can I help you?"
# when user asks How are you
if "how are you" in usrmsg:
return "I’m just Python based Math Chat agent, but running smoothly 😄"
# when user ask who are you
if all(keyword in usrmsg for keyword in ["what","can","do?"]) or all(keyword in usrmsg for keyword in ["tell","about","you?"]) or all(keyword in usrmsg for keyword in ["who","are","you?"]):
return "I am a chat based calculator, I can do basic mathematical calculations"
# when user ask ur Name
if "your name" in usrmsg:
return "I am your Python Chat agent to help with math."
# just to remind user about Memory
if len(chat_history) > 20:
return "We’ve been chatting quite a bit."
# when used send Math questions
if any(op in usrmsg for op in ["+", "-", "*", "/","(",")"]):
return calculations(usrmsg)
# Default message if user ask anything outside above messages
return "I am still learning more. As of now, my expertise currently focused on basic mathematical calculations"
#creating loop for chat and starting the chat loop, when to break it
while True:
user_input = input("You: ")
if user_input.lower() == "exit":
print("AI: Goodbye! 👋")
break
reply = chatrespond(user_input)
print("AI:", reply)
Comments
Post a Comment