🐫 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
feat: Enhanced DingTalk toolkit integration - fixes #3050 (#3123)
LIHUA3eaf3856533c
diff --git a/camel/toolkits/__init__.py b/camel/toolkits/__init__.pyindex 3ce811023..f29ab67d4 100644--- a/camel/toolkits/__init__.py+++ b/camel/toolkits/__init__.py@@ -41,6 +41,7 @@ from .arxiv_toolkit import ArxivToolkitfrom .slack_toolkit import SlackToolkitfrom .whatsapp_toolkit import WhatsAppToolkitfrom .wechat_official_toolkit import WeChatOfficialToolkit+from .dingtalk import DingtalkToolkitfrom .twitter_toolkit import TwitterToolkitfrom .open_api_toolkit import OpenAPIToolkitfrom .retrieval_toolkit import RetrievalToolkit@@ -108,6 +109,7 @@ __all__ = ['SlackToolkit','WhatsAppToolkit','WeChatOfficialToolkit',+ 'DingtalkToolkit','ImageGenToolkit','TwitterToolkit','WeatherToolkit',diff --git a/camel/toolkits/dingtalk.py b/camel/toolkits/dingtalk.pynew file mode 100644index 000000000..9c89bc56b--- /dev/null+++ b/camel/toolkits/dingtalk.py@@ -0,0 +1,1138 @@+# ========= 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 base64+import hashlib+import hmac+import os+import re+import time+import urllib.parse+from typing import Any, Dict, List, Literal, Optional++import requests++from camel.logger import get_logger+from camel.toolkits import FunctionTool+from camel.toolkits.base import BaseToolkit+from camel.utils import MCPServer, api_keys_required, retry_on_error++logger = get_logger(__name__)++# Global variables for caching access token+_dingtalk_access_token = None+_dingtalk_access_token_expires_at = 0+++@retry_on_error()+def _get_dingtalk_access_token() -> str:+ r"""Gets access token for Dingtalk API.++ Returns:+ str: Access token for API requests.+ """+ global _dingtalk_access_token, _dingtalk_access_token_expires_at++ if (+ _dingtalk_access_token+ and _dingtalk_access_token_expires_at > time.time()+ ):+ return _dingtalk_access_token++ app_key = os.environ.get("DINGTALK_APP_KEY", "")+ app_secret = os.environ.get("DINGTALK_APP_SECRET", "")++ url = "https://oapi.dingtalk.com/gettoken"+ params = {"appkey": app_key, "appsecret": app_secret}++ response = requests.get(url, params=params, timeout=30)+ response.raise_for_status()+ data = response.json()++ if data.get("errcode") == 0 and "access_token" in data:+ _dingtalk_access_token = data["access_token"]+ _dingtalk_access_token_expires_at = (+ time.time() + data.get("expires_in", 7200) - 60+ )+ logger.info("Dingtalk access token refreshed.")+ return _dingtalk_access_token+ else:+ errcode = data.get("errcode")+ errmsg = data.get("errmsg", "Unknown error")+ raise ValueError(f"Failed to get access token {errcode}: {errmsg}")+++def _make_dingtalk_request(+ method: Literal["GET", "POST"], endpoint: str, **kwargs+) -> Dict[str, Any]:+ r"""Makes authenticated request to Dingtalk API.++ Args:+ method (Literal["GET", "POST"]): HTTP method to use.+ endpoint (str): API endpoint path.+ **kwargs: Additional arguments passed to requests.++ Returns:+ Dict[str, Any]: API response data.++ Raises:+ Exception: If API request fails or returns error.+ """+ global _dingtalk_access_token, _dingtalk_access_token_expires_at+ access_token = _get_dingtalk_access_token()++ # Handle URL parameter concatenation+ separator = "&" if "?" in endpoint else "?"+ url = f"https://oapi.dingtalk.com{endpoint}{separator}access_token={access_token}"++ if method.upper() == "GET":+ response = requests.get(url, **kwargs)+ else:+ response = requests.post(url, **kwargs)++ response.raise_for_status()+ data = response.json()++ if data.get("errcode") and data.get("errcode") != 0:+ errcode = data.get("errcode")+ errmsg = data.get("errmsg", "Unknown error")+ raise ValueError(f"Dingtalk API error {errcode}: {errmsg}")++ return data+++def _generate_signature(secret: str, timestamp: str) -> str:+ r"""Generates signature for Dingtalk webhook.++ Args:+ secret (str): Webhook secret.+ timestamp (str): Current timestamp.++ Returns:+ str: Generated signature.+ """+ string_to_sign = f"{timestamp}\n{secret}"+ hmac_code = hmac.new(+ secret.encode("utf-8"), string_to_sign.encode("utf-8"), hashlib.sha256+ ).digest()+ return base64.b64encode(hmac_code).decode('utf-8')+++@MCPServer()+class DingtalkToolkit(BaseToolkit):+ r"""A toolkit for Dingtalk operations.++ This toolkit provides methods to interact with the Dingtalk API,+ allowing users to send messages, manage users, departments, and handle+ webhook operations.+ """++ def __init__(self, timeout: Optional[float] = None):+ r"""Initializes the DingtalkToolkit.++ Args:+ timeout (Optional[float]): Timeout for API requests in seconds.+ """+ super().__init__(timeout=timeout)+ self.base_url = "https://oapi.dingtalk.com"++ # Validate credentials+ app_key = os.environ.get("DINGTALK_APP_KEY", "")+ app_secret = os.environ.get("DINGTALK_APP_SECRET", "")++ if not all([app_key, app_secret]):+ raise ValueError(+ "Dingtalk credentials missing. Set DINGTALK_APP_KEY and"+ " DINGTALK_APP_SECRET."+ )++ # Initialize access token for enterprise reliability+ self._initialize_token_safely()++ def _initialize_token_safely(self):+ r"""Safely initializes access token during toolkit setup.++ This method attempts to get an access token during initialization+ but doesn't raise exceptions if it fails, allowing the toolkit+ to be instantiated even if credentials are temporarily invalid.+ """+ try:+ _get_dingtalk_access_token()+ logger.info("Dingtalk toolkit initialized successfully.")+ except Exception as e:+ logger.warning(f"Failed to initialize access token: {e}")+ logger.warning(+ "Toolkit created but may fail on actual API calls. "+ "Check your credentials."+ )++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_text_message(+ self,+ userid: str,+ content: str,+ ) -> str:+ r"""Sends a text message to a Dingtalk user.++ Args:+ userid (str): The user's userid.+ content (str): Message content.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-single-chat-message+ """+ payload = {+ "msg": {"msgtype": "text", "text": {"content": content}},+ "userid": userid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"Message sent successfully to user {userid}."+ except Exception as e:+ return f"Failed to send message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_markdown_message(+ self,+ userid: str,+ title: str,+ markdown_content: str,+ ) -> str:+ r"""Sends a markdown message to a Dingtalk user.++ Args:+ userid (str): The user's userid.+ title (str): Message title.+ markdown_content (str): Markdown formatted content.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-single-chat-message+ """+ payload = {+ "msg": {+ "msgtype": "markdown",+ "markdown": {"title": title, "text": markdown_content},+ },+ "userid": userid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"Markdown message sent successfully to user {userid}."+ except Exception as e:+ return f"Failed to send markdown message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_user_info(+ self,+ userid: str,+ ) -> Dict[str, Any]:+ r"""Retrieves Dingtalk user information.++ Args:+ userid (str): The user's userid.++ Returns:+ Dict[str, Any]: User information or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-user-details+ """+ payload = {"userid": userid}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/v2/user/get",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get user info: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_department_list(+ self,+ dept_id: Optional[int] = None,+ ) -> Dict[str, Any]:+ r"""Retrieves list of departments.++ Args:+ dept_id (Optional[int]): Department ID. If None, gets root+ departments.++ Returns:+ Dict[str, Any]: Department list or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/obtain-the-department-list-v2+ """+ payload = {}+ if dept_id is not None:+ payload["dept_id"] = dept_id++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/v2/department/listsub",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get department list: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_department_users(+ self,+ dept_id: int,+ offset: int = 0,+ size: int = 100,+ ) -> Dict[str, Any]:+ r"""Retrieves users in a department.++ Args:+ dept_id (int): Department ID.+ offset (int): Offset for pagination (default: 0).+ size (int): Number of users to retrieve (default: 100, max: 100).++ Returns:+ Dict[str, Any]: Users list or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/queries-the-complete-information-of-a-department-user+ """+ payload = {"dept_id": dept_id, "offset": offset, "size": size}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/v2/user/list",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get department users: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_search_users_by_name(+ self,+ name: str,+ ) -> Dict[str, Any]:+ r"""Searches for users by name.++ Args:+ name (str): User name to search for.++ Returns:+ Dict[str, Any]: Search results or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-users+ """+ payload = {"name": name}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/user/search",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to search users: {e!s}"}++ # Include more webhook methods if useful. Double check link implementation+ # is done correctly here.+ def dingtalk_send_webhook_message(+ self,+ content: str,+ msgtype: Literal["text", "markdown", "link", "actionCard"] = "text",+ title: Optional[str] = None,+ webhook_url: Optional[str] = None,+ webhook_secret: Optional[str] = None,+ ) -> str:+ r"""Sends a message via Dingtalk webhook.++ Args:+ content (str): Message content.+ msgtype (Literal): Message type (text, markdown, link, actionCard).+ title (Optional[str]): Message title (required for markdown).+ webhook_url (Optional[str]): Webhook URL. If None, uses env var.+ webhook_secret (Optional[str]): Webhook secret. If None, uses env var.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/robots/custom-robot-access+ """+ # Get webhook configuration+ url = webhook_url or os.environ.get("DINGTALK_WEBHOOK_URL", "")+ secret = webhook_secret or os.environ.get("DINGTALK_WEBHOOK_SECRET", "")++ if not url:+ return "Error: Webhook URL not provided or set in environment"++ # Prepare message payload+ payload: Dict[str, Any] = {"msgtype": msgtype}++ if msgtype == "text":+ payload["text"] = {"content": content}+ elif msgtype == "markdown":+ if not title:+ return "Error: Title is required for markdown messages"+ payload["markdown"] = {"title": title, "text": content}+ elif msgtype == "link":+ # For link messages, content should be structured differently+ # This is a simplified implementation+ payload["link"] = {+ "text": content,+ "title": title or "Link Message",+ "messageUrl": "https://www.dingtalk.com/",+ }+ elif msgtype == "actionCard":+ payload["actionCard"] = {+ "title": title or "Action Card",+ "text": content,+ "singleTitle": "Read More",+ "singleURL": "https://www.dingtalk.com/",+ }++ # Add signature if secret is provided+ if secret:+ timestamp = str(round(time.time() * 1000))+ sign = _generate_signature(secret, timestamp)+ url += f"×tamp={timestamp}&sign={urllib.parse.quote(sign)}"++ try:+ response = requests.post(+ url,+ json=payload,+ headers={"Content-Type": "application/json"},+ timeout=self.timeout,+ )+ response.raise_for_status()++ result = response.json()+ if result.get("errcode") == 0:+ return "Webhook message sent successfully"+ else:+ return f"Webhook error: {result.get('errmsg', 'Unknown error')}"++ except Exception as e:+ return f"Failed to send webhook message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_create_group(+ self,+ name: str,+ owner: str,+ useridlist: List[str],+ ) -> Dict[str, Any]:+ r"""Creates a Dingtalk group.++ Args:+ name (str): Group name.+ owner (str): Group owner's userid.+ useridlist (List[str]): List of user IDs to add to the group.++ Returns:+ Dict[str, Any]: Group creation result with chatid or error.++ References:+ https://open.dingtalk.com/document/orgapp-server/create-group-session+ """+ payload = {+ "name": name,+ "owner": owner,+ "useridlist": useridlist,+ }++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/im/chat/create",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to create group: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_group_message(+ self,+ chatid: str,+ content: str,+ msgtype: Literal["text", "markdown"] = "text",+ ) -> str:+ r"""Sends a message to a Dingtalk group.++ Args:+ chatid (str): Group chat ID.+ content (str): Message content.+ msgtype (Literal["text", "markdown"]): Message type.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-group-messages+ """+ msg_data: Dict[str, Any] = {"msgtype": msgtype}++ if msgtype == "text":+ msg_data["text"] = {"content": content}+ elif msgtype == "markdown":+ msg_data["markdown"] = {"text": content}++ payload = {+ "msg": msg_data,+ "chatid": chatid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"Message sent successfully to group {chatid}."+ except Exception as e:+ return f"Failed to send group message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_link_message(+ self,+ userid: str,+ title: str,+ text: str,+ message_url: str,+ pic_url: Optional[str] = None,+ ) -> str:+ r"""Sends a link message to a Dingtalk user.++ Args:+ userid (str): The user's userid.+ title (str): Link title.+ text (str): Link description text.+ message_url (str): URL to link to.+ pic_url (Optional[str]): Picture URL for the link.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-single-chat-message+ """+ link_data: Dict[str, Any] = {+ "title": title,+ "text": text,+ "messageUrl": message_url,+ }++ if pic_url:+ link_data["picUrl"] = pic_url++ payload = {+ "msg": {"msgtype": "link", "link": link_data},+ "userid": userid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"Link message sent successfully to user {userid}."+ except Exception as e:+ return f"Failed to send link message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_action_card_message(+ self,+ userid: str,+ title: str,+ text: str,+ single_title: str,+ single_url: str,+ ) -> str:+ r"""Sends an action card message to a Dingtalk user.++ Args:+ userid (str): The user's userid.+ title (str): Card title.+ text (str): Card content text.+ single_title (str): Action button title.+ single_url (str): Action button URL.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-single-chat-message+ """+ payload = {+ "msg": {+ "msgtype": "actionCard",+ "actionCard": {+ "title": title,+ "text": text,+ "singleTitle": single_title,+ "singleURL": single_url,+ },+ },+ "userid": userid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"Action card message sent successfully to user {userid}."+ except Exception as e:+ return f"Failed to send action card message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_user_by_mobile(self, mobile: str) -> Dict[str, Any]:+ r"""Gets user information by mobile number.++ Args:+ mobile (str): User's mobile number. Should be a valid Chinese+ mobile number format (11 digits starting with 1).++ Returns:+ Dict[str, Any]: User information or error information.+ """+ # Validate mobile number format (Chinese mobile number: 11 digits starting with 1)+ mobile_pattern = r'^1[3-9]\d{9}$'+ if not re.match(mobile_pattern, mobile):+ return {+ "error": "Invalid mobile number format. Expected 11 digits starting with 1 (e.g., 13800000000)."+ }++ payload = {"mobile": mobile}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/v2/user/getbymobile",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get user by mobile: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_user_by_unionid(self, unionid: str) -> Dict[str, Any]:+ r"""Gets user information by unionid.++ Args:+ unionid (str): User's unique identifier across all DingTalk+ organizations. This is a global identifier that remains+ consistent even if the user belongs to multiple DingTalk+ organizations, unlike userid which is organization-specific.++ Returns:+ Dict[str, Any]: User information or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-a-user-by-the-union-id+ """+ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/user/getbyunionid",+ headers={"Content-Type": "application/json"},+ json={"unionid": unionid},+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get user by unionid: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_department_detail(self, dept_id: int) -> Dict[str, Any]:+ r"""Gets detailed information about a department.++ Args:+ dept_id (int): Department ID.++ Returns:+ Dict[str, Any]: Department details or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-department-details0-v2+ """+ payload = {"dept_id": dept_id}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/v2/department/get",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get department detail: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_oa_message(+ self,+ userid: str,+ message_url: str,+ head_bgcolor: str,+ head_text: str,+ body_title: str,+ body_content: str,+ ) -> str:+ r"""Sends an OA (Office Automation) message to a Dingtalk user.++ Args:+ userid (str): The user's userid.+ message_url (str): URL for the message action.+ head_bgcolor (str): Header background color (hex format).+ head_text (str): Header text.+ body_title (str): Body title.+ body_content (str): Body content.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/send-single-chat-message+ """+ oa_data: Dict[str, Any] = {+ "message_url": message_url,+ "head": {+ "bgcolor": head_bgcolor,+ "text": head_text,+ },+ "body": {+ "title": body_title,+ "form": [{"key": "Content:", "value": body_content}],+ },+ }++ payload = {+ "msg": {"msgtype": "oa", "oa": oa_data},+ "userid": userid,+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return f"OA message sent successfully to user {userid}."+ except Exception as e:+ return f"Failed to send OA message: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_group_info(self, chatid: str) -> Dict[str, Any]:+ r"""Gets information about a group chat.++ Args:+ chatid (str): Group chat ID.++ Returns:+ Dict[str, Any]: Group information or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-group-session-information+ """+ payload = {"chatid": chatid}++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/im/chat/get",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to get group info: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_update_group(+ self,+ chatid: str,+ name: Optional[str] = None,+ owner: Optional[str] = None,+ add_useridlist: Optional[List[str]] = None,+ del_useridlist: Optional[List[str]] = None,+ ) -> Dict[str, Any]:+ r"""Updates a Dingtalk group configuration.++ Args:+ chatid (str): Group chat ID.+ name (Optional[str]): New group name.+ owner (Optional[str]): New group owner userid.+ add_useridlist (Optional[List[str]]): List of user IDs to add.+ Note: Internally converted to comma-separated string as+ required by the DingTalk API.+ del_useridlist (Optional[List[str]]): List of user IDs to remove.+ Note: Internally converted to comma-separated string as+ required by the DingTalk API.++ Returns:+ Dict[str, Any]: Update result or error information.++ References:+ https://open.dingtalk.com/document/orgapp-server/modify-group-session+ """+ payload: Dict[str, Any] = {"chatid": chatid}++ if name:+ payload["name"] = name+ if owner:+ payload["owner"] = owner+ # Note: DingTalk update group API requires comma-separated string format+ # This is different from send_work_notification which uses array format+ if add_useridlist:+ payload["add_useridlist"] = ",".join(add_useridlist)+ if del_useridlist:+ payload["del_useridlist"] = ",".join(del_useridlist)++ try:+ data = _make_dingtalk_request(+ "POST",+ "/topapi/im/chat/update",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return data+ except Exception as e:+ return {"error": f"Failed to update group: {e!s}"}++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_send_work_notification(+ self,+ userid_list: List[str],+ msg_content: str,+ msg_type: Literal["text", "markdown"] = "text",+ ) -> str:+ r"""Sends work notification to multiple users.++ Args:+ userid_list (List[str]): List of user IDs to send to.+ Note: This API accepts array format, unlike some other APIs+ that require comma-separated strings.+ msg_content (str): Message content.+ msg_type (Literal["text", "markdown"]): Message type.++ Returns:+ str: Success or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/asynchronous-sending-of-enterprise-session-messages+ """+ if not userid_list:+ return "Error: userid_list cannot be empty"++ if len(userid_list) > 100:+ return "Error: Cannot send to more than 100 users at once"++ msg_data: Dict[str, Any] = {"msgtype": msg_type}+ if msg_type == "text":+ msg_data["text"] = {"content": msg_content}+ elif msg_type == "markdown":+ msg_data["markdown"] = {"text": msg_content}++ payload = {+ "msg": msg_data,+ "userid_list": userid_list, # Array format for this API+ }++ try:+ _make_dingtalk_request(+ "POST",+ "/topapi/message/corpconversation/asyncsend_v2",+ headers={"Content-Type": "application/json"},+ json=payload,+ )+ return (+ f"Work notification sent successfully to "+ f"{len(userid_list)} users."+ )+ except Exception as e:+ return f"Failed to send work notification: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_userid_by_phone(+ self,+ phone_number: str+ ) -> str:+ r"""Gets user ID by phone number for LLM agents.++ Args:+ phone_number (str): User's phone number.++ Returns:+ str: User ID or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-user-details+ """+ try:+ user_info = self.dingtalk_get_user_by_mobile(phone_number)+ if 'result' in user_info and 'userid' in user_info['result']:+ return user_info['result']['userid']+ else:+ return f"User not found for phone number: {phone_number}"+ except Exception as e:+ return f"Failed to get user ID by phone: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_userid_by_name(+ self,+ user_name: str+ ) -> str:+ r"""Gets user ID by user name for LLM agents.++ Args:+ user_name (str): User's display name.++ Returns:+ str: User ID or error message.++ References:+ https://open.dingtalk.com/document/orgapp-server/query-users+ """+ try:+ search_result = self.dingtalk_search_users_by_name(user_name)+ if 'result' in search_result and search_result['result']:+ # Return the first match+ return search_result['result'][0].get('userid',+ f"No userid found for user: {user_name}")+ else:+ return f"User not found with name: {user_name}"+ except Exception as e:+ return f"Failed to get user ID by name: {e!s}"++ @api_keys_required(+ [+ (None, "DINGTALK_APP_KEY"),+ (None, "DINGTALK_APP_SECRET"),+ ]+ )+ def dingtalk_get_department_id_by_name(+ self,+ department_name: str+ ) -> str:+ r"""Gets department ID by department name for LLM agents.++ Args:+ department_name (str): Department name to search for.++ Returns:+ str: Department ID or error message.+ """+ try:+ dept_list = self.dingtalk_get_department_list()+ if 'result' in dept_list:+ for dept in dept_list['result']:+ if dept.get('name') == department_name:+ return str(dept.get('id', ''))+ return f"Department not found: {department_name}"+ else:+ return f"Failed to get department list"+ except Exception as e:+ return f"Failed to get department ID by name: {e!s}"++ def dingtalk_get_chatid_by_group_name(+ self,+ group_name: str+ ) -> str:+ r"""Gets chat ID by group name for LLM agents.++ Note: This function provides guidance as Dingtalk API doesn't directly+ support searching groups by name. Users should use the group creation+ response or group management features to obtain chat IDs.++ Args:+ group_name (str): Group name to search for.++ Returns:+ str: Guidance message for obtaining chat ID.+ """+ return (+ f"To get chat ID for group '{group_name}': "+ "1. Use dingtalk_create_group() and save the returned chatid, or "+ "2. Contact group admin to provide the chat ID, or "+ "3. Use Dingtalk admin console to find the group ID. "+ "Chat IDs are typically returned when creating groups."+ )++ def get_tools(self) -> List[FunctionTool]:+ r"""Returns toolkit functions as tools."""+ return [+ # Original message functions+ FunctionTool(self.dingtalk_send_text_message),+ FunctionTool(self.dingtalk_send_markdown_message),+ FunctionTool(self.dingtalk_send_webhook_message),+ # New message types+ FunctionTool(self.dingtalk_send_link_message),+ FunctionTool(self.dingtalk_send_action_card_message),+ FunctionTool(self.dingtalk_send_oa_message),+ FunctionTool(self.dingtalk_send_work_notification),+ # User management functions+ FunctionTool(self.dingtalk_get_user_info),+ FunctionTool(self.dingtalk_get_user_by_mobile),+ FunctionTool(self.dingtalk_get_user_by_unionid),+ FunctionTool(self.dingtalk_search_users_by_name),+ # Department management functions+ FunctionTool(self.dingtalk_get_department_list),+ FunctionTool(self.dingtalk_get_department_users),+ FunctionTool(self.dingtalk_get_department_detail),+ # Group management functions+ FunctionTool(self.dingtalk_create_group),+ FunctionTool(self.dingtalk_send_group_message),+ FunctionTool(self.dingtalk_get_group_info),+ FunctionTool(self.dingtalk_update_group),+ # Helper functions for LLM agents to get IDs+ FunctionTool(self.dingtalk_get_userid_by_phone),+ FunctionTool(self.dingtalk_get_userid_by_name),+ FunctionTool(self.dingtalk_get_department_id_by_name),+ FunctionTool(self.dingtalk_get_chatid_by_group_name),+ ]+++# many other functionalities, cards etc build on top after initial works\ No newline at end of filediff --git a/camel/types/__init__.py b/camel/types/__init__.pyindex ec5a3a5f4..4b78ede24 100644--- a/camel/types/__init__.py+++ b/camel/types/__init__.py@@ -41,8 +41,8 @@ from .openai_types import (ChatCompletionAssistantMessageParam,ChatCompletionChunk,ChatCompletionMessage,- ChatCompletionMessageFunctionToolCall,ChatCompletionMessageParam,+ ChatCompletionMessageFunctionToolCall,ChatCompletionSystemMessageParam,ChatCompletionToolMessageParam,ChatCompletionUserMessageParam,diff --git a/examples/external_tools/use_external_tools.py b/examples/external_tools/use_external_tools.pyindex 50a1b0f6a..91df17659 100644--- a/examples/external_tools/use_external_tools.py+++ b/examples/external_tools/use_external_tools.py@@ -70,5 +70,5 @@ if __name__ == "__main__":Output:The video game "Portal" was released in 2007 as part of a bundle called The Orange Box for Windows, Xbox 360, and PlayStation 3.-ChatCompletionMessageFunctionToolCall(id='call_U5Xju7vYtAQAEW4D1M8R1kgs', function=Function(arguments='{"a": 2007, "b": 1776}', name='sub'), type='function')+ChatCompletionMessageToolCall(id='call_U5Xju7vYtAQAEW4D1M8R1kgs', function=Function(arguments='{"a": 2007, "b": 1776}', name='sub'), type='function')"""diff --git a/examples/toolkits/dingtalk.py b/examples/toolkits/dingtalk.pynew file mode 100644index 000000000..ee49bb122--- /dev/null+++ b/examples/toolkits/dingtalk.py@@ -0,0 +1,395 @@+# ========= 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 json+import os+from unittest.mock import MagicMock, patch++from camel.agents import ChatAgent+from camel.models import ModelFactory+from camel.toolkits import DingtalkToolkit+from camel.types import ModelPlatformType, ModelType+++def print_tool_calls(tool_calls):+ """Helper function to print tool calls with formatted JSON arguments."""+ for i, tool_call in enumerate(tool_calls, 1):+ print(f" {i}. {tool_call.tool_name}")+ print(" Args:")++ # Print each argument with proper formatting+ for key, value in tool_call.args.items():+ if isinstance(value, str) and ('\\n' in value or '\n' in value):+ # Handle multiline strings specially+ print(f" {key}: |")+ # Replace escaped newlines and split into lines+ lines = value.replace('\\n', '\n').split('\n')+ for line in lines:+ print(f" {line}")+ else:+ # Regular single-line values+ formatted_value = json.dumps(value, ensure_ascii=False)+ print(f" {key}: {formatted_value}")+ print()+++def main():+ # Set up mock environment variables for testing+ os.environ["DINGTALK_APP_KEY"] = "mock_app_key"+ os.environ["DINGTALK_APP_SECRET"] = "mock_app_secret"+ os.environ["DINGTALK_WEBHOOK_URL"] = (+ "https://oapi.dingtalk.com/robot/send?access_token=mock_webhook_token"+ )+ os.environ["DINGTALK_WEBHOOK_SECRET"] = "mock_webhook_secret"++ # Mock the DingtalkToolkit methods to return realistic responses+ with (+ patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token,+ patch(+ 'camel.toolkits.dingtalk._make_dingtalk_request'+ ) as mock_request,+ patch('camel.toolkits.dingtalk.requests.post') as mock_post,+ ):+ # Mock access token+ mock_token.return_value = "mock_access_token_12345"++ # Mock API responses+ mock_request.side_effect = [+ # get_department_list response+ {+ 'errcode': 0,+ 'department': [+ {'id': 1, 'name': '技术部', 'parentid': 0},+ {'id': 2, 'name': '产品部', 'parentid': 0},+ {'id': 3, 'name': '运营部', 'parentid': 0},+ ],+ },+ # send_text_message response+ {'errcode': 0, 'task_id': '12345'},+ # get_user_info response+ {+ 'errcode': 0,+ 'userid': 'test_userid',+ 'name': '测试用户',+ 'department': [1, 2],+ 'position': '高级工程师',+ 'mobile': '138****1234',+ 'email': '[email protected]',+ },+ # send_markdown_message response+ {'errcode': 0, 'task_id': '12346'},+ # search_users_by_name response+ {+ 'errcode': 0,+ 'userlist': [+ {+ 'userid': 'test_userid',+ 'name': '测试用户',+ 'department': [1],+ },+ {+ 'userid': 'test_user2',+ 'name': '测试用户2',+ 'department': [2],+ },+ {+ 'userid': 'test_user3',+ 'name': '测试用户3',+ 'department': [3],+ },+ ],+ },+ # send_text_message response (second call)+ {'errcode': 0, 'task_id': '12347'},+ # send_link_message response+ {'errcode': 0, 'task_id': '12348'},+ # send_action_card_message response+ {'errcode': 0, 'task_id': '12349'},+ # get_user_by_mobile response+ {+ 'errcode': 0,+ 'userid': 'mobile_user_123',+ 'name': '手机用户',+ 'mobile': '13800000000',+ 'department': [1],+ },+ # get_department_detail response+ {+ 'errcode': 0,+ 'id': 1,+ 'name': '技术部详细信息',+ 'parent_id': 0,+ 'member_count': 25,+ 'create_time': '2024-01-01T00:00:00Z',+ },+ # send_work_notification response+ {'errcode': 0, 'task_id': '12350'},+ # get_group_info response+ {+ 'errcode': 0,+ 'chatid': 'chat123',+ 'name': '项目讨论组',+ 'owner': 'owner_123',+ 'member_count': 8,+ 'create_time': '2024-01-15T10:00:00Z',+ },+ # update_group response+ {'errcode': 0},+ # send_oa_message response+ {'errcode': 0, 'task_id': '12351'},+ ]++ # Mock webhook responses+ mock_webhook_response = MagicMock()+ mock_webhook_response.json.return_value = {'errcode': 0}+ mock_post.return_value = mock_webhook_response++ print("🚀 Running Dingtalk Toolkit Examples with Mocked Responses")+ print("=" * 60)++ # Initialize Dingtalk toolkit+ dingtalk_toolkit = DingtalkToolkit()++ # Create model+ model = ModelFactory.create(+ model_platform=ModelPlatformType.DEFAULT,+ model_type=ModelType.DEFAULT,+ )++ # Create agent with Dingtalk toolkit+ agent = ChatAgent(+ system_message=(+ "You are a Dingtalk enterprise communication assistant. "+ "Help manage Dingtalk operations and send messages to users."+ ),+ model=model,+ tools=dingtalk_toolkit.get_tools(),+ )++ # Example 1: Get department list and send a text message+ print("\n1️⃣ Example 1: Get departments and send welcome message")+ response = agent.step(+ "Get the list of departments, then send a welcome message to user "+ "'test_userid' saying 'Welcome to our Dingtalk integration!'"+ )+ print("Text Message Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 2: Get user information and send markdown message+ print("\n2️⃣ Example 2: Get user info and send markdown message")+ response = agent.step(+ "Get detailed information about user 'test_userid', then send a "+ "markdown message with their details formatted nicely."+ )+ print("User Info and Markdown Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 3: Search users and send webhook notification+ print("\n3️⃣ Example 3: Search users and send webhook notification")+ response = agent.step(+ "Search for users with name containing 'test', then send a "+ "webhook "+ "message to notify about the search results."+ )+ print("User Search and Webhook Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 4: Send different message types+ print("\n4️⃣ Example 4: Send multiple message types")+ response = agent.step(+ "Send a text message to user 'test_userid' with content "+ "'Hello from CAMEL!', then send a webhook message with markdown "+ "format showing system status."+ )+ print("Multiple Message Types Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 5: Send different message types (new features)+ print("\n5️⃣ Example 5: Send link and action card messages")+ response = agent.step(+ "Send a link message to user 'test_userid' with title "+ "'Visit Our Website', description 'Click to visit our website', "+ "and URL 'https://camel-ai.org'. Then send an action card message "+ "with title 'Action Required', content 'Please review document', "+ "button text 'Review Now', and button URL 'https://docs.camel-ai.org'."+ )+ print("Link and Action Card Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 6: Advanced user management+ print("\n6️⃣ Example 6: Advanced user management")+ response = agent.step(+ "Get user information by mobile number '13800000000', then get "+ "detailed information about department ID 1, and finally send a "+ "work notification to users 'user1', 'user2', 'user3' with "+ "message 'Team meeting at 3 PM today'."+ )+ print("Advanced User Management Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ # Example 7: Group management with new features+ print("\n7️⃣ Example 7: Advanced group management")+ response = agent.step(+ "Get information about group 'chat123', then update the group by "+ "adding users 'newuser1' and 'newuser2' to it, and finally send "+ "an OA message to user 'test_userid' with title 'System Update', "+ "content 'System maintenance tonight'."+ )+ print("Advanced Group Management Response:", response.msg.content)+ print("Tool calls:")+ print_tool_calls(response.info['tool_calls'])+ print()++ print("=" * 60)+ print("✅ All examples completed with mocked responses!")+ print(f"📊 Total tools available: {len(dingtalk_toolkit.get_tools())}")+ print("📋 Copy the responses above to update the example file.")+++if __name__ == "__main__":+ main()++"""+============================================================++1️⃣ Example 1: Get departments and send welcome message+Text Message Response: I retrieved the department list and sent the welcome+message.++Departments found:+- 1: 技术部+- 2: 产品部+- 3: 运营部++Message delivery:+- Sent "Welcome to our Dingtalk integration!" to user test_userid.+Tool calls:+ 1. get_department_list+ Args:+ dept_id: null++ 2. send_text_message+ Args:+ userid: "test_userid"+ content: "Welcome to our Dingtalk integration!"++++2️⃣ Example 2: Get user info and send markdown message+User Info and Markdown Response: I fetched the user details and sent a+formatted markdown message.++User details:+- Name: 测试用户+- UserID: test_userid+- Departments: 技术部, 产品部+- Position: 高级工程师+- Mobile: 138****1234+- Email: [email protected]++Message: "User Profile — 测试用户" sent successfully.+Tool calls:+ 1. get_user_info+ Args:+ userid: "test_userid"++ 2. send_markdown_message+ Args:+ userid: "test_userid"+ title: "User Profile — 测试用户"+ markdown_content: |+ ### 用户资料++ - **姓名**: 测试用户+ - **用户ID**: test_userid+ - **部门**: 技术部, 产品部+ - **职位**: 高级工程师+ - **手机**: 138****1234+ - **邮箱**: [email protected]++++3️⃣ Example 3: Search users and send webhook notification+User Search and Webhook Response: Search completed and webhook notification+sent. Results:+- 测试用户 (test_userid) — 部门: 技术部+- 测试用户2 (test_user2) — 部门: 产品部+- 测试用户3 (test_user3) — 部门: 运营部+- Total: 3 users+Tool calls:+ 1. search_users_by_name+ Args:+ name: "test"++ 2. send_webhook_message+ Args:+ content: |+ # User search results for 'test'++ - 测试用户 (test_userid) — 部门: 技术部+ - 测试用户2 (test_user2) — 部门: 产品部+ - 测试用户3 (test_user3) — 部门: 运营部++ Total: 3 users found.+ msgtype: "markdown"+ title: "User Search Results"+ webhook_url: null+ webhook_secret: null++++4️⃣ Example 4: Send multiple message types+Multiple Message Types Response: Done — text message to test_userid sent and+webhook status message posted.+Tool calls:+ 1. send_text_message+ Args:+ userid: "test_userid"+ content: "Hello from CAMEL!"++ 2. send_webhook_message+ Args:+ content: |+ ### System Status++ - **Overall**: ✅ Operational+ - **Uptime**: 72 hours+ - **Services**:+ - API: ✅ Healthy+ - Messaging: ✅ Healthy+ - Database: ✅ Healthy++ _Last checked: just now_+ msgtype: "markdown"+ title: "System Status"+ webhook_url: null+ webhook_secret: null+++============================================================+"""diff --git a/examples/toolkits/github_toolkit.py b/examples/toolkits/github_toolkit.pyindex a3a626400..b761e0c13 100644--- a/examples/toolkits/github_toolkit.py+++ b/examples/toolkits/github_toolkit.py@@ -70,7 +70,7 @@ from typing import (Union,)-from openai.types.chat import ChatCompletionMessageFunctionToolCall+from openai.types.chat import ChatCompletionMessageToolCallf==============================================================================="""diff --git a/test/agents/test_chat_agent.py b/test/agents/test_chat_agent.pyindex 770c00432..373951d79 100644--- a/test/agents/test_chat_agent.py+++ b/test/agents/test_chat_agent.py@@ -19,10 +19,10 @@ from typing import Listfrom unittest.mock import AsyncMock, MagicMockimport pytest+from openai.types.chat import ChatCompletionMessageToolCallfrom openai.types.chat.chat_completion import Choicefrom openai.types.chat.chat_completion_message import ChatCompletionMessagefrom openai.types.chat.chat_completion_message_function_tool_call import (- ChatCompletionMessageFunctionToolCall,Function,)from openai.types.completion_usage import CompletionUsage@@ -267,7 +267,7 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{ \@@ -277,7 +277,7 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):),type='function',),- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123457',function=Function(arguments='{ \@@ -314,7 +314,7 @@ def test_chat_agent_step_with_external_tools(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{"a":1776,"b":2007}',@@ -399,7 +399,7 @@ async def test_chat_agent_astep_with_external_tools(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{ \@@ -409,7 +409,7 @@ async def test_chat_agent_astep_with_external_tools(step_call_count=3):),type='function',),- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123457',function=Function(arguments='{ \@@ -446,7 +446,7 @@ async def test_chat_agent_astep_with_external_tools(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{"a":1776,"b":2007}',@@ -906,7 +906,7 @@ def test_tool_calling_sync(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{ \@@ -918,7 +918,7 @@ def test_tool_calling_sync(step_call_count=3):),type='function',),- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123457',function=Function(arguments='{"a": 0, "b": 10}',@@ -952,7 +952,7 @@ def test_tool_calling_sync(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_kIJby7Y6As6gAbWoxDqxD6HG',function=Function(arguments='{"a":16,"b":10}',@@ -1079,7 +1079,7 @@ async def test_tool_calling_math_async(step_call_count=3):audio=None,function_call=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{ \@@ -1186,7 +1186,7 @@ async def test_tool_calling_async(step_call_count=3):# Reset tool_calls at the beginning of each new round of step() callif model.run.call_count % 2 == 1:model_backend_rsp_tool_async.choices[0].message.tool_calls = [- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id='call_mock_123456',function=Function(arguments='{"second":1}', name='async_sleep'diff --git a/test/models/test_sglang_model.py b/test/models/test_sglang_model.pyindex 08b4f6fdd..c44801dcb 100644--- a/test/models/test_sglang_model.py+++ b/test/models/test_sglang_model.py@@ -99,7 +99,7 @@ def test_sglang_function_call(sglang_model_cleanup):# Create a mock response objectfrom openai.types.chat.chat_completion_message_function_tool_call import (- ChatCompletionMessageFunctionToolCall,+ ChatCompletionMessageToolCall,)from camel.types import (@@ -122,7 +122,7 @@ def test_sglang_function_call(sglang_model_cleanup):role="assistant",content=None,tool_calls=[- ChatCompletionMessageFunctionToolCall(+ ChatCompletionMessageToolCall(id="0",type="function",function={"name": "test_tool", "arguments": "{}"},diff --git a/test/toolkits/test_dingtalk.py b/test/toolkits/test_dingtalk.pynew file mode 100644index 000000000..81c35c795--- /dev/null+++ b/test/toolkits/test_dingtalk.py@@ -0,0 +1,545 @@+# ========= 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, patch++import pytest++from camel.toolkits.dingtalk import (+ DingtalkToolkit,+ _get_dingtalk_access_token,+)++[email protected](autouse=True)+def set_env_vars(monkeypatch):+ """Set up environment variables for testing."""+ monkeypatch.setenv("DINGTALK_APP_KEY", "test_app_key")+ monkeypatch.setenv("DINGTALK_APP_SECRET", "test_app_secret")+ monkeypatch.setenv(+ "DINGTALK_WEBHOOK_URL",+ "https://oapi.dingtalk.com/robot/send?access_token=test_webhook_token",+ )+ monkeypatch.setenv("DINGTALK_WEBHOOK_SECRET", "test_webhook_secret")+++def test_toolkit_init():+ """Test toolkit initialization."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ assert toolkit.base_url == "https://oapi.dingtalk.com"+++def test_get_tools():+ """Test getting available tools."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ tools = toolkit.get_tools()+ # Check that we have the expected number of tools+ assert len(tools) >= 5 # send_text_message, send_markdown_message,+ # get_user_info, send_webhook_message, etc.+++@patch('camel.toolkits.dingtalk.requests.get')+def test_get_access_token(mock_get):+ """Test access token retrieval."""+ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'access_token': 'test_token',+ 'expires_in': 7200,+ 'errcode': 0,+ }+ mock_get.return_value = mock_response++ token = _get_dingtalk_access_token()+ assert token == 'test_token'+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_text_message(mock_request):+ """Test sending text message."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_text_message('test_userid', 'Hello World')+ assert 'Message sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_markdown_message(mock_request):+ """Test sending markdown message."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_markdown_message(+ 'test_userid', 'Test Title', '# Hello World'+ )+ assert 'Markdown message sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_user_info(mock_request):+ """Test getting user information."""+ expected_data = {+ 'userid': 'test_userid',+ 'name': 'Test User',+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_user_info('test_userid')+ assert result == expected_data+++@patch('camel.toolkits.dingtalk.requests.post')+def test_send_webhook_message(mock_post):+ """Test sending webhook message."""+ mock_response = MagicMock()+ mock_response.json.return_value = {'errcode': 0}+ mock_post.return_value = mock_response++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_webhook_message('Hello from webhook!')+ assert 'Webhook message sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_department_list(mock_request):+ """Test getting department list."""+ expected_data = {+ 'department': [+ {'id': 1, 'name': 'Test Department'},+ {'id': 2, 'name': 'Another Department'},+ ],+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_department_list()+ assert result == expected_data+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_search_users_by_name(mock_request):+ """Test searching users by name."""+ expected_data = {+ 'userlist': [+ {'userid': 'user1', 'name': 'John Doe'},+ {'userid': 'user2', 'name': 'Jane Smith'},+ ],+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.search_users_by_name('John')+ assert result == expected_data+++def test_missing_credentials(monkeypatch):+ """Test initialization with missing credentials."""+ monkeypatch.delenv("DINGTALK_APP_KEY", raising=False)++ with pytest.raises(ValueError, match="Dingtalk credentials missing"):+ DingtalkToolkit()+++def test_missing_webhook_url():+ """Test webhook message with missing webhook URL."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()++ # Test with no webhook URL in environment+ with patch.dict('os.environ', {}, clear=True):+ result = toolkit.send_webhook_message('Hello')+ assert 'Webhook URL not provided' in result+++@patch('camel.toolkits.dingtalk.requests.get')+def test_access_token_error_handling(mock_get):+ """Test access token retrieval with API error."""+ # Clear the global token cache+ import camel.toolkits.dingtalk as dingtalk_module++ dingtalk_module._dingtalk_access_token = None+ dingtalk_module._dingtalk_access_token_expires_at = 0++ mock_response = MagicMock()+ mock_response.json.return_value = {+ 'errcode': 40001,+ 'errmsg': 'Invalid app key',+ }+ mock_get.return_value = mock_response++ with pytest.raises(ValueError, match="Failed to get access token 40001"):+ _get_dingtalk_access_token()+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_text_message_error_handling(mock_request):+ """Test sending text message with API error."""+ mock_request.side_effect = Exception("Network error")++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_text_message('test_userid', 'Hello')+ assert 'Failed to send message' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_user_info_error_handling(mock_request):+ """Test getting user info with API error."""+ mock_request.side_effect = Exception("Network error")++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_user_info('test_userid')+ assert 'error' in result+ assert 'Failed to get user info' in result['error']+++def test_generate_signature():+ """Test signature generation for webhook."""+ from camel.toolkits.dingtalk import _generate_signature++ secret = "test_secret"+ timestamp = "1234567890"++ # Test that signature is generated (exact value depends on implementation)+ signature = _generate_signature(secret, timestamp)+ assert isinstance(signature, str)+ assert len(signature) > 0+++@patch('camel.toolkits.dingtalk.requests.post')+def test_webhook_with_signature(mock_post):+ """Test webhook message with signature."""+ mock_response = MagicMock()+ mock_response.json.return_value = {'errcode': 0}+ mock_post.return_value = mock_response++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()++ # Test webhook with custom secret+ result = toolkit.send_webhook_message(+ 'Hello with signature!', webhook_secret='custom_secret'+ )+ assert 'Webhook message sent successfully' in result++ # Verify that the request was made with signature parameters+ mock_post.assert_called_once()+ call_args = mock_post.call_args+ assert 'timestamp' in call_args[1]['json'] or 'timestamp' in str(+ call_args[0][0]+ )+++def test_toolkit_initialization_with_token_failure():+ """Test toolkit initialization when token fetch fails."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.side_effect = Exception("Token fetch failed")++ # Should not raise exception, just log warning+ toolkit = DingtalkToolkit()+ assert toolkit.base_url == "https://oapi.dingtalk.com"+++# ========= Tests for new extended features =========+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_link_message(mock_request):+ """Test sending link message."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_link_message(+ 'test_userid', 'Test Link', 'Click to visit', 'https://example.com'+ )+ assert 'Link message' in result and 'sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_action_card_message(mock_request):+ """Test sending action card message."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_action_card_message(+ 'test_userid',+ 'Action Required',+ 'Please click the button below',+ 'Click Here',+ 'https://example.com/action',+ )+ assert 'Action card' in result and 'sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_user_by_mobile(mock_request):+ """Test getting user by mobile number."""+ expected_data = {+ 'userid': 'test_userid',+ 'name': 'Test User',+ 'mobile': '13800000000',+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.dingtalk_get_user_by_mobile('13800000000')+ assert result == expected_data+++def test_get_user_by_mobile_validation():+ """Test mobile number validation in get_user_by_mobile."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()++ # Test invalid mobile numbers+ invalid_mobiles = [+ '1234567890', # 10 digits+ '123456789012', # 12 digits+ '23800000000', # doesn't start with 1+ '12800000000', # second digit is 2 (invalid)+ 'abc1380000000', # contains letters+ '138-0000-0000', # contains hyphens+ '', # empty string+ ]++ for invalid_mobile in invalid_mobiles:+ result = toolkit.dingtalk_get_user_by_mobile(invalid_mobile)+ assert 'error' in result+ assert 'Invalid mobile number format' in result['error']+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_user_by_unionid(mock_request):+ """Test getting user by unionid."""+ expected_data = {+ 'userid': 'test_userid',+ 'name': 'Test User',+ 'unionid': 'test_unionid',+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_user_by_unionid('test_unionid')+ assert result == expected_data+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_department_detail(mock_request):+ """Test getting department details."""+ expected_data = {+ 'id': 1,+ 'name': 'Test Department',+ 'parent_id': 0,+ 'member_count': 10,+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_department_detail(1)+ assert result == expected_data+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_oa_message(mock_request):+ """Test sending OA message."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_oa_message(+ 'test_userid',+ 'https://example.com',+ 'FFBBBBBB',+ 'Important Notice',+ 'System Update',+ 'The system will be updated tonight.',+ )+ assert 'OA message sent successfully' in result+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_get_group_info(mock_request):+ """Test getting group information."""+ expected_data = {+ 'chatid': 'test_chatid',+ 'name': 'Test Group',+ 'owner': 'owner_userid',+ 'member_count': 5,+ 'errcode': 0,+ }+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.get_group_info('test_chatid')+ assert result == expected_data+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_update_group(mock_request):+ """Test updating group."""+ expected_data = {'errcode': 0}+ mock_request.return_value = expected_data++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.update_group(+ 'test_chatid',+ name='New Group Name',+ add_useridlist=['user1', 'user2'],+ )+ assert result == expected_data+++@patch('camel.toolkits.dingtalk._make_dingtalk_request')+def test_send_work_notification(mock_request):+ """Test sending work notification to multiple users."""+ mock_request.return_value = {'errcode': 0}++ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ result = toolkit.send_work_notification(+ ['user1', 'user2', 'user3'],+ 'Important announcement for all team members.',+ )+ assert 'Work notification sent successfully to 3 users' in result+++def test_send_work_notification_validation():+ """Test work notification input validation."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()++ # Test empty user list+ result = toolkit.send_work_notification([], 'test message')+ assert 'userid_list cannot be empty' in result++ # Test too many users+ large_user_list = [f'user{i}' for i in range(101)]+ result = toolkit.send_work_notification(+ large_user_list, 'test message'+ )+ assert 'Cannot send to more than 100 users' in result+++def test_extended_tools_count():+ """Test that all new tools are included."""+ with patch(+ 'camel.toolkits.dingtalk._get_dingtalk_access_token'+ ) as mock_token:+ mock_token.return_value = "test_access_token"+ toolkit = DingtalkToolkit()+ tools = toolkit.get_tools()++ # Should have original 9 tools + 9 new tools = 18 tools+ assert len(tools) == 18++ # Check some specific new tools are present+ tool_names = [tool.func.__name__ for tool in tools]+ assert 'send_link_message' in tool_names+ assert 'send_action_card_message' in tool_names+ assert 'get_user_by_mobile' in tool_names+ assert 'send_work_notification' in tool_names