Pārlūkot izejas kodu

add built-in maths tool for local expression evaluation on NumExpr (#2390)

Bowen Liang 1 gadu atpakaļ
vecāks
revīzija
d4cfd3e7ac

+ 1 - 0
api/core/tools/provider/_position.yaml

@@ -13,3 +13,4 @@
 - vectorizer
 - youtube
 - gaode
+- maths

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 3 - 0
api/core/tools/provider/builtin/maths/_assets/icon.svg


+ 18 - 0
api/core/tools/provider/builtin/maths/maths.py

@@ -0,0 +1,18 @@
+from typing import Any, Dict
+
+from core.tools.errors import ToolProviderCredentialValidationError
+from core.tools.provider.builtin.maths.tools.eval_expression import EvaluateExpressionTool
+from core.tools.provider.builtin_tool_provider import BuiltinToolProviderController
+
+
+class MathsProvider(BuiltinToolProviderController):
+    def _validate_credentials(self, credentials: Dict[str, Any]) -> None:
+        try:
+            EvaluateExpressionTool().invoke(
+                user_id='',
+                tool_parameters={
+                    'expression': '1+(2+3)*4',
+                },
+            )
+        except Exception as e:
+            raise ToolProviderCredentialValidationError(str(e))

+ 12 - 0
api/core/tools/provider/builtin/maths/maths.yaml

@@ -0,0 +1,12 @@
+identity:
+  author: Bowen Liang
+  name: maths
+  label:
+    en_US: Maths
+    zh_Hans: 数学工具
+    pt_BR: Maths
+  description:
+    en_US: A tool for maths.
+    zh_Hans: 一个用于数学计算的工具。
+    pt_BR: A tool for maths.
+  icon: icon.svg

+ 29 - 0
api/core/tools/provider/builtin/maths/tools/eval_expression.py

@@ -0,0 +1,29 @@
+import logging
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Union
+
+from core.tools.entities.tool_entities import ToolInvokeMessage
+from core.tools.tool.builtin_tool import BuiltinTool
+from pytz import timezone as pytz_timezone
+import numexpr as ne
+
+class EvaluateExpressionTool(BuiltinTool):
+    def _invoke(self, 
+                user_id: str,
+               tool_parameters: Dict[str, Any], 
+        ) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
+        """
+            invoke tools
+        """
+        # get expression
+        expression = tool_parameters.get('expression', '').strip()
+        if not expression:
+            return self.create_text_message('Invalid expression')
+
+        try:
+            result = ne.evaluate(expression)
+            result_str = str(result)
+        except Exception as e:
+            logging.exception(f'Error evaluating expression: {expression}')
+            return self.create_text_message(f'Invalid expression: {expression}, error: {str(e)}')
+        return self.create_text_message(f'The result of the expression "{expression}" is {result_str}')

+ 26 - 0
api/core/tools/provider/builtin/maths/tools/eval_expression.yaml

@@ -0,0 +1,26 @@
+identity:
+  name: eval_expression
+  author: Bowen Liang
+  label:
+    en_US: Evaluate Math Expression
+    zh_Hans: 计算数学表达式
+    pt_BR: Evaluate Math Expression
+description:
+  human:
+    en_US: A tool for evaluating an math expression, calculated locally with NumExpr.
+    zh_Hans: 一个用于计算数学表达式的工具,表达式将通过NumExpr本地执行。
+    pt_BR: A tool for evaluating an math expression, calculated locally with NumExpr.
+  llm: A tool for evaluating an math expression.
+parameters:
+  - name: expression
+    type: string
+    required: true
+    label:
+      en_US: Math Expression
+      zh_Hans: 数学计算表达式
+      pt_BR: Math Expression
+    human_description:
+      en_US: Math Expression
+      zh_Hans: 数学计算表达式
+      pt_BR: Math Expression
+    form: llm

+ 2 - 1
api/requirements.txt

@@ -64,4 +64,5 @@ httpx[socks]~=0.24.1
 matplotlib~=3.8.2
 yfinance~=0.2.35
 pydub~=0.25.1
-gmpy2~=2.1.5
+gmpy2~=2.1.5
+numexpr~=2.9.0

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels