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: Notion toolkit integration (#1111)

Will Shang36b3713a4055
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.py
index 28ecd5d73..f6535963a 100644
--- a/camel/toolkits/__init__.py
+++ b/camel/toolkits/__init__.py
@@ -20,7 +20,6 @@ from .function_tool import (
)
from .open_api_specs.security_config import openapi_security_config
-
from .math_toolkit import MathToolkit, MATH_FUNCS
from .search_toolkit import SearchToolkit, SEARCH_FUNCS
from .weather_toolkit import WeatherToolkit, WEATHER_FUNCS
@@ -39,6 +38,7 @@ from .slack_toolkit import SlackToolkit
from .twitter_toolkit import TwitterToolkit, TWITTER_FUNCS
from .open_api_toolkit import OpenAPIToolkit
from .retrieval_toolkit import RetrievalToolkit
+from .notion_toolkit import NotionToolkit
__all__ = [
'BaseToolkit',
@@ -63,6 +63,7 @@ __all__ = [
'AskNewsToolkit',
'AsyncAskNewsToolkit',
'GoogleScholarToolkit',
+ 'NotionToolkit',
'ArxivToolkit',
'MATH_FUNCS',
'SEARCH_FUNCS',
diff --git a/camel/toolkits/notion_toolkit.py b/camel/toolkits/notion_toolkit.py
new file mode 100644
index 000000000..a81cc0905
--- /dev/null
+++ b/camel/toolkits/notion_toolkit.py
@@ -0,0 +1,279 @@
+# =========== 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 os
+from typing import List, Optional, cast
+
+from camel.toolkits import FunctionTool
+from camel.toolkits.base import BaseToolkit
+
+
+def get_plain_text_from_rich_text(rich_text: List[dict]) -> str:
+ r"""Extracts plain text from a list of rich text elements.
+
+ Args:
+ rich_text: A list of dictionaries representing rich text elements.
+ Each dictionary should contain a key named "plain_text" with
+ the plain text content.
+
+ Returns:
+ str: A string containing the combined plain text from all elements,
+ joined together.
+ """
+ plain_texts = [element.get("plain_text", "") for element in rich_text]
+ return "".join(plain_texts)
+
+
+def get_media_source_text(block: dict) -> str:
+ r"""Extracts the source URL and optional caption from a
+ Notion media block.
+
+ Args:
+ block: A dictionary representing a Notion media block.
+
+ Returns:
+ A string containing the source URL and caption (if available),
+ separated by a colon.
+ """
+ block_type = block.get("type", "Unknown Type")
+ block_content = block.get(block_type, {})
+
+ # Extract source URL based on available types
+ source = (
+ block_content.get("external", {}).get("url")
+ or block_content.get("file", {}).get("url")
+ or block_content.get(
+ "url", "[Missing case for media block types]: " + block_type
+ )
+ )
+
+ # Extract caption if available
+ caption_elements = block_content.get("caption", [])
+ if caption_elements:
+ caption = get_plain_text_from_rich_text(caption_elements)
+ return f"{caption}: {source}"
+
+ return source
+
+
+class NotionToolkit(BaseToolkit):
+ r"""A toolkit for retrieving information from the user's notion pages.
+
+ Attributes:
+ notion_token (Optional[str], optional): The notion_token used to
+ interact with notion APIs.(default: :obj:`None`)
+ notion_client (module): The notion module for interacting with
+ the notion APIs.
+ """
+
+ def __init__(
+ self,
+ notion_token: Optional[str] = None,
+ ) -> None:
+ r"""Initializes the NotionToolkit.
+
+ Args:
+ notion_token (Optional[str], optional): The optional notion_token
+ used to interact with notion APIs.(default: :obj:`None`)
+ """
+ from notion_client import Client
+
+ self.notion_token = notion_token or os.environ.get("NOTION_TOKEN")
+ self.notion_client = Client(auth=self.notion_token)
+
+ def list_all_users(self) -> List[dict]:
+ r"""Lists all users via the Notion integration.
+
+ Returns:
+ List[dict]: A list of user objects with type, name, and workspace.
+ """
+ all_users_info: List[dict] = []
+ cursor = None
+
+ while True:
+ response = cast(
+ dict,
+ self.notion_client.users.list(start_cursor=cursor),
+ )
+ all_users_info.extend(response["results"])
+
+ if not response["has_more"]:
+ break
+
+ cursor = response["next_cursor"]
+
+ formatted_users = [
+ {
+ "type": user["type"],
+ "name": user["name"],
+ "workspace": user.get(user.get("type"), {}).get(
+ "workspace_name", ""
+ ),
+ }
+ for user in all_users_info
+ ]
+
+ return formatted_users
+
+ def list_all_pages(self) -> List[dict]:
+ r"""Lists all pages in the Notion workspace.
+
+ Returns:
+ List[dict]: A list of page objects with title and id.
+ """
+ all_pages_info: List[dict] = []
+ cursor = None
+
+ while True:
+ response = cast(
+ dict,
+ self.notion_client.search(
+ filter={"property": "object", "value": "page"},
+ start_cursor=cursor,
+ ),
+ )
+ all_pages_info.extend(response["results"])
+
+ if not response["has_more"]:
+ break
+
+ cursor = response["next_cursor"]
+
+ formatted_pages = [
+ {
+ "id": page.get("id"),
+ "title": next(
+ (
+ title.get("text", {}).get("content")
+ for title in page["properties"]
+ .get("title", {})
+ .get("title", [])
+ if title["type"] == "text"
+ ),
+ None,
+ ),
+ }
+ for page in all_pages_info
+ ]
+
+ return formatted_pages
+
+ def get_notion_block_text_content(self, block_id: str) -> str:
+ r"""Retrieves the text content of a Notion block.
+
+ Args:
+ block_id (str): The ID of the Notion block to retrieve.
+
+ Returns:
+ str: The text content of a Notion block, containing all
+ the sub blocks.
+ """
+ blocks: List[dict] = []
+ cursor = None
+
+ while True:
+ response = cast(
+ dict,
+ self.notion_client.blocks.children.list(
+ block_id=block_id, start_cursor=cursor
+ ),
+ )
+ blocks.extend(response["results"])
+
+ if not response["has_more"]:
+ break
+
+ cursor = response["next_cursor"]
+
+ block_text_content = " ".join(
+ [self.get_text_from_block(sub_block) for sub_block in blocks]
+ )
+
+ return block_text_content
+
+ def get_text_from_block(self, block: dict) -> str:
+ r"""Extracts plain text from a Notion block based on its type.
+
+ Args:
+ block (dict): A dictionary representing a Notion block.
+
+ Returns:
+ str: A string containing the extracted plain text and block type.
+ """
+ # Get rich text for supported block types
+ if block.get(block.get("type"), {}).get("rich_text"):
+ # Empty string if it's an empty line
+ text = get_plain_text_from_rich_text(
+ block[block["type"]]["rich_text"]
+ )
+ else:
+ # Handle block types by case
+ block_type = block.get("type")
+ if block_type == "unsupported":
+ text = "[Unsupported block type]"
+ elif block_type == "bookmark":
+ text = block["bookmark"]["url"]
+ elif block_type == "child_database":
+ text = block["child_database"]["title"]
+ # Use other API endpoints for full database data
+ elif block_type == "child_page":
+ text = block["child_page"]["title"]
+ elif block_type in ("embed", "video", "file", "image", "pdf"):
+ text = get_media_source_text(block)
+ elif block_type == "equation":
+ text = block["equation"]["expression"]
+ elif block_type == "link_preview":
+ text = block["link_preview"]["url"]
+ elif block_type == "synced_block":
+ if block["synced_block"].get("synced_from"):
+ text = (
+ f"This block is synced with a block with ID: "
+ f"""
+ {block['synced_block']['synced_from']
+ [block['synced_block']['synced_from']['type']]}
+ """
+ )
+ else:
+ text = (
+ "Source sync block that another"
+ + "blocked is synced with."
+ )
+ elif block_type == "table":
+ text = f"Table width: {block['table']['table_width']}"
+ # Fetch children for full table data
+ elif block_type == "table_of_contents":
+ text = f"ToC color: {block['table_of_contents']['color']}"
+ elif block_type in ("breadcrumb", "column_list", "divider"):
+ text = "No text available"
+ else:
+ text = "[Needs case added]"
+
+ # Query children for blocks with children
+ if block.get("has_children"):
+ text += self.get_notion_block_text_content(block["id"])
+
+ return text
+
+ 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.list_all_pages),
+ FunctionTool(self.list_all_users),
+ FunctionTool(self.get_notion_block_text_content),
+ ]
diff --git a/examples/tool_call/google_scholar_toolkit.py b/examples/tool_call/google_scholar_toolkit.py
index f20cb7fed..facf628fc 100644
--- a/examples/tool_call/google_scholar_toolkit.py
+++ b/examples/tool_call/google_scholar_toolkit.py
@@ -28,6 +28,7 @@ sys_msg = BaseMessage.make_assistant_message(
tools = GoogleScholarToolkit(
author_identifier="https://scholar.google.com/citations?user=JicYPdAAAAAJ&hl=en&oi=ao"
).get_tools()
+
model_config_dict = ChatGPTConfig(
temperature=0.0,
).as_dict()
diff --git a/examples/tool_call/notion_toolkit.py b/examples/tool_call/notion_toolkit.py
new file mode 100644
index 000000000..a84af1f97
--- /dev/null
+++ b/examples/tool_call/notion_toolkit.py
@@ -0,0 +1,98 @@
+# =========== 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.agents import ChatAgent
+from camel.configs.openai_config import ChatGPTConfig
+from camel.messages import BaseMessage
+from camel.models import ModelFactory
+from camel.toolkits import NotionToolkit
+from camel.types import ModelPlatformType, ModelType
+
+# Define system message
+sys_msg = BaseMessage.make_assistant_message(
+ role_name="Tools calling opertor", content="You are a helpful assistant"
+)
+
+# Set model config
+tools = NotionToolkit().get_tools()
+model_config_dict = ChatGPTConfig(
+ temperature=0.0,
+).as_dict()
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.OPENAI,
+ model_type=ModelType.GPT_4O_MINI,
+ model_config_dict=model_config_dict,
+)
+
+# Set agent
+camel_agent = ChatAgent(
+ system_message=sys_msg,
+ model=model,
+ tools=tools,
+)
+camel_agent.reset()
+
+# Define a user message
+usr_msg = BaseMessage.make_user_message(
+ role_name="CAMEL User",
+ content="Lists all pages in the Notion workspace",
+)
+
+# Get response information
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls'])[:1000])
+"""
+==========================================================================
+[FunctionCallingRecord(func_name='list_all_pages', args={}, result=[{'id':
+'12684f56-4caa-8080-be91-d7fb1a5834e3', 'title': 'test page'},
+{'id': '47a4fb54-e34b-4b45-9928-aa2802982eb8', 'title': 'Aigentbot'}])]
+"""
+
+usr_msg = BaseMessage.make_user_message(
+ role_name="CAMEL User",
+ content="Retrieves the text content of a Notion block which id is"
+ + "'12684f56-4caa-8080-be91-d7fb1a5834e3'",
+)
+
+# Get response information
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls'])[:1000])
+"""
+==========================================================================
+[FunctionCallingRecord(func_name='get_notion_block_text_content', args=
+{'block_id': '12684f56-4caa-8080-be91-d7fb1a5834e3'}, result='hellonihao
+buhao this is a test par [Needs case added] another par [Needs case added]
+A cute cat: https://www.google.com/imgres?q=cat&imgurl=https%3A%2F%2Fi.
+natgeofe.com%2Fn%2F548467d8-c5f1-4551-9f58-6817a8d2c45e%2FNationalGeographic
+_2572187_square.jpg&imgrefurl=https%3A%2F%2Fwww.nationalgeographic.com%2F
+animals%2Fmammals%2Ffacts%2Fdomestic-cat&docid=K6Qd9XWnQFQCoM&tbnid=eAP24
+4UcF5wdYM&vet=12ahUKEwir9rf3oKGJAxVsFTQIHYsrMYkQM3oECBkQAA..i&w=3072&h=307
+2&hcb=2&ved=2ahUKEwir9rf3oKGJAxVsFTQIHYsrMYkQM3oECBkQAA')]
+"""
+
+usr_msg = BaseMessage.make_user_message(
+ role_name="CAMEL User",
+ content="List names of users via the Notion integration",
+)
+
+# Get response information
+response = camel_agent.step(usr_msg)
+print(str(response.info['tool_calls'])[:1000])
+"""
+==========================================================================
+[FunctionCallingRecord(func_name='list_all_users', args={}, result=[{'type':
+'person', 'name': 'user a', 'workspace': ''}, {'type': 'bot', 'name':
+'test', 'workspace': "user a's Notion"}])]
+"""
diff --git a/poetry.lock b/poetry.lock
index efaa1f47c..cdeb1cf23 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -2902,13 +2902,13 @@ test = ["flaky", "ipyparallel", "pre-commit", "pytest (>=7.0)", "pytest-asyncio
[[package]]
name = "ipython"
-version = "8.28.0"
+version = "8.29.0"
description = "IPython: Productive Interactive Computing"
optional = true
python-versions = ">=3.10"
files = [
- {file = "ipython-8.28.0-py3-none-any.whl", hash = "sha256:530ef1e7bb693724d3cdc37287c80b07ad9b25986c007a53aa1857272dac3f35"},
- {file = "ipython-8.28.0.tar.gz", hash = "sha256:0d0d15ca1e01faeb868ef56bc7ee5a0de5bd66885735682e8a322ae289a13d1a"},
+ {file = "ipython-8.29.0-py3-none-any.whl", hash = "sha256:0188a1bd83267192123ccea7f4a8ed0a78910535dbaa3f37671dca76ebd429c8"},
+ {file = "ipython-8.29.0.tar.gz", hash = "sha256:40b60e15b22591450eef73e40a027cf77bd652e757523eebc5bd7c7c498290eb"},
]
[package.dependencies]
@@ -4423,6 +4423,20 @@ files = [
{file = "nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f"},
]
+[[package]]
+name = "notion-client"
+version = "2.2.1"
+description = "Python client for the official Notion API"
+optional = true
+python-versions = ">=3.7, <4"
+files = [
+ {file = "notion-client-2.2.1.tar.gz", hash = "sha256:3827e381ccb5a21aeb606686787edfb6c7a10681cb3507c4d606a1918e791061"},
+ {file = "notion_client-2.2.1-py2.py3-none-any.whl", hash = "sha256:4ecf9ec527a124462f7bd407d9c9ead9853a9b2c8f00e56f3fa8fb15106ad871"},
+]
+
+[package.dependencies]
+httpx = ">=0.15.0"
+
[[package]]
name = "numpy"
version = "1.26.4"
@@ -7763,13 +7777,13 @@ files = [
[[package]]
name = "slack-bolt"
-version = "1.21.1"
+version = "1.21.2"
description = "The Bolt Framework for Python"
optional = true
python-versions = ">=3.6"
files = [
- {file = "slack_bolt-1.21.1-py2.py3-none-any.whl", hash = "sha256:feb3c97ed7c388318d6e007a9c1b50dd88b0d59e64ff1f8c4e770db30e890ec8"},
- {file = "slack_bolt-1.21.1.tar.gz", hash = "sha256:f0f1e7223f0e5621a768d1efce470058619b4f4eacbec405625c8c813e489c20"},
+ {file = "slack_bolt-1.21.2-py2.py3-none-any.whl", hash = "sha256:6860fc8693ca543b653c5d49a09b8b542f5fb7a02638342a7ddd18d8bc6f3ba0"},
+ {file = "slack_bolt-1.21.2.tar.gz", hash = "sha256:05ac2d454adfddfc629fb63c7a3723bd1432a24373119368bc81f2f52b029cbf"},
]
[package.dependencies]
@@ -7777,13 +7791,13 @@ slack-sdk = ">=3.33.1,<4"
[[package]]
name = "slack-sdk"
-version = "3.33.1"
+version = "3.33.2"
description = "The Slack API Platform SDK for Python"
optional = true
python-versions = ">=3.6"
files = [
- {file = "slack_sdk-3.33.1-py2.py3-none-any.whl", hash = "sha256:ef93beec3ce9c8f64da02fd487598a05ec4bc9c92ceed58f122dbe632691cbe2"},
- {file = "slack_sdk-3.33.1.tar.gz", hash = "sha256:e328bb661d95db5f66b993b1d64288ac7c72201a745b4c7cf8848dafb7b74e40"},
+ {file = "slack_sdk-3.33.2-py2.py3-none-any.whl", hash = "sha256:8107912488028f5a3f04ee9c58524418d3a2763a843db25530375b7733e6ec0a"},
+ {file = "slack_sdk-3.33.2.tar.gz", hash = "sha256:34c51cfb9c254553219a0bba7a741c913f5d4d372d6278c3e7e10fe7bb667724"},
]
[package.extras]
@@ -9827,7 +9841,7 @@ test = ["big-O", "importlib-resources", "jaraco.functools", "jaraco.itertools",
type = ["pytest-mypy"]
[extras]
-all = ["PyMuPDF", "accelerate", "agentops", "anthropic", "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", "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", "textblob", "torch", "torch", "transformers", "unstructured", "wikipedia", "wolframalpha"]
+all = ["PyMuPDF", "accelerate", "agentops", "anthropic", "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", "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"]
@@ -9838,10 +9852,10 @@ rag = ["cohere", "nebula3-python", "neo4j", "pymilvus", "qdrant-client", "rank-b
retrievers = ["cohere", "rank-bm25"]
search-tools = ["duckduckgo-search", "wikipedia", "wolframalpha"]
test = ["mock", "pytest", "pytest-asyncio"]
-tools = ["PyMuPDF", "agentops", "arxiv", "arxiv2text", "asknews", "beautifulsoup4", "discord.py", "docker", "docx2txt", "duckduckgo-search", "firecrawl-py", "googlemaps", "imageio", "ipykernel", "jupyter_client", "newspaper3k", "nltk", "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", "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"]
vector-databases = ["pymilvus", "qdrant-client"]
[metadata]
lock-version = "2.0"
python-versions = ">=3.10,<3.13"
-content-hash = "a1983fb8ca72c647e6c4d6bc96813e6509ffda08414f551c41a012023142a3ce"
+content-hash = "b4cec55ebd8227386e1658ef0d0c204cd171c20b6907e4d5973fb180b210e55e"
diff --git a/pyproject.toml b/pyproject.toml
index 929d6cc0f..4f5ac3f13 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -100,6 +100,8 @@ arxiv2text = { version = "^0.1.14", optional = true }
jupyter_client = { version = "^8.6.2", optional = true }
ipykernel = { version = "^6.0.0", optional = true }
pdfplumber = { version = "^0.11.0", optional = true }
+notion-client = { version = "^2.2.1", optional = true }
+
# encoders
sentence-transformers = { version = "^3.0.1", optional = true }
@@ -202,6 +204,7 @@ tools = [
"textblob",
"scholarly",
"pdfplumber",
+ "notion-client",
]
vector-databases = [
@@ -274,6 +277,7 @@ all = [
"asknews",
"scholarly",
"pdfplumber",
+ "notion-client",
# vector-database
"qdrant-client",
"pymilvus",
@@ -440,5 +444,6 @@ module = [
"praw",
"textblob",
"scholarly",
+ "notion-client",
]
ignore_missing_imports = true
diff --git a/test/toolkits/test_notion_toolkit.py b/test/toolkits/test_notion_toolkit.py
new file mode 100644
index 000000000..11f568dba
--- /dev/null
+++ b/test/toolkits/test_notion_toolkit.py
@@ -0,0 +1,152 @@
+# =========== 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 import FunctionTool, NotionToolkit
+
+
+def test_get_user():
+ with patch('notion_client.Client') as mock_client:
+ # Mock the list_children method to return a sample block structure
+ mock_client = mock_client.return_value
+ mock_client.users.list.return_value = {
+ "results": [
+ {
+ "object": "user",
+ "id": "user id",
+ "name": "abc",
+ "avatar_url": "",
+ "type": "person",
+ "person": {"email": "[email protected]"},
+ },
+ {
+ "object": "user",
+ "id": "test id",
+ "name": "test",
+ "avatar_url": "",
+ "type": "bot",
+ "bot": {
+ "owner": {"type": "workspace", "workspace": "true"},
+ "workspace_name": "workspace name",
+ },
+ },
+ ],
+ "has_more": False,
+ }
+
+ notion_client = NotionToolkit()
+
+ users_list = notion_client.list_all_users()
+
+ expected_users = [
+ {"type": "person", "name": "abc", "workspace": ""},
+ {"type": "bot", "name": "test", "workspace": "workspace name"},
+ ]
+
+ assert users_list == expected_users
+
+
+def test_get_notion_block_text_content():
+ with patch('notion_client.Client') as mock_client:
+ # Mock the list_children method to return a sample block structure
+ mock_client = mock_client.return_value
+ mock_client.blocks.children.list.return_value = {
+ "results": [
+ {
+ "type": "paragraph",
+ "paragraph": {
+ "rich_text": [
+ {
+ "type": "text",
+ "text": {
+ "content": "This is a sample paragraph"
+ },
+ "plain_text": "This is a sample paragraph",
+ },
+ ]
+ },
+ },
+ {
+ "type": "unsupported",
+ },
+ ],
+ "has_more": False,
+ }
+
+ notion_client = NotionToolkit()
+
+ block_id = "block id"
+
+ text_content = notion_client.get_notion_block_text_content(block_id)
+
+ expected_text = "This is a sample paragraph [Unsupported block type]"
+
+ assert text_content == expected_text
+
+ mock_client.blocks.children.list.assert_called_once_with(
+ block_id=block_id, start_cursor=None
+ )
+
+
+def test_list_all_pages():
+ # Mock the search method to return sample page data
+ with patch('notion_client.Client') as mock_client:
+ mock_client = mock_client.return_value
+ mock_client.search.return_value = {
+ "results": [
+ {
+ "id": "page-id-1",
+ "properties": {
+ "title": {
+ "title": [
+ {"type": "text", "text": {"content": "Page 1"}}
+ ]
+ }
+ },
+ },
+ {
+ "id": "page-id-2",
+ "properties": {
+ "title": {
+ "title": [
+ {"type": "text", "text": {"content": "Page 2"}}
+ ]
+ }
+ },
+ },
+ ],
+ "has_more": False,
+ }
+
+ # Create a NotionToolkit instance
+ notion_client = NotionToolkit()
+
+ # Call the method under test
+ all_pages = notion_client.list_all_pages()
+
+ # Expected list of pages with titles and IDs
+ expected_pages = [
+ {"id": "page-id-1", "title": "Page 1"},
+ {"id": "page-id-2", "title": "Page 2"},
+ ]
+
+ # Assert that the returned list matches the expectation
+ assert all_pages == expected_pages
+
+
+def test_get_tools():
+ toolkit = NotionToolkit()
+ tools = toolkit.get_tools()
+ assert len(tools) == 3
+ assert all(isinstance(tool, FunctionTool) for tool in tools)