-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
math_plugin.py
65 lines (54 loc) · 2.32 KB
/
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Copyright (c) Microsoft. All rights reserved.
from typing import Annotated
from semantic_kernel.functions.kernel_function_decorator import kernel_function
class MathPlugin:
"""
Description: MathPlugin provides a set of functions to make Math calculations.
Usage:
kernel.add_plugin(MathPlugin(), plugin_name="math")
Examples:
{{math.Add}} => Returns the sum of input and amount (provided in the KernelArguments)
{{math.Subtract}} => Returns the difference of input and amount (provided in the KernelArguments)
"""
@kernel_function(name="Add")
def add(
self,
input: Annotated[int, "the first number to add"],
amount: Annotated[int, "the second number to add"],
) -> Annotated[int, "the output is a number"]:
"""Returns the Addition result of the values provided."""
if isinstance(input, str):
input = int(input)
if isinstance(amount, str):
amount = int(amount)
return MathPlugin.add_or_subtract(input, amount, add=True)
@kernel_function(
description="Subtracts value to a value",
name="Subtract",
)
def subtract(
self,
input: Annotated[int, "the first number"],
amount: Annotated[int, "the number to subtract"],
) -> int:
"""
Returns the difference of numbers provided.
:param initial_value_text: Initial value as string to subtract the specified amount
:param context: Contains the context to get the numbers from
:return: The resulting subtraction as a string
"""
if isinstance(input, str):
input = int(input)
if isinstance(amount, str):
amount = int(amount)
return MathPlugin.add_or_subtract(input, amount, add=False)
@staticmethod
def add_or_subtract(input: int, amount: int, add: bool) -> int:
"""
Helper function to perform addition or subtraction based on the add flag.
:param initial_value_text: Initial value as string to add or subtract the specified amount
:param context: Contains the context to get the numbers from
:param add: If True, performs addition, otherwise performs subtraction
:return: The resulting sum or subtraction as a string
"""
return input + amount if add else input - amount