🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
refactor: wolfram toolkit (#2387)
JINO ROHITeaae07eb05e8
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 377c450c2..d40b636d7 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -72,6 +72,7 @@ from .pulse_mcp_search_toolkit import PulseMCPSearchToolkitfrom .klavis_toolkit import KlavisToolkitfrom .aci_toolkit import ACIToolkitfrom .playwright_mcp_toolkit import PlaywrightMCPToolkit+from .wolfram_alpha_toolkit import WolframAlphaToolkit__all__ = [@@ -132,4 +133,5 @@ __all__ = ['KlavisToolkit','ACIToolkit','PlaywrightMCPToolkit',+ 'WolframAlphaToolkit',]diff --git a/camel/toolkits/search_toolkit.py b/camel/toolkits/search_toolkit.pyindex 67977f15d..5e92dda13 100644--- a/camel/toolkits/search_toolkit.py+++ b/camel/toolkits/search_toolkit.py@@ -12,7 +12,6 @@# limitations under the License.# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import os-import xml.etree.ElementTree as ETfrom typing import Any, Dict, List, Literal, Optional, TypeAlias, Union, castimport requests@@ -489,173 +488,6 @@ class SearchToolkit(BaseToolkit):# If no answer found, return an empty listreturn responses- @dependencies_required("wolframalpha")- def query_wolfram_alpha(- self, query: str, is_detailed: bool = False- ) -> Union[str, Dict[str, Any]]:- r"""Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is an- answer engine developed by Wolfram Research. It is offered as an online- service that answers factual queries by computing answers from- externally sourced data.-- Args:- query (str): The query to send to Wolfram Alpha.- is_detailed (bool): Whether to include additional details- including step by step information in the result.- (default: :obj:`False`)-- Returns:- Union[str, Dict[str, Any]]: The result from Wolfram Alpha.- Returns a string if `is_detailed` is False, otherwise returns- a dictionary with detailed information.- """- import wolframalpha-- WOLFRAMALPHA_APP_ID = os.environ.get("WOLFRAMALPHA_APP_ID")- if not WOLFRAMALPHA_APP_ID:- raise ValueError(- "`WOLFRAMALPHA_APP_ID` not found in environment "- "variables. Get `WOLFRAMALPHA_APP_ID` here: `https://products.wolframalpha.com/api/`."- )-- try:- client = wolframalpha.Client(WOLFRAMALPHA_APP_ID)- res = client.query(query)-- except Exception as e:- return f"Wolfram Alpha wasn't able to answer it. Error: {e}"-- pased_result = self._parse_wolfram_result(res)-- if is_detailed:- step_info = self._get_wolframalpha_step_by_step_solution(- WOLFRAMALPHA_APP_ID, query- )- pased_result["steps"] = step_info- return pased_result-- return pased_result["final_answer"]-- def _parse_wolfram_result(self, result) -> Dict[str, Any]:- r"""Parses a Wolfram Alpha API result into a structured dictionary- format.-- Args:- result: The API result returned from a Wolfram Alpha- query, structured with multiple pods, each containing specific- information related to the query.-- Returns:- dict: A structured dictionary with the original query and the- final answer.- """-- # Extract the original query- query = result.get("@inputstring", "")-- # Initialize a dictionary to hold structured output- output = {"query": query, "pod_info": [], "final_answer": None}-- # Loop through each pod to extract the details- for pod in result.get("pod", []):- # Handle the case where subpod might be a list- subpod_data = pod.get("subpod", {})- if isinstance(subpod_data, list):- # If it's a list, get the first item for 'plaintext' and 'img'- description, image_url = next(- (- (data["plaintext"], data["img"])- for data in subpod_data- if "plaintext" in data and "img" in data- ),- ("", ""),- )- else:- # Otherwise, handle it as a dictionary- description = subpod_data.get("plaintext", "")- image_url = subpod_data.get("img", {}).get("@src", "")-- pod_info = {- "title": pod.get("@title", ""),- "description": description,- "image_url": image_url,- }-- # For Results pod, collect all plaintext values from subpods- if pod.get("@title") == "Results":- results_text = []- if isinstance(subpod_data, list):- for subpod in subpod_data:- if subpod.get("plaintext"):- results_text.append(subpod["plaintext"])- else:- if description:- results_text.append(description)- pod_info["description"] = "\n".join(results_text)-- # Add to steps list- output["pod_info"].append(pod_info)-- # Get final answer- if pod.get("@primary", False):- output["final_answer"] = description-- return output-- def _get_wolframalpha_step_by_step_solution(- self, app_id: str, query: str- ) -> dict:- r"""Retrieve a step-by-step solution from the Wolfram Alpha API for a- given query.-- Args:- app_id (str): Your Wolfram Alpha API application ID.- query (str): The mathematical or computational query to solve.-- Returns:- dict: The step-by-step solution response text from the Wolfram- Alpha API.- """- # Define the base URL- url = "https://api.wolframalpha.com/v2/query"-- # Set up the query parameters- params = {- "appid": app_id,- "input": query,- "podstate": ["Result__Step-by-step solution", "Show all steps"],- "format": "plaintext",- }-- # Send the request- response = requests.get(url, params=params)- root = ET.fromstring(response.text)-- # Extracting step-by-step steps, including 'SBSStep' and 'SBSHintStep'- steps = []- # Find all subpods within the 'Results' pod- for subpod in root.findall(".//pod[@title='Results']//subpod"):- # Check if the subpod has the desired stepbystepcontenttype- content_type = subpod.find("stepbystepcontenttype")- if content_type is not None and content_type.text in [- "SBSStep",- "SBSHintStep",- ]:- plaintext = subpod.find("plaintext")- if plaintext is not None and plaintext.text:- step_text = plaintext.text.strip()- cleaned_step = step_text.replace(- "Hint: |", ""- ).strip() # Remove 'Hint: |' if present- steps.append(cleaned_step)-- # Structuring the steps into a dictionary- structured_steps = {}- for i, step in enumerate(steps, start=1):- structured_steps[f"step{i}"] = step-- return structured_steps-def tavily_search(self, query: str, num_results: int = 5, **kwargs) -> List[Dict[str, Any]]:@@ -1243,7 +1075,6 @@ class SearchToolkit(BaseToolkit):FunctionTool(self.search_linkup),FunctionTool(self.search_google),FunctionTool(self.search_duckduckgo),- FunctionTool(self.query_wolfram_alpha),FunctionTool(self.tavily_search),FunctionTool(self.search_brave),FunctionTool(self.search_bocha),diff --git a/camel/toolkits/wolfram_alpha_toolkit.py b/camel/toolkits/wolfram_alpha_toolkit.pynew file mode 100644index 000000000..3b5b93670--- /dev/null+++ b/camel/toolkits/wolfram_alpha_toolkit.py@@ -0,0 +1,237 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import os+import xml.etree.ElementTree as ET+from typing import Any, Dict, List, Union++import requests++from camel.toolkits.base import BaseToolkit+from camel.toolkits.function_tool import FunctionTool+from camel.utils import MCPServer, api_keys_required, dependencies_required+++@MCPServer()+class WolframAlphaToolkit(BaseToolkit):+ r"""A class representing a toolkit for WolframAlpha.++ Wolfram|Alpha is an answer engine developed by Wolfram Research.+ It is offered as an online service that answers factual queries+ by computing answers from externally sourced data.+ """++ @api_keys_required(+ [+ (None, "WOLFRAMALPHA_APP_ID"),+ ]+ )+ @dependencies_required("wolframalpha")+ def query_wolfram_alpha(+ self, query: str, is_detailed: bool = False+ ) -> Union[str, Dict[str, Any]]:+ r"""Queries Wolfram|Alpha and returns the result.++ Args:+ query (str): The query to send to Wolfram Alpha.+ is_detailed (bool): Whether to include additional details+ including step by step information in the result.+ (default: :obj:`False`)++ Returns:+ Union[str, Dict[str, Any]]: The result from Wolfram Alpha.+ Returns a string if `is_detailed` is False, otherwise returns+ a dictionary with detailed information.+ """+ import wolframalpha++ WOLFRAMALPHA_APP_ID = os.environ.get("WOLFRAMALPHA_APP_ID", "")++ try:+ client = wolframalpha.Client(WOLFRAMALPHA_APP_ID)+ res = client.query(query)++ except Exception as e:+ return f"Wolfram Alpha wasn't able to answer it. Error: {e}"++ pased_result = self._parse_wolfram_result(res)++ if is_detailed:+ step_info = self._get_wolframalpha_step_by_step_solution(+ WOLFRAMALPHA_APP_ID, query+ )+ pased_result["steps"] = step_info+ return pased_result++ return pased_result["final_answer"]++ @api_keys_required(+ [+ (None, "WOLFRAMALPHA_APP_ID"),+ ]+ )+ def query_wolfram_llm(self, query: str) -> str:+ r"""Queries Wolfram|Alpha LLM API and returns the result.++ Args:+ query (str): The query to send to Wolfram Alpha LLM.++ Returns:+ str: The result from Wolfram Alpha as a string.+ """++ WOLFRAMALPHA_APP_ID = os.environ.get("WOLFRAMALPHA_APP_ID", "")++ try:+ url = "https://www.wolframalpha.com/api/v1/llm-api"+ params = {"input": query, "appid": WOLFRAMALPHA_APP_ID}++ response = requests.get(url, params=params)+ response.raise_for_status()+ return response.text++ except Exception as e:+ return f"Wolfram Alpha wasn't able to answer it. Error: {e}"++ def _parse_wolfram_result(self, result) -> Dict[str, Any]:+ r"""Parses a Wolfram Alpha API result into a structured dictionary+ format.++ Args:+ result: The API result returned from a Wolfram Alpha+ query, structured with multiple pods, each containing specific+ information related to the query.++ Returns:+ Dict[str, Any]: A structured dictionary with the original query+ and the final answer.+ """++ # Extract the original query+ query = result.get("@inputstring", "")++ # Initialize a dictionary to hold structured output+ output = {"query": query, "pod_info": [], "final_answer": None}++ # Loop through each pod to extract the details+ for pod in result.get("pod", []):+ # Handle the case where subpod might be a list+ subpod_data = pod.get("subpod", {})+ if isinstance(subpod_data, list):+ # If it's a list, get the first item for 'plaintext' and 'img'+ description, image_url = next(+ (+ (data["plaintext"], data["img"])+ for data in subpod_data+ if "plaintext" in data and "img" in data+ ),+ ("", ""),+ )+ else:+ # Otherwise, handle it as a dictionary+ description = subpod_data.get("plaintext", "")+ image_url = subpod_data.get("img", {}).get("@src", "")++ pod_info = {+ "title": pod.get("@title", ""),+ "description": description,+ "image_url": image_url,+ }++ # For Results pod, collect all plaintext values from subpods+ if pod.get("@title") == "Results":+ results_text = []+ if isinstance(subpod_data, list):+ for subpod in subpod_data:+ if subpod.get("plaintext"):+ results_text.append(subpod["plaintext"])+ else:+ if description:+ results_text.append(description)+ pod_info["description"] = "\n".join(results_text)++ # Add to steps list+ output["pod_info"].append(pod_info)++ # Get final answer+ if pod.get("@primary", False):+ output["final_answer"] = description++ return output++ def _get_wolframalpha_step_by_step_solution(+ self, app_id: str, query: str+ ) -> dict:+ r"""Retrieve a step-by-step solution from the Wolfram Alpha API for a+ given query.++ Args:+ app_id (str): Your Wolfram Alpha API application ID.+ query (str): The mathematical or computational query to solve.++ Returns:+ dict: The step-by-step solution response text from the Wolfram+ Alpha API.+ """+ # Define the base URL+ url = "https://api.wolframalpha.com/v2/query"++ # Set up the query parameters+ params = {+ "appid": app_id,+ "input": query,+ "podstate": ["Result__Step-by-step solution", "Show all steps"],+ "format": "plaintext",+ }++ # Send the request+ response = requests.get(url, params=params)+ root = ET.fromstring(response.text)++ # Extracting step-by-step steps, including 'SBSStep' and 'SBSHintStep'+ steps = []+ # Find all subpods within the 'Results' pod+ for subpod in root.findall(".//pod[@title='Results']//subpod"):+ # Check if the subpod has the desired stepbystepcontenttype+ content_type = subpod.find("stepbystepcontenttype")+ if content_type is not None and content_type.text in [+ "SBSStep",+ "SBSHintStep",+ ]:+ plaintext = subpod.find("plaintext")+ if plaintext is not None and plaintext.text:+ step_text = plaintext.text.strip()+ cleaned_step = step_text.replace(+ "Hint: |", ""+ ).strip() # Remove 'Hint: |' if present+ steps.append(cleaned_step)++ # Structuring the steps into a dictionary+ structured_steps = {}+ for i, step in enumerate(steps, start=1):+ structured_steps[f"step{i}"] = step++ return structured_steps++ def get_tools(self) -> List[FunctionTool]:+ r"""Returns a list of FunctionTool objects representing the+ functions in the toolkit.++ Returns:+ List[FunctionTool]: A list of FunctionTool objects+ representing the functions in the toolkit.+ """+ return [+ FunctionTool(self.query_wolfram_alpha),+ FunctionTool(self.query_wolfram_llm),+ ]diff --git a/examples/toolkits/search_toolkit.py b/examples/toolkits/search_toolkit.pyindex c1ad8d536..692d00ceb 100644--- a/examples/toolkits/search_toolkit.py+++ b/examples/toolkits/search_toolkit.py@@ -17,48 +17,6 @@ from pydantic import BaseModelfrom camel.agents import ChatAgentfrom camel.toolkits import FunctionTool, SearchToolkit-res_simple = SearchToolkit().query_wolfram_alpha(- query="solve 3x-7=11", is_detailed=False-)--print(res_simple)-'''-===============================================================================-x = 6-===============================================================================-'''--res_detailed = SearchToolkit().query_wolfram_alpha(- query="solve 3x-7=11", is_detailed=True-)--print(res_detailed)-'''-===============================================================================-{'query': 'solve 3x-7=11', 'pod_info': [{'title': 'Input interpretation',-'description': 'solve 3 x - 7 = 11', 'image_url': 'https://www6b3.wolframalpha.-com/Calculate/MSP/MSP37741a3dc67f338579ff00003fih94dg39300iaf?-MSPStoreType=image/gif&s=18'}, {'title': 'Result', 'description': 'x = 6',-'image_url': 'https://www6b3.wolframalpha.com/Calculate/MSP/-MSP37751a3dc67f338579ff00001dg4gbdcd0f10i3f?MSPStoreType=image/gif&s=18'},-{'title': 'Plot', 'description': None, 'image_url': 'https://www6b3.-wolframalpha.com/Calculate/MSP/MSP37761a3dc67f338579ff0000374484g95bh3ah3e?-MSPStoreType=image/gif&s=18'}, {'title': 'Number line', 'description': None,-'image_url': 'https://www6b3.wolframalpha.com/Calculate/MSP/-MSP37771a3dc67f338579ff00005573c3a87ahg8dbc?MSPStoreType=image/gif&s=18'}],-'final_answer': 'x = 6', 'steps': {'step1': 'Isolate terms with x to the left-hand side.\nAdd 7 to both sides:\n3 x + (7 - 7) = 7 + 11', 'step2': 'Look for-the difference of two identical terms.\n7 - 7 = 0:\n3 x = 11 + 7', 'step3':-'Evaluate 11 + 7.\n11 + 7 = 18:\n3 x = 18', 'step4': 'Divide both sides by a-constant to simplify the equation.\nDivide both sides of 3 x = 18 by 3:\n(3 x)/-3 = 18/3', 'step5': 'Any nonzero number divided by itself is one.\n3/3 = 1:\nx-= 18/3', 'step6': 'Reduce 18/3 to lowest terms. Start by finding the greatest-common divisor of 18 and 3.\nThe greatest common divisor of 18 and 3 is 3, so-factor out 3 from both the numerator and denominator: 18/3 = (3x6)/(3x1) = 3/3-x 6 = 6\nAnswer: | \n | x = 6'}}-===============================================================================-'''-res_brave = SearchToolkit().search_brave(q="What is the weather in Tokyo?",search_lang="en",diff --git a/examples/toolkits/wolfram_alpha_toolkit.py b/examples/toolkits/wolfram_alpha_toolkit.pynew file mode 100644index 000000000..8ed7f7c3d--- /dev/null+++ b/examples/toolkits/wolfram_alpha_toolkit.py@@ -0,0 +1,81 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========++from camel.models import ModelFactory+from camel.toolkits import WolframAlphaToolkit+from camel.types import ModelPlatformType, ModelType++model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+)++res_simple = WolframAlphaToolkit().query_wolfram_alpha(+ query="solve 3x-7=11", is_detailed=False+)++print(res_simple)+'''+===============================================================================+x = 6+===============================================================================+'''++res_detailed = WolframAlphaToolkit().query_wolfram_alpha(+ query="solve 3x-7=11", is_detailed=True+)++print(res_detailed)+'''+===============================================================================+{'query': 'solve 3x-7=11', 'pod_info': [{'title': 'Input interpretation',+'description': 'solve 3 x - 7 = 11', 'image_url': 'https://www6b3.wolframalpha.+com/Calculate/MSP/MSP37741a3dc67f338579ff00003fih94dg39300iaf?+MSPStoreType=image/gif&s=18'}, {'title': 'Result', 'description': 'x = 6',+'image_url': 'https://www6b3.wolframalpha.com/Calculate/MSP/+MSP37751a3dc67f338579ff00001dg4gbdcd0f10i3f?MSPStoreType=image/gif&s=18'},+{'title': 'Plot', 'description': None, 'image_url': 'https://www6b3.+wolframalpha.com/Calculate/MSP/MSP37761a3dc67f338579ff0000374484g95bh3ah3e?+MSPStoreType=image/gif&s=18'}, {'title': 'Number line', 'description': None,+'image_url': 'https://www6b3.wolframalpha.com/Calculate/MSP/+MSP37771a3dc67f338579ff00005573c3a87ahg8dbc?MSPStoreType=image/gif&s=18'}],+'final_answer': 'x = 6', 'steps': {'step1': 'Isolate terms with x to the left+hand side.\nAdd 7 to both sides:\n3 x + (7 - 7) = 7 + 11', 'step2': 'Look for+the difference of two identical terms.\n7 - 7 = 0:\n3 x = 11 + 7', 'step3':+'Evaluate 11 + 7.\n11 + 7 = 18:\n3 x = 18', 'step4': 'Divide both sides by a+constant to simplify the equation.\nDivide both sides of 3 x = 18 by 3:\n(3 x)/+3 = 18/3', 'step5': 'Any nonzero number divided by itself is one.\n3/3 = 1:\nx+= 18/3', 'step6': 'Reduce 18/3 to lowest terms. Start by finding the greatest+common divisor of 18 and 3.\nThe greatest common divisor of 18 and 3 is 3, so+factor out 3 from both the numerator and denominator: 18/3 = (3x6)/(3x1) = 3/3+x 6 = 6\nAnswer: | \n | x = 6'}}+===============================================================================+'''++res_llm = WolframAlphaToolkit().query_wolfram_llm(query="solve 3x-7=11")++print(res_llm)++'''+===============================================================================+'Query:\n"solve 3x-7=11"\n\nInput interpretation:\nsolve 3 x - 7 = 11\n\nResult+:\nx = 6\n\nPlot:\nimage: https://www6b3.wolframalpha.com/Calculate/MSP/MSP6802+0g1bg1ih5hce47h000016g8h3d8220352g2?MSPStoreType=image/png&s=2\nWolfram+Language code: Plot[{-7 + 3 x, 11}, {x, -9., 9.}]\n\nNumber line:\nimage:+https://www6b3.wolframalpha.com/Calculate/MSP/MSP68120g1bg1ih5hce47h000047d112+d53f34d535?MSPStoreType=image/png&s=2\nWolfram Language code: NumberLinePlot[x+== 6, x]\n\nWolfram|Alpha website result for "solve 3x-7=11":\nhttps://www6b3+.wolframalpha.com/input?i=solve+3x-7%3D11'+===============================================================================+'''diff --git a/test/toolkits/test_search_functions.py b/test/toolkits/test_search_functions.pyindex 8009f6602..ea32d1666 100644--- a/test/toolkits/test_search_functions.py+++ b/test/toolkits/test_search_functions.py@@ -13,7 +13,7 @@# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========import osfrom unittest import mock-from unittest.mock import MagicMock, Mock, patch+from unittest.mock import MagicMock, patchimport pytestimport requests@@ -309,147 +309,6 @@ def test_search_bing(mock_get, search_toolkit):)-@patch('requests.get')-@patch('wolframalpha.Client')-@patch('os.environ.get')-def test_query_wolfram_alpha(mock_get_env, mock_client, mock_requests_get):- mock_get_env.return_value = 'FAKE_APP_ID'-- mock_res = MagicMock()- mock_res.get.side_effect = lambda key, default: {- '@inputstring': 'calculate limit of sinx^2/x',- 'pod': [- {- '@title': 'Limit',- 'subpod': {'plaintext': 'lim_(x->0) (sin^2(x))/x = 0'},- },- {- '@title': 'Plot',- 'subpod': {'plaintext': None},- },- ],- }[key]-- mock_instance = MagicMock()- mock_instance.query.return_value = mock_res- mock_client.return_value = mock_instance-- mock_requests_get.return_value = MagicMock(status_code=200)- mock_requests_get.return_value.text = """- <queryresult success="true" error="false">- <pod title="Limit">- <subpod>- <plaintext>lim_(x->0) (sin^2(x))/x = 0</plaintext>- </subpod>- </pod>- <pod title="Plot">- <subpod>- <plaintext></plaintext>- </subpod>- </pod>- </queryresult>- """-- result = SearchToolkit().query_wolfram_alpha(- "calculate limit of sinx^2/x", True- )-- expected_output = {- "query": "calculate limit of sinx^2/x",- "pod_info": [- {- "title": "Limit",- "description": "lim_(x->0) (sin^2(x))/x = 0",- "image_url": '',- },- {- "title": "Plot",- "description": None,- "image_url": '',- },- ],- "final_answer": None,- "steps": {},- }-- assert result == expected_output---def test_parse_wolfram_result():- sample_wolfram_result = {- "@inputstring": "What is 2+2?",- "pod": [- {- "@title": "Input",- "subpod": {- "plaintext": "2 + 2",- "img": {"@src": "http://example.com/image1.png"},- },- },- {- "@title": "Result",- "subpod": {- "plaintext": "4",- "img": {"@src": "http://example.com/image2.png"},- },- "@primary": "true",- },- ],- }- expected_output = {- "query": "What is 2+2?",- "pod_info": [- {- "title": "Input",- "description": "2 + 2",- "image_url": "http://example.com/image1.png",- },- {- "title": "Result",- "description": "4",- "image_url": "http://example.com/image2.png",- },- ],- "final_answer": "4",- }-- result = SearchToolkit()._parse_wolfram_result(sample_wolfram_result)-- assert (- result == expected_output- ), f"Expected {expected_output}, but got {result}"---@patch('requests.get')-def test_get_wolframalpha_step_by_step_solution(mock_get):- sample_response = """- <queryresult>- <pod title="Results">- <subpod>- <stepbystepcontenttype>SBSHintStep</stepbystepcontenttype>- <plaintext>Hint: | Step 1</plaintext>- </subpod>- <subpod>- <stepbystepcontenttype>SBSHintStep</stepbystepcontenttype>- <plaintext>Hint: | Step 2</plaintext>- </subpod>- </pod>- </queryresult>- """-- mock_get.return_value = Mock(text=sample_response)-- expected_steps = {"step1": "Step 1", "step2": "Step 2"}-- result = SearchToolkit()._get_wolframalpha_step_by_step_solution(- "dummy_app_id", "dummy_query"- )-- assert (- result == expected_steps- ), f"Expected {expected_steps}, but got {result}"--class MockSearchResult:def __init__(self, **kwargs):self.__dict__.update(kwargs)diff --git a/test/toolkits/test_wolframalpha_toolkit.py b/test/toolkits/test_wolframalpha_toolkit.pynew file mode 100644index 000000000..346d715e4--- /dev/null+++ b/test/toolkits/test_wolframalpha_toolkit.py@@ -0,0 +1,157 @@+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from unittest.mock import MagicMock, Mock, patch++from camel.toolkits import WolframAlphaToolkit+++@patch('requests.get')+@patch('wolframalpha.Client')+@patch('os.environ.get')+def test_query_wolfram_alpha(mock_get_env, mock_client, mock_requests_get):+ mock_get_env.return_value = 'FAKE_APP_ID'++ mock_res = MagicMock()+ mock_res.get.side_effect = lambda key, default: {+ '@inputstring': 'calculate limit of sinx^2/x',+ 'pod': [+ {+ '@title': 'Limit',+ 'subpod': {'plaintext': 'lim_(x->0) (sin^2(x))/x = 0'},+ },+ {+ '@title': 'Plot',+ 'subpod': {'plaintext': None},+ },+ ],+ }[key]++ mock_instance = MagicMock()+ mock_instance.query.return_value = mock_res+ mock_client.return_value = mock_instance++ mock_requests_get.return_value = MagicMock(status_code=200)+ mock_requests_get.return_value.text = """+ <queryresult success="true" error="false">+ <pod title="Limit">+ <subpod>+ <plaintext>lim_(x->0) (sin^2(x))/x = 0</plaintext>+ </subpod>+ </pod>+ <pod title="Plot">+ <subpod>+ <plaintext></plaintext>+ </subpod>+ </pod>+ </queryresult>+ """++ result = WolframAlphaToolkit().query_wolfram_alpha(+ "calculate limit of sinx^2/x", True+ )++ expected_output = {+ "query": "calculate limit of sinx^2/x",+ "pod_info": [+ {+ "title": "Limit",+ "description": "lim_(x->0) (sin^2(x))/x = 0",+ "image_url": '',+ },+ {+ "title": "Plot",+ "description": None,+ "image_url": '',+ },+ ],+ "final_answer": None,+ "steps": {},+ }++ assert result == expected_output+++def test_parse_wolfram_result():+ sample_wolfram_result = {+ "@inputstring": "What is 2+2?",+ "pod": [+ {+ "@title": "Input",+ "subpod": {+ "plaintext": "2 + 2",+ "img": {"@src": "http://example.com/image1.png"},+ },+ },+ {+ "@title": "Result",+ "subpod": {+ "plaintext": "4",+ "img": {"@src": "http://example.com/image2.png"},+ },+ "@primary": "true",+ },+ ],+ }+ expected_output = {+ "query": "What is 2+2?",+ "pod_info": [+ {+ "title": "Input",+ "description": "2 + 2",+ "image_url": "http://example.com/image1.png",+ },+ {+ "title": "Result",+ "description": "4",+ "image_url": "http://example.com/image2.png",+ },+ ],+ "final_answer": "4",+ }++ result = WolframAlphaToolkit()._parse_wolfram_result(sample_wolfram_result)++ assert (+ result == expected_output+ ), f"Expected {expected_output}, but got {result}"+++@patch('requests.get')+def test_get_wolframalpha_step_by_step_solution(mock_get):+ sample_response = """+ <queryresult>+ <pod title="Results">+ <subpod>+ <stepbystepcontenttype>SBSHintStep</stepbystepcontenttype>+ <plaintext>Hint: | Step 1</plaintext>+ </subpod>+ <subpod>+ <stepbystepcontenttype>SBSHintStep</stepbystepcontenttype>+ <plaintext>Hint: | Step 2</plaintext>+ </subpod>+ </pod>+ </queryresult>+ """++ mock_get.return_value = Mock(text=sample_response)++ expected_steps = {"step1": "Step 1", "step2": "Step 2"}++ result = WolframAlphaToolkit()._get_wolframalpha_step_by_step_solution(+ "dummy_app_id", "dummy_query"+ )++ assert (+ result == expected_steps+ ), f"Expected {expected_steps}, but got {result}"