-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
math_plugin.py
28 lines (22 loc) · 1010 Bytes
/
math_plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from _context import sm
class MathPlugin(sm.BasePlugin):
def pre_send_hook(self, conversation: sm.Conversation):
last_user_message = conversation.get_last_message(role="user")
if last_user_message is None:
return
if "calculate" in last_user_message.text.lower():
expression = last_user_message.text.lower().replace("calculate", "").strip()
try:
result = eval(expression)
conversation.add_message(
role="assistant", text=f"The result is {result}."
)
except Exception:
conversation.add_message(
role="assistant",
text="I'm sorry, I couldn't compute that expression. Please try again.",
)
conversation = sm.create_conversation(llm_model="gpt-4o", llm_provider="openai")
conversation.add_plugin(MathPlugin())
conversation.add_message("user", "Calculate 2 + 2 * 3")
print(conversation.send())