Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Add data commons toolkit (#979)

Danield17688382561
diff --git a/camel/toolkits/data_commons_toolkit.py b/camel/toolkits/data_commons_toolkit.py
new file mode 100644
index 000000000..714bdbdb5
--- /dev/null
+++ b/camel/toolkits/data_commons_toolkit.py
@@ -0,0 +1,360 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+import logging
+from typing import Any, Dict, List, Optional, Union
+
+from camel.toolkits.base import BaseToolkit
+
+logger = logging.getLogger(__name__)
+
+
+class DataCommonsToolkit(BaseToolkit):
+ r"""A class representing a toolkit for Data Commons.
+
+ This class provides methods for querying and retrieving data from the
+ Data Commons knowledge graph. It includes functionality for:
+ - Executing SPARQL queries
+ - Retrieving triples associated with nodes
+ - Fetching statistical time series data
+ - Analyzing property labels and values
+ - Retrieving places within a given place type
+ - Obtaining statistical values for specific variables and locations
+
+ All the data are grabbed from the knowledge graph of Data Commons.
+ Refer to https://datacommons.org/browser/ for more details.
+ """
+
+ @staticmethod
+ def query_data_commons(
+ query_string: str,
+ ) -> Optional[List[Dict[str, Any]]]:
+ r"""Query the Data Commons knowledge graph using SPARQL.
+
+ Args:
+ query_string (str): A SPARQL query string.
+
+ Returns:
+ Optional[List[Dict[str, Any]]]: A list of dictionaries, each
+ representing a node matching the query conditions if success,
+ (default: :obj:`None`) otherwise.
+
+ Note:
+ - Only supports a limited subset of SPARQL functionality (ORDER BY,
+ DISTINCT, LIMIT).
+ - Each variable in the query should have a 'typeOf' condition.
+ - The Python SPARQL library currently only supports the V1 version
+ of the API.
+
+ Reference:
+ https://docs.datacommons.org/api/python/query.html
+ """
+ import datacommons
+
+ try:
+ results = datacommons.query(query_string)
+
+ processed_results = [
+ {key: value for key, value in row.items()} for row in results
+ ]
+
+ return processed_results
+
+ except Exception as e:
+ logger.error(
+ f"An error occurred while querying Data Commons: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_triples(
+ dcids: Union[str, List[str]], limit: int = 500
+ ) -> Optional[Dict[str, List[tuple]]]:
+ r"""Retrieve triples associated with nodes.
+
+ Args:
+ dcids (Union[str, List[str]]): A single DCID or a list of DCIDs
+ to query.
+ limit (int): The maximum number of triples per
+ combination of property and type. (default: :obj:`500`)
+
+ Returns:
+ Optional[Dict[str, List[tuple]]]: A dictionary where keys are
+ DCIDs and values are lists of associated triples if success,
+ (default: :obj:`None`) otherwise.
+
+ Note:
+ - The function will raise a ValueError if any of the required
+ arguments are missing.
+ - The function will raise a TypeError if the dcids are not a string
+ or a list of strings.
+ - The function will raise a ValueError if the limit is not between
+ 1 and 500.
+ - The function will raise a KeyError if one or more of the provided
+ DCIDs do not exist in the Data Commons knowledge graph.
+ - The function will raise an Exception if an unexpected error occurs.
+
+ Reference:
+ https://docs.datacommons.org/api/python/triple.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_triples(dcids, limit)
+ return result
+
+ except Exception as e:
+ logger.error(f"An error occurred: {e!s}")
+ return None
+
+ @staticmethod
+ def get_stat_time_series(
+ place: str,
+ stat_var: str,
+ measurement_method: Optional[str] = None,
+ observation_period: Optional[str] = None,
+ unit: Optional[str] = None,
+ scaling_factor: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ r"""Retrieve statistical time series for a place.
+
+ Args:
+ place (str): The dcid of the Place to query for.
+ stat_var (str): The dcid of the StatisticalVariable.
+ measurement_method (str, optional): The technique used for
+ measuring a statistical variable. (default: :obj:`None`)
+ observation_period (str, optional): The time period over which an
+ observation is made. (default: :obj:`None`)
+ scaling_factor (str, optional): Property of statistical variables
+ indicating factor by which a measurement is multiplied to fit
+ a certain format. (default: :obj:`None`)
+ unit (str, optional): The unit of measurement. (default:
+ :obj:`None`)
+
+ Returns:
+ Optional[Dict[str, Any]]: A dictionary containing the statistical
+ time series data if success, (default: :obj:`None`) otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/stat_series.html
+ """
+ import datacommons_pandas
+
+ try:
+ result = datacommons_pandas.get_stat_series(
+ place,
+ stat_var,
+ measurement_method,
+ observation_period,
+ unit,
+ scaling_factor,
+ )
+ return result
+ except Exception as e:
+ logger.error(
+ f"An error occurred while querying Data Commons: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_property_labels(
+ dcids: Union[str, List[str]], out: bool = True
+ ) -> Optional[Dict[str, List[str]]]:
+ r"""Retrieves and analyzes property labels for given DCIDs.
+
+ Args:
+ dcids (list): A list of Data Commons IDs (DCIDs) to analyze.
+ out (bool): Direction of properties to retrieve. (default:
+ :obj:`True`)
+
+ Returns:
+ Optional[Dict[str, List[str]]]: Analysis results for each DCID if
+ success, (default: :obj:`None`) otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/property_label.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_property_labels(dcids, out=out)
+ return result
+ except Exception as e:
+ logger.error(
+ f"An error occurred while analyzing property labels: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_property_values(
+ dcids: Union[str, List[str]],
+ prop: str,
+ out: Optional[bool] = True,
+ value_type: Optional[str] = None,
+ limit: Optional[int] = None,
+ ) -> Optional[Dict[str, Any]]:
+ r"""Retrieves and analyzes property values for given DCIDs.
+
+ Args:
+ dcids (list): A list of Data Commons IDs (DCIDs) to analyze.
+ prop (str): The property to analyze.
+ value_type (str, optional): The type of the property value to
+ filter by. Defaults to NONE. Only applicable if the value
+ refers to a node.
+ out (bool, optional): The label's direction. (default: :obj:`True`)
+ (only returning response nodes directed towards the requested
+ node). If set to False, will only return response nodes
+ directed away from the request node. (default: :obj:`None`)
+ limit (int, optional): (≤ 500) Maximum number of values returned
+ per node. (default: :obj:`datacommons.utils._MAX_LIMIT`)
+
+ Returns:
+ Optional[Dict[str, Any]]: Analysis results for each DCID if
+ success, (default: :obj:`None`) otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/property_value.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_property_values(
+ dcids, prop, out, value_type, limit
+ )
+ return result
+
+ except Exception as e:
+ logger.error(
+ f"An error occurred while analyzing property values: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_places_in(
+ dcids: list, place_type: str
+ ) -> Optional[Dict[str, Any]]:
+ r"""Retrieves places within a given place type.
+
+ Args:
+ dcids (list): A list of Data Commons IDs (DCIDs) to analyze.
+ place_type (str): The type of the place to filter by.
+
+ Returns:
+ Optional[Dict[str, Any]]: Analysis results for each DCID if
+ success, (default: :obj:`None`) otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/place_in.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_places_in(dcids, place_type)
+ return result
+
+ except Exception as e:
+ logger.error(
+ "An error occurred while retrieving places in a given place "
+ f"type: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_stat_value(
+ place: str,
+ stat_var: str,
+ date: Optional[str] = None,
+ measurement_method: Optional[str] = None,
+ observation_period: Optional[str] = None,
+ unit: Optional[str] = None,
+ scaling_factor: Optional[str] = None,
+ ) -> Optional[float]:
+ r"""Retrieves the value of a statistical variable for a given place
+ and date.
+
+ Args:
+ place (str): The DCID of the Place to query for.
+ stat_var (str): The DCID of the StatisticalVariable.
+ date (str, optional): The preferred date of observation in ISO
+ 8601 format. If not specified, returns the latest observation.
+ (default: :obj:`None`)
+ measurement_method (str, optional): The DCID of the preferred
+ measurementMethod value. (default: :obj:`None`)
+ observation_period (str, optional): The preferred observationPeriod
+ value. (default: :obj:`None`)
+ unit (str, optional): The DCID of the preferred unit value.
+ (default: :obj:`None`)
+ scaling_factor (str, optional): The preferred scalingFactor value.
+ (default: :obj:`None`)
+
+ Returns:
+ Optional[float]: The value of the statistical variable for the
+ given place and date if success, (default: :obj:`None`)
+ otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/stat_value.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_stat_value(
+ place,
+ stat_var,
+ date,
+ measurement_method,
+ observation_period,
+ unit,
+ scaling_factor,
+ )
+ return result
+
+ except Exception as e:
+ logger.error(
+ "An error occurred while retrieving the value of a "
+ f"statistical variable: {e!s}"
+ )
+ return None
+
+ @staticmethod
+ def get_stat_all(places: str, stat_vars: str) -> Optional[dict]:
+ r"""Retrieves the value of a statistical variable for a given place
+ and date.
+
+ Args:
+ places (str): The DCID IDs of the Place objects to query for.
+ (Here DCID stands for Data Commons ID, the unique identifier
+ assigned to all entities in Data Commons.)
+ stat_vars (str): The dcids of the StatisticalVariables at
+ https://datacommons.org/browser/StatisticalVariable
+
+ Returns:
+ Optional[dict]: A dictionary with the DCID of the place as the key
+ and a list of tuples as the value if success, (default:
+ :obj:`None`) otherwise.
+
+ Reference:
+ https://docs.datacommons.org/api/python/stat_all.html
+ """
+ import datacommons
+
+ try:
+ result = datacommons.get_stat_all(places, stat_vars)
+ return result
+
+ except Exception as e:
+ logger.error(
+ "An error occurred while retrieving the value of a "
+ f"statistical variable: {e!s}"
+ )
+ return None
diff --git a/examples/toolkits/data_commons_toolkit.py b/examples/toolkits/data_commons_toolkit.py
new file mode 100644
index 000000000..2935fea61
--- /dev/null
+++ b/examples/toolkits/data_commons_toolkit.py
@@ -0,0 +1,121 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from camel.toolkits.data_commons_toolkit import DataCommonsToolkit
+
+# Initialize the DataCommonsToolkit
+dc_toolkit = DataCommonsToolkit()
+
+# Example 1: Query Data Commons
+geoId06_name_query = '''
+SELECT ?name ?dcid
+WHERE {
+ ?a typeOf Place .
+ ?a name ?name .
+ ?a dcid ("geoId/06" "geoId/21" "geoId/24") .
+ ?a dcid ?dcid
+}
+'''
+result = dc_toolkit.query_data_commons(geoId06_name_query)
+print("Query Result:")
+print(result)
+
+'''
+===============================================================================
+Query Result:
+[{'?name': 'Kentucky', '?dcid': 'geoId/21'},
+ {'?name': 'California', '?dcid': 'geoId/06'},
+ {'?name': 'Maryland', '?dcid': 'geoId/24'}]
+===============================================================================
+'''
+
+# Example 2: Get Triples
+dcids = ["geoId/06", "geoId/21", "geoId/24"]
+triples = dc_toolkit.get_triples(dcids)
+print("\nTriples for California, Kentucky, and Maryland:")
+print(triples)
+
+'''
+===============================================================================
+Triples for California, Kentucky, and Maryland:
+{
+ "geoId/06": [
+ ("name", "California"),
+ ("containedInPlace", "country/USA"),
+ ...
+ ],
+ "geoId/21": [
+ ("name", "Kentucky"),
+ ("containedInPlace", "country/USA"),
+ ...
+ ],
+ "geoId/24": [
+ ("name", "Maryland"),
+ ("containedInPlace", "country/USA"),
+ ...
+ ]
+}
+===============================================================================
+'''
+
+# Example 3: Get Statistical Time Series
+place = "geoId/06"
+stat_var = "Count_Person"
+series = dc_toolkit.get_stat_time_series(place, stat_var)
+print("\nPopulation Time Series for California:")
+print(series)
+
+'''
+===============================================================================
+Population Time Series for California:
+{
+ "2010": 37253956,
+ "2011": 37594778,
+ "2012": 37971427,
+ ...
+}
+===============================================================================
+'''
+
+# Example 4: Get Property Values
+dcids = ["geoId/06", "geoId/21", "geoId/24"]
+prop = "containedInPlace"
+values = dc_toolkit.get_property_values(dcids, prop)
+print("\nContained In Place for California, Kentucky, and Maryland:")
+print(values)
+
+'''
+===============================================================================
+Contained In Place for California, Kentucky, and Maryland:
+{
+ "geoId/06": ["country/USA"],
+ "geoId/21": ["country/USA"],
+ "geoId/24": ["country/USA"]
+}
+===============================================================================
+'''
+
+# Example 5: Get Statistical Value
+place = "geoId/06"
+stat_var = "Count_Person"
+date = "2021"
+value = dc_toolkit.get_stat_value(place, stat_var, date)
+print("\nPopulation of California in 2021:")
+print(value)
+
+'''
+===============================================================================
+Population of California in 2021:
+39237836
+===============================================================================
+'''
diff --git a/poetry.lock b/poetry.lock
index f3277fb82..7f780966e 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.
+# This file is automatically @generated by Poetry 1.8.4 and should not be changed by hand.
[[package]]
name = "accelerate"
@@ -1292,6 +1292,35 @@ files = [
marshmallow = ">=3.18.0,<4.0.0"
typing-inspect = ">=0.4.0,<1"
+[[package]]
+name = "datacommons"
+version = "1.4.3"
+description = "A library to access Data Commons Python API."
+optional = true
+python-versions = ">=2.7"
+files = [
+ {file = "datacommons-1.4.3-py3-none-any.whl", hash = "sha256:fd75f626b45f717164f32bf0cf0a76775012917d46c2a75cbe94c9d7f8d14926"},
+ {file = "datacommons-1.4.3.tar.gz", hash = "sha256:4940a6ccdca7e571d5d4e094acab222adb967d83ca93877354b8396924e79d26"},
+]
+
+[package.dependencies]
+six = "*"
+
+[[package]]
+name = "datacommons-pandas"
+version = "0.0.3"
+description = "A library to create pandas objects using the Data Commons Python API."
+optional = true
+python-versions = ">=2.7"
+files = [
+ {file = "datacommons_pandas-0.0.3-py3-none-any.whl", hash = "sha256:e44709c7b732b1d8b0adea5e6cd2febb4bee5cfefb9d73d6338d8d4046a74532"},
+ {file = "datacommons_pandas-0.0.3.tar.gz", hash = "sha256:2cc4db8e6d79c72fd46fa860f6489778f059c500c1c75b66288487dd7b0c139c"},
+]
+
+[package.dependencies]
+pandas = "*"
+six = "*"
+
[[package]]
name = "datasets"
version = "2.14.4"
@@ -3900,7 +3929,6 @@ python-versions = ">=3.7"
files = [
{file = "milvus_lite-2.4.10-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:fc4246d3ed7d1910847afce0c9ba18212e93a6e9b8406048436940578dfad5cb"},
{file = "milvus_lite-2.4.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:74a8e07c5e3b057df17fbb46913388e84df1dc403a200f4e423799a58184c800"},
- {file = "milvus_lite-2.4.10-py3-none-manylinux2014_aarch64.whl", hash = "sha256:240c7386b747bad696ecb5bd1f58d491e86b9d4b92dccee3315ed7256256eddc"},
{file = "milvus_lite-2.4.10-py3-none-manylinux2014_x86_64.whl", hash = "sha256:211d2e334a043f9282bdd9755f76b9b2d93b23bffa7af240919ffce6a8dfe325"},
]
@@ -4992,31 +5020,43 @@ python-versions = ">=3.9"
files = [
{file = "pandas-2.2.3-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:1948ddde24197a0f7add2bdc4ca83bf2b1ef84a1bc8ccffd95eda17fd836ecb5"},
{file = "pandas-2.2.3-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:381175499d3802cde0eabbaf6324cce0c4f5d52ca6f8c377c29ad442f50f6348"},
+ {file = "pandas-2.2.3-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d9c45366def9a3dd85a6454c0e7908f2b3b8e9c138f5dc38fed7ce720d8453ed"},
{file = "pandas-2.2.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:86976a1c5b25ae3f8ccae3a5306e443569ee3c3faf444dfd0f41cda24667ad57"},
+ {file = "pandas-2.2.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:b8661b0238a69d7aafe156b7fa86c44b881387509653fdf857bebc5e4008ad42"},
{file = "pandas-2.2.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:37e0aced3e8f539eccf2e099f65cdb9c8aa85109b0be6e93e2baff94264bdc6f"},
{file = "pandas-2.2.3-cp310-cp310-win_amd64.whl", hash = "sha256:56534ce0746a58afaf7942ba4863e0ef81c9c50d3f0ae93e9497d6a41a057645"},
{file = "pandas-2.2.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:66108071e1b935240e74525006034333f98bcdb87ea116de573a6a0dccb6c039"},
{file = "pandas-2.2.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7c2875855b0ff77b2a64a0365e24455d9990730d6431b9e0ee18ad8acee13dbd"},
+ {file = "pandas-2.2.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cd8d0c3be0515c12fed0bdbae072551c8b54b7192c7b1fda0ba56059a0179698"},
{file = "pandas-2.2.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c124333816c3a9b03fbeef3a9f230ba9a737e9e5bb4060aa2107a86cc0a497fc"},
+ {file = "pandas-2.2.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:63cc132e40a2e084cf01adf0775b15ac515ba905d7dcca47e9a251819c575ef3"},
{file = "pandas-2.2.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:29401dbfa9ad77319367d36940cd8a0b3a11aba16063e39632d98b0e931ddf32"},
{file = "pandas-2.2.3-cp311-cp311-win_amd64.whl", hash = "sha256:3fc6873a41186404dad67245896a6e440baacc92f5b716ccd1bc9ed2995ab2c5"},
{file = "pandas-2.2.3-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b1d432e8d08679a40e2a6d8b2f9770a5c21793a6f9f47fdd52c5ce1948a5a8a9"},
{file = "pandas-2.2.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a5a1595fe639f5988ba6a8e5bc9649af3baf26df3998a0abe56c02609392e0a4"},
+ {file = "pandas-2.2.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5de54125a92bb4d1c051c0659e6fcb75256bf799a732a87184e5ea503965bce3"},
{file = "pandas-2.2.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fffb8ae78d8af97f849404f21411c95062db1496aeb3e56f146f0355c9989319"},
+ {file = "pandas-2.2.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6dfcb5ee8d4d50c06a51c2fffa6cff6272098ad6540aed1a76d15fb9318194d8"},
{file = "pandas-2.2.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:062309c1b9ea12a50e8ce661145c6aab431b1e99530d3cd60640e255778bd43a"},
{file = "pandas-2.2.3-cp312-cp312-win_amd64.whl", hash = "sha256:59ef3764d0fe818125a5097d2ae867ca3fa64df032331b7e0917cf5d7bf66b13"},
{file = "pandas-2.2.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f00d1345d84d8c86a63e476bb4955e46458b304b9575dcf71102b5c705320015"},
{file = "pandas-2.2.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:3508d914817e153ad359d7e069d752cdd736a247c322d932eb89e6bc84217f28"},
+ {file = "pandas-2.2.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:22a9d949bfc9a502d320aa04e5d02feab689d61da4e7764b62c30b991c42c5f0"},
{file = "pandas-2.2.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3a255b2c19987fbbe62a9dfd6cff7ff2aa9ccab3fc75218fd4b7530f01efa24"},
+ {file = "pandas-2.2.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:800250ecdadb6d9c78eae4990da62743b857b470883fa27f652db8bdde7f6659"},
{file = "pandas-2.2.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6374c452ff3ec675a8f46fd9ab25c4ad0ba590b71cf0656f8b6daa5202bca3fb"},
{file = "pandas-2.2.3-cp313-cp313-win_amd64.whl", hash = "sha256:61c5ad4043f791b61dd4752191d9f07f0ae412515d59ba8f005832a532f8736d"},
{file = "pandas-2.2.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3b71f27954685ee685317063bf13c7709a7ba74fc996b84fc6821c59b0f06468"},
{file = "pandas-2.2.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:38cf8125c40dae9d5acc10fa66af8ea6fdf760b2714ee482ca691fc66e6fcb18"},
+ {file = "pandas-2.2.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ba96630bc17c875161df3818780af30e43be9b166ce51c9a18c1feae342906c2"},
{file = "pandas-2.2.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1db71525a1538b30142094edb9adc10be3f3e176748cd7acc2240c2f2e5aa3a4"},
+ {file = "pandas-2.2.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:15c0e1e02e93116177d29ff83e8b1619c93ddc9c49083f237d4312337a61165d"},
{file = "pandas-2.2.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ad5b65698ab28ed8d7f18790a0dc58005c7629f227be9ecc1072aa74c0c1d43a"},
{file = "pandas-2.2.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:bc6b93f9b966093cb0fd62ff1a7e4c09e6d546ad7c1de191767baffc57628f39"},
{file = "pandas-2.2.3-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:5dbca4c1acd72e8eeef4753eeca07de9b1db4f398669d5994086f788a5d7cc30"},
+ {file = "pandas-2.2.3-cp39-cp39-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8cd6d7cc958a3910f934ea8dbdf17b2364827bb4dafc38ce6eef6bb3d65ff09c"},
{file = "pandas-2.2.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:99df71520d25fade9db7c1076ac94eb994f4d2673ef2aa2e86ee039b6746d20c"},
+ {file = "pandas-2.2.3-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:31d0ced62d4ea3e231a9f228366919a5ea0b07440d9d4dac345376fd8e1477ea"},
{file = "pandas-2.2.3-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:7eee9e7cea6adf3e3d24e304ac6b8300646e2a5d1cd3a3c2abed9101b0846761"},
{file = "pandas-2.2.3-cp39-cp39-win_amd64.whl", hash = "sha256:4850ba03528b6dd51d6c5d273c46f183f39a9baf3f0143e566b89450965b105e"},
{file = "pandas-2.2.3.tar.gz", hash = "sha256:4f18ba62b61d7e192368b84517265a99b4d7ee8912f8708660fb4a366cc82667"},
@@ -5869,7 +5909,6 @@ description = "Pure-Python implementation of ASN.1 types and DER/BER/CER codecs
optional = true
python-versions = ">=3.8"
files = [
- {file = "pyasn1-0.6.1-py3-none-any.whl", hash = "sha256:0d632f46f2ba09143da3a8afe9e33fb6f92fa2320ab7e886e2d0f7672af84629"},
{file = "pyasn1-0.6.1.tar.gz", hash = "sha256:6f580d2bdd84365380830acf45550f2511469f673cb4a5ae3857a3170128b034"},
]
@@ -5880,7 +5919,6 @@ description = "A collection of ASN.1-based protocols modules"
optional = true
python-versions = ">=3.8"
files = [
- {file = "pyasn1_modules-0.4.1-py3-none-any.whl", hash = "sha256:49bfa96b45a292b711e986f222502c1c9a5e1f4e568fc30e2574a6c7d07838fd"},
{file = "pyasn1_modules-0.4.1.tar.gz", hash = "sha256:c28e2dbf9c06ad61c71a075c7e0f9fd0f1b0bb2d2ad4377f240d33ac2ab60a7c"},
]
@@ -9881,7 +9919,7 @@ test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools",
type = ["pytest-mypy"]
[extras]
-all = ["PyMuPDF", "accelerate", "agentops", "anthropic", "apify_client", "arxiv", "arxiv2text", "asknews", "azure-storage-blob", "beautifulsoup4", "botocore", "cohere", "datasets", "diffusers", "discord.py", "docker", "docx2txt", "duckduckgo-search", "firecrawl-py", "google-cloud-storage", "google-generativeai", "googlemaps", "imageio", "ipykernel", "jupyter_client", "litellm", "mistralai", "nebula3-python", "neo4j", "newspaper3k", "nltk", "notion-client", "openapi-spec-validator", "opencv-python", "pdfplumber", "pillow", "prance", "praw", "pyTelegramBotAPI", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "redis", "reka-api", "requests_oauthlib", "scholarly", "sentence-transformers", "sentencepiece", "slack-bolt", "slack-sdk", "soundfile", "tavily-python", "textblob", "torch", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]
+all = ["PyMuPDF", "accelerate", "agentops", "anthropic", "apify_client", "arxiv", "arxiv2text", "asknews", "azure-storage-blob", "beautifulsoup4", "botocore", "cohere", "datacommons", "datacommons_pandas", "datasets", "diffusers", "discord.py", "docker", "docx2txt", "duckduckgo-search", "firecrawl-py", "google-cloud-storage", "google-generativeai", "googlemaps", "imageio", "ipykernel", "jupyter_client", "litellm", "mistralai", "nebula3-python", "neo4j", "newspaper3k", "nltk", "notion-client", "openapi-spec-validator", "opencv-python", "pdfplumber", "pillow", "prance", "praw", "pyTelegramBotAPI", "pydub", "pygithub", "pymilvus", "pyowm", "qdrant-client", "rank-bm25", "redis", "reka-api", "requests_oauthlib", "scholarly", "sentence-transformers", "sentencepiece", "slack-bolt", "slack-sdk", "soundfile", "tavily-python", "textblob", "torch", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]
encoders = ["sentence-transformers"]
graph-storages = ["nebula3-python", "neo4j"]
huggingface-agent = ["accelerate", "datasets", "diffusers", "opencv-python", "sentencepiece", "soundfile", "torch", "torch", "transformers"]
@@ -9892,10 +9930,10 @@ rag = ["cohere", "nebula3-python", "neo4j", "pymilvus", "qdrant-client", "rank-b
retrievers = ["cohere", "rank-bm25"]
search-tools = ["duckduckgo-search", "tavily-python", "wikipedia", "wolframalpha"]
test = ["mock", "pytest", "pytest-asyncio"]
-tools = ["PyMuPDF", "agentops", "apify_client", "arxiv", "arxiv2text", "asknews", "beautifulsoup4", "discord.py", "docker", "docx2txt", "duckduckgo-search", "firecrawl-py", "googlemaps", "imageio", "ipykernel", "jupyter_client", "newspaper3k", "nltk", "notion-client", "openapi-spec-validator", "pdfplumber", "pillow", "prance", "praw", "pyTelegramBotAPI", "pydub", "pygithub", "pyowm", "requests_oauthlib", "scholarly", "slack-bolt", "slack-sdk", "textblob", "unstructured", "wikipedia", "wolframalpha"]
+tools = ["PyMuPDF", "agentops", "apify_client", "arxiv", "arxiv2text", "asknews", "beautifulsoup4", "datacommons", "datacommons_pandas", "discord.py", "docker", "docx2txt", "duckduckgo-search", "firecrawl-py", "googlemaps", "imageio", "ipykernel", "jupyter_client", "newspaper3k", "nltk", "notion-client", "openapi-spec-validator", "pdfplumber", "pillow", "prance", "praw", "pyTelegramBotAPI", "pydub", "pygithub", "pyowm", "requests_oauthlib", "scholarly", "slack-bolt", "slack-sdk", "textblob", "unstructured", "wikipedia", "wolframalpha"]
vector-databases = ["pymilvus", "qdrant-client"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.13"
-content-hash = "84ea4c2edea9a953abb9b0353ce3296e7343b97fd0397cdb56e30383aab003c3"
+content-hash = "b49bd4106eb3ed70a5cc22e20eb21592995f49e785c30e79749569f3e0b6a4d0"
diff --git a/pyproject.toml b/pyproject.toml
index c772f7ba7..6e49331e7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -94,6 +94,8 @@ nltk = { version = "3.8.1", optional = true }
asknews = { version = "^0.7.43", optional = true }
praw = { version = "^7.7.1", optional = true }
textblob = { version = "^0.18.0.post0", optional = true }
+datacommons = { version = "^1.4.3", optional = true }
+datacommons_pandas = { version = "^0.0.3", optional = true }
tavily-python = { version = "^0.5.0", optional = true }
scholarly = { extras = ["tor"], version = "1.7.11", optional = true }
arxiv = { version = "^2.1.3", optional = true }
@@ -205,6 +207,8 @@ tools = [
"asknews",
"praw",
"textblob",
+ "datacommons",
+ "datacommons_pandas",
"scholarly",
"pdfplumber",
"apify_client",
@@ -306,6 +310,8 @@ all = [
"azure-storage-blob",
"google-cloud-storage",
"botocore",
+ "datacommons",
+ "datacommons_pandas",
"tavily-python",
"apify_client",
]
@@ -449,6 +455,8 @@ module = [
"arxiv2text",
"praw",
"textblob",
+ "datacommons",
+ "datacommons_pandas",
"tavily-python",
"scholarly",
"notion-client",
diff --git a/test/toolkits/test_data_commons_toolkit.py b/test/toolkits/test_data_commons_toolkit.py
new file mode 100644
index 000000000..a155c7f9b
--- /dev/null
+++ b/test/toolkits/test_data_commons_toolkit.py
@@ -0,0 +1,250 @@
+# =========== Copyright 2023 @ 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 @ CAMEL-AI.org. All Rights Reserved. ===========
+from unittest.mock import patch
+
+from camel.toolkits.data_commons_toolkit import DataCommonsToolkit
+
+
+def test_query_data_commons():
+ dc_toolkit = DataCommonsToolkit()
+ query = '''
+ SELECT ?name ?dcid
+ WHERE {
+ ?a typeOf Place .
+ ?a name ?name .
+ ?a dcid ("geoId/06" "geoId/21" "geoId/24") .
+ ?a dcid ?dcid
+ }
+ '''
+ expected_result = [
+ {'?name': 'Kentucky', '?dcid': 'geoId/21'},
+ {'?name': 'California', '?dcid': 'geoId/06'},
+ {'?name': 'Maryland', '?dcid': 'geoId/24'},
+ ]
+
+ with patch('datacommons.query') as mock_query:
+ mock_query.return_value = expected_result
+ try:
+ result = dc_toolkit.query_data_commons(query)
+ assert result == expected_result
+ print("test_query_data_commons passed successfully")
+ except Exception as e:
+ print(f"An error occurred: {e!s}")
+ print(f"Result: {result}")
+ raise
+
+
+def test_get_triples():
+ dc_toolkit = DataCommonsToolkit()
+ dcids = ['dc/c3j78rpyssdmf', 'dc/7hfhd2ek8ppd2']
+ expected_result = {
+ 'dc/c3j78rpyssdmf': [
+ ('dc/c3j78rpyssdmf', 'provenance', 'dc/h2lkz1'),
+ ('dc/zn6l0flenf3m6', 'biosampleOntology', 'dc/c3j78rpyssdmf'),
+ ('dc/tkcknpfwxfrhf', 'biosampleOntology', 'dc/c3j78rpyssdmf'),
+ ('dc/jdzbbfhgzghv1', 'biosampleOntology', 'dc/c3j78rpyssdmf'),
+ ('dc/4f9w8lhcwggxc', 'biosampleOntology', 'dc/c3j78rpyssdmf'),
+ ],
+ 'dc/7hfhd2ek8ppd2': [
+ ('dc/4mjs95b1meh1h', 'biosampleOntology', 'dc/7hfhd2ek8ppd2'),
+ ('dc/13xcyzcr819cb', 'biosampleOntology', 'dc/7hfhd2ek8ppd2'),
+ ('dc/7hfhd2ek8ppd2', 'provenance', 'dc/h2lkz1'),
+ ],
+ }
+
+ with patch('datacommons.get_triples') as mock_get_triples:
+ mock_get_triples.return_value = expected_result
+ result = dc_toolkit.get_triples(dcids)
+ assert result == expected_result
+ mock_get_triples.assert_called()
+ assert (
+ mock_get_triples.call_args[0][0] == dcids
+ ) # Check that dcids were passed correctly
+ print("test_get_triples passed successfully")
+
+
+def test_get_property_labels():
+ dc_toolkit = DataCommonsToolkit()
+ dcids = ['geoId/5508']
+ expected_result = {
+ 'geoId/5508': [
+ 'containedInPlace',
+ 'geoId',
+ 'geoJsonCoordinates',
+ 'geoOverlaps',
+ 'kmlCoordinates',
+ 'landArea',
+ 'latitude',
+ 'longitude',
+ 'name',
+ 'provenance',
+ 'typeOf',
+ 'usCensusGeoId',
+ 'waterArea',
+ ]
+ }
+
+ with patch('datacommons.get_property_labels') as mock_get_property_labels:
+ mock_get_property_labels.return_value = expected_result
+ result = dc_toolkit.get_property_labels(dcids, out=True)
+ assert result == expected_result
+ mock_get_property_labels.assert_called_once_with(dcids, out=True)
+ print("test_get_property_labels passed successfully")
+
+
+def test_get_property_values():
+ dc_toolkit = DataCommonsToolkit()
+ dcids = ["country/MDG"]
+ prop, out, value_type = 'affectedPlace', False, 'EarthquakeEvent'
+ expected_result = {
+ 'country/MDG': [
+ 'earthquake/us10007snb',
+ 'earthquake/us200040me',
+ 'earthquake/us60003r15',
+ 'earthquake/us70009fim',
+ 'earthquake/us7000h164',
+ 'earthquake/usc000evr6',
+ 'earthquake/usp00005zf',
+ 'earthquake/usp00006yt',
+ 'earthquake/usp0000afz',
+ 'earthquake/usp0001fcd',
+ 'earthquake/usp0001ss5',
+ 'earthquake/usp00020ud',
+ 'earthquake/usp0002kfd',
+ 'earthquake/usp0004qn4',
+ 'earthquake/usp0005gu9',
+ 'earthquake/usp0007k9j',
+ 'earthquake/usp0008vc6',
+ 'earthquake/usp00091ab',
+ 'earthquake/usp000dckw',
+ 'earthquake/usp000fu24',
+ 'earthquake/usp000gd93',
+ 'earthquake/usp000gmuf',
+ 'earthquake/usp000h6zw',
+ 'earthquake/usp000jgbb',
+ ]
+ }
+
+ with patch('datacommons.get_property_values') as mock_get_property_values:
+ mock_get_property_values.return_value = expected_result
+ result = dc_toolkit.get_property_values(
+ dcids, prop, out, value_type, 10
+ )
+ assert result == expected_result
+ mock_get_property_values.assert_called_once_with(
+ dcids, prop, out, value_type, 10
+ )
+ print("test_get_property_values passed successfully")
+
+
+def test_get_places_in():
+ dc_toolkit = DataCommonsToolkit()
+ dcids = ["geoId/15", "geoId/02"]
+ place_type = "CongressionalDistrict"
+ expected_result = {
+ 'geoId/15': ['geoId/1501', 'geoId/1502'],
+ 'geoId/02': ['geoId/0200'],
+ }
+
+ with patch('datacommons.get_places_in') as mock_get_places_in:
+ mock_get_places_in.return_value = expected_result
+ result = dc_toolkit.get_places_in(dcids, place_type)
+ assert result == expected_result
+ mock_get_places_in.assert_called_once_with(dcids, place_type)
+ print("test_get_places_in passed successfully")
+
+
+def test_get_stat_value():
+ dc_toolkit = DataCommonsToolkit()
+ place = "geoId/12086" # Miami-Dade County
+ stat_var = "RetailDrugDistribution_DrugDistribution_Naloxone"
+ unit = "Grams"
+ expected_result = 118.79
+
+ with patch('datacommons.get_stat_value') as mock_get_stat_value:
+ mock_get_stat_value.return_value = expected_result
+ result = dc_toolkit.get_stat_value(place, stat_var, unit=unit)
+ assert result == expected_result
+ mock_get_stat_value.assert_called_once_with(
+ place, stat_var, None, None, None, unit, None
+ )
+ print("test_get_stat_value passed successfully")
+
+
+def test_get_stat_all():
+ dc_toolkit = DataCommonsToolkit()
+ places = ["geoId/27", "geoId/55"]
+ stat_vars = ["Count_Person_EducationalAttainmentDoctorateDegree"]
+ expected_result = {
+ 'geoId/27': {
+ 'Count_Person_EducationalAttainmentDoctorateDegree': {
+ 'sourceSeries': [
+ {
+ 'val': {
+ '2016': 50039,
+ '2017': 52737,
+ '2018': 54303,
+ '2012': 40961,
+ '2013': 42511,
+ '2014': 44713,
+ '2015': 47323,
+ },
+ 'measurementMethod': 'CensusACS5yrSurvey',
+ 'importName': 'CensusACS5YearSurvey',
+ 'provenanceDomain': 'census.gov',
+ 'provenanceUrl': 'https://www.census.gov/',
+ }
+ ]
+ }
+ },
+ 'geoId/55': {
+ 'Count_Person_EducationalAttainmentDoctorateDegree': {
+ 'sourceSeries': [
+ {
+ 'val': {
+ '2017': 43737,
+ '2018': 46071,
+ '2012': 38052,
+ '2013': 38711,
+ '2014': 40133,
+ '2015': 41387,
+ '2016': 42590,
+ },
+ 'measurementMethod': 'CensusACS5yrSurvey',
+ 'importName': 'CensusACS5YearSurvey',
+ 'provenanceDomain': 'census.gov',
+ 'provenanceUrl': 'https://www.census.gov/',
+ }
+ ]
+ }
+ },
+ }
+
+ with patch('datacommons.get_stat_all') as mock_get_stat_all:
+ mock_get_stat_all.return_value = expected_result
+ result = dc_toolkit.get_stat_all(places, stat_vars)
+ assert result == expected_result
+ mock_get_stat_all.assert_called_once_with(places, stat_vars)
+ print("test_get_stat_all passed successfully")
+
+
+if __name__ == '__main__':
+ test_query_data_commons()
+ test_get_triples()
+ test_get_property_labels()
+ test_get_property_values()
+ test_get_places_in()
+ test_get_stat_all()
+ test_get_stat_value()
+ print("All tests completed successfully!")