🐫 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
enhance: Integrate Wechat PR3087 (#3106)
Wendong-Fanca4b5a51c5a5
diff --git a/camel/toolkits/wechat_official_toolkit.py b/camel/toolkits/wechat_official_toolkit.pyindex 9563ba6e3..8647f01c4 100644--- a/camel/toolkits/wechat_official_toolkit.py+++ b/camel/toolkits/wechat_official_toolkit.py@@ -14,7 +14,7 @@import osimport time-from typing import Any, Dict, List, Optional, Literal+from typing import Any, Dict, List, Literal, Optionalimport requests@@ -36,15 +36,15 @@ def _get_wechat_access_token() -> str:Returns:str: The valid access token.-+Raises:ValueError: If credentials are missing or token retrieval fails.-+References:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html"""global _wechat_access_token, _wechat_access_token_expires_at-+if _wechat_access_token and _wechat_access_token_expires_at > time.time():return _wechat_access_token@@ -61,7 +61,9 @@ def _get_wechat_access_token() -> str:if "access_token" in data:_wechat_access_token = data["access_token"]- _wechat_access_token_expires_at = time.time() + data.get("expires_in", 7200) - 60+ _wechat_access_token_expires_at = (+ time.time() + data.get("expires_in", 7200) - 60+ )logger.info("WeChat access token refreshed.")return _wechat_access_tokenelse:@@ -69,46 +71,50 @@ def _get_wechat_access_token() -> str:errmsg = data.get("errmsg", "Unknown error")raise ValueError(f"Failed to get access token {errcode}: {errmsg}")-def _make_wechat_request(method: Literal["GET", "POST"], endpoint: str, **kwargs) -> Dict[str, Any]:++def _make_wechat_request(+ method: Literal["GET", "POST"], endpoint: str, **kwargs+) -> Dict[str, Any]:r"""Makes a request to WeChat API with proper error handling.-+Args:method (Literal["GET", "POST"]): HTTP method ('GET' or 'POST').endpoint (str): API endpoint path.**kwargs: Additional arguments for requests.-+Returns:Dict[str, Any]: API response data.-+Raises:requests.exceptions.RequestException: If request fails.ValueError: If API returns an error."""global _wechat_access_token, _wechat_access_token_expires_ataccess_token = _get_wechat_access_token()-+# Handle URL parameter concatenationseparator = "&" if "?" in endpoint else "?"url = (f"https://api.weixin.qq.com{endpoint}{separator}"f"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"WeChat API error {errcode}: {errmsg}")-+return data+@MCPServer()class WeChatOfficialToolkit(BaseToolkit):r"""A toolkit for WeChat Official Account operations.@@ -128,21 +134,25 @@ class WeChatOfficialToolkit(BaseToolkit):r"""Initializes the WeChatOfficialToolkit."""super().__init__(timeout=timeout)self.base_url = "https://api.weixin.qq.com"-+# Validate credentialsapp_id = os.environ.get("WECHAT_APP_ID", "")app_secret = os.environ.get("WECHAT_APP_SECRET", "")-+if not all([app_id, app_secret]):raise ValueError(- "WeChat credentials missing. Set WECHAT_APP_ID and WECHAT_APP_SECRET."+ "WeChat credentials missing. Set WECHAT_APP_ID and"+ " WECHAT_APP_SECRET.")-+# Define full logic as class methods; top-level functions delegate here- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])++ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def send_customer_message(self,openid: str,@@ -190,10 +200,12 @@ class WeChatOfficialToolkit(BaseToolkit):)return f"Message sent successfully to {openid}."- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])+ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def get_user_info(self,openid: str,@@ -203,23 +215,28 @@ class WeChatOfficialToolkit(BaseToolkit):Args:openid (str): The user's OpenID.- lang (str): Response language. Common values: "zh_CN", "zh_TW", "en". (default: "zh_CN")+ lang (str): Response language. Common values: "zh_CN", "zh_TW",+ "en". (default: "zh_CN")Returns:- Dict[str, Any]: User information as dictionary or error information.+ Dict[str, Any]: User information as dictionary or error+ information.References:- https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_user_basic_information.html+ https://developers.weixin.qq.com/doc/offiaccount/User_Management/+ Getting_user_basic_information.html"""data = _make_wechat_request("GET", f"/cgi-bin/user/info?openid={openid}&lang={lang}")return data- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])+ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def get_followers_list(self,next_openid: str = "",@@ -233,7 +250,8 @@ class WeChatOfficialToolkit(BaseToolkit):Dict[str, Any]: Followers list as dictionary or error information.References:- https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_list_of_followers.html+ https://developers.weixin.qq.com/doc/offiaccount/User_Management/+ Getting_a_list_of_followers.html"""endpoint = "/cgi-bin/user/get"if next_openid:@@ -241,10 +259,12 @@ class WeChatOfficialToolkit(BaseToolkit):data = _make_wechat_request("GET", endpoint)return data- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])+ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def upload_wechat_media(self,media_type: Literal[@@ -262,15 +282,19 @@ class WeChatOfficialToolkit(BaseToolkit):Args:media_type (str): Media type: "image", "voice", "video", "thumb".file_path (str): Local file path.- permanent (bool): Whether to upload as permanent media. (default: False)- description (Optional[str]): Video description in JSON format for permanent upload.+ permanent (bool): Whether to upload as permanent media.+ (default: :obj:`False`)+ description (Optional[str]): Video description in JSON format+ for permanent upload. (default: :obj:`None`)Returns:Dict[str, Any]: Upload result with media_id or error information.References:- - Temporary: https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Temporary_Assets.html- - Permanent: https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Permanent_Assets.html+ - Temporary: https://developers.weixin.qq.com/doc/offiaccount/+ Asset_Management/Adding_Temporary_Assets.html+ - Permanent: https://developers.weixin.qq.com/doc/offiaccount/+ Asset_Management/Adding_Permanent_Assets.html"""if permanent:endpoint = f"/cgi-bin/material/add_material?type={media_type}"@@ -278,7 +302,7 @@ class WeChatOfficialToolkit(BaseToolkit):if media_type == "video" and description:data_payload["description"] = descriptionwith open(file_path, "rb") as media_file:- files = {"media": media_file}+ files: Dict[str, Any] = {"media": media_file}if media_type == "video" and description:files["description"] = (None, description)data = _make_wechat_request(@@ -292,10 +316,12 @@ class WeChatOfficialToolkit(BaseToolkit):return data- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])+ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def get_media_list(self,media_type: Literal[@@ -311,14 +337,15 @@ class WeChatOfficialToolkit(BaseToolkit):Args:media_type (str): Media type: "image", "voice", "video", "news".- offset (int): Starting position. (default: 0)- count (int): Number of items (1-20). (default: 20)+ offset (int): Starting position. (default: :obj:`0`)+ count (int): Number of items (1-20). (default: :obj:`20`)Returns:Dict[str, Any]: Media list as dictionary or error information.References:- https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_the_list_of_all_materials.html+ https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/+ Get_the_list_of_all_materials.html"""payload = {"type": media_type, "offset": offset, "count": count}data = _make_wechat_request(@@ -329,10 +356,12 @@ class WeChatOfficialToolkit(BaseToolkit):)return data- @api_keys_required([- (None, "WECHAT_APP_ID"),- (None, "WECHAT_APP_SECRET"),- ])+ @api_keys_required(+ [+ (None, "WECHAT_APP_ID"),+ (None, "WECHAT_APP_SECRET"),+ ]+ )def send_mass_message_to_all(self,content: str,@@ -371,7 +400,8 @@ class WeChatOfficialToolkit(BaseToolkit):References:- Mass send by OpenID list:- https://developers.weixin.qq.com/doc/service/api/notify/message/api_masssend.html+ https://developers.weixin.qq.com/doc/service/api/notify/message/+ api_masssend.html"""# 1) Collect all follower OpenIDsall_openids: List[str] = []@@ -382,10 +412,16 @@ class WeChatOfficialToolkit(BaseToolkit):endpoint += f"?next_openid={next_openid}"page = _make_wechat_request("GET", endpoint)data_block = page.get("data", {}) if isinstance(page, dict) else {}- openids = data_block.get("openid", []) if isinstance(data_block, dict) else []+ openids = (+ data_block.get("openid", [])+ if isinstance(data_block, dict)+ else []+ )if openids:all_openids.extend(openids)- next_openid = page.get("next_openid", "") if isinstance(page, dict) else ""+ next_openid = (+ page.get("next_openid", "") if isinstance(page, dict) else ""+ )if not next_openid:break@@ -434,6 +470,7 @@ class WeChatOfficialToolkit(BaseToolkit):"batches": (len(all_openids) + batch_size - 1) // batch_size,"results": results,}+def get_tools(self) -> List[FunctionTool]:r"""Returns toolkit functions as tools."""return [@@ -443,4 +480,4 @@ class WeChatOfficialToolkit(BaseToolkit):FunctionTool(self.upload_wechat_media),FunctionTool(self.get_media_list),FunctionTool(self.send_mass_message_to_all),- ]\ No newline at end of file+ ]diff --git a/examples/toolkits/wechat_official_toolkit.py b/examples/toolkits/wechat_official_toolkit.pyindex d56bc3332..852eb8155 100644--- a/examples/toolkits/wechat_official_toolkit.py+++ b/examples/toolkits/wechat_official_toolkit.py@@ -16,10 +16,11 @@ from camel.models import ModelFactoryfrom camel.toolkits import WeChatOfficialToolkitfrom camel.types import ModelPlatformType, ModelType+def main():# Initialize WeChat toolkitwechat_toolkit = WeChatOfficialToolkit()-+# Create modelmodel = ModelFactory.create(model_platform=ModelPlatformType.DEFAULT,@@ -28,45 +29,50 @@ def main():# Create agent with WeChat toolkitagent = ChatAgent(- system_message="You are a WeChat Official Account assistant. Help manage WeChat operations.",+ system_message="You are a WeChat Official Account assistant. "+ "Help manage WeChat operations.",model=model,tools=wechat_toolkit.get_tools(),)-+# Example 1: Get followers and send a text messageresponse = agent.step(- "Get the list of followers, then send a welcome message to the fifth follower."+ "Get the list of followers, then send a welcome message to the "+ "fifth follower.")print("Text Message Response:", response.msg.content)print("Tool calls:")for i, tool_call in enumerate(response.info['tool_calls'], 1):print(f" {i}. {tool_call.tool_name}({tool_call.args})")print()-+# Example 2: Upload and send an imageimage_path = "/home/lyz/Camel/CAMEL_logo.jpg" # Update this path as neededresponse = agent.step(- f"Upload the image at '{image_path}' as temporary media, then send this image to the fifth follower."+ f"Upload the image at '{image_path}' as temporary media, then send "+ "this image to the fifth follower.")print("Image Upload and Send Response:", response.msg.content)print("Tool calls:")for i, tool_call in enumerate(response.info['tool_calls'], 1):print(f" {i}. {tool_call.tool_name}({tool_call.args})")print()-+# Example 3: Get detailed user informationresponse = agent.step(- "Get detailed information about the fifth follower, including their language preference and subscription details."+ "Get detailed information about the fifth follower, including their "+ "language preference and subscription details.")print("User Info Response:", response.msg.content)print("Tool calls:")for i, tool_call in enumerate(response.info['tool_calls'], 1):print(f" {i}. {tool_call.tool_name}({tool_call.args})")print()-+# Example 4: Upload permanent media and get media listresponse = agent.step(- f"Upload the image at '{image_path}' as permanent media, then get the list of all image media files."+ f"Upload the image at '{image_path}' as permanent media, then get "+ "the list of all image media files.")print("Permanent Media Upload Response:", response.msg.content)print("Tool calls:")@@ -84,12 +90,17 @@ Text Message Response:I've successfully completed both tasks:1. **Retrieved the followers list**: Found 6 total followers with their OpenIDs-2. **Sent welcome message to the fifth follower**: The welcome message was successfully sent to the follower with OpenID `oKSAF2******rEJI`+2. **Sent welcome message to the fifth follower**: The welcome message was+successfully sent to the follower with OpenID `oKSAF2******rEJI`-The welcome message "Welcome! Thank you for following our WeChat Official Account. We're excited to have you as part of our community!" has been delivered successfully.+The welcome message "Welcome! Thank you for following our WeChat Official+Account. We're excited to have you as part of our community!" has been+delivered successfully.Tool calls:1. get_followers_list({'next_openid': ''})- 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome! Thank you for following our WeChat Official Account. We're excited to have you as part of our community!", 'msgtype': 'text'})+ 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome!+ Thank you for following our WeChat Official Account. We're excited to have+ you as part of our community!", 'msgtype': 'text'})==============================@@ -97,33 +108,45 @@ Image Upload and Send Response:Perfect! I've successfully completed both tasks:-1. **Uploaded the image**: The image at '/home/lyz/Camel/CAMEL_logo.jpg' has been uploaded as temporary media with media_id: `A_6Hlu******C6IUr`+1. **Uploaded the image**: The image at '/home/lyz/Camel/CAMEL_logo.jpg' has+been uploaded as temporary media with media_id: `A_6Hlu******C6IUr`-2. **Sent the image to the fifth follower**: The image has been successfully sent to the fifth follower (OpenID: oKSAF2******rEJI)+2. **Sent the image to the fifth follower**: The image has been successfully+sent to the fifth follower (OpenID: oKSAF2******rEJI)Both operations completed successfully!Tool calls:- 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': False, 'description': ''})- 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': 'A_6Hlu******C6IUr', 'msgtype': 'image'})+ 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/+ CAMEL_logo.jpg', 'permanent': False, 'description': ''})+ 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content':+ 'A_6Hlu******C6IUr', 'msgtype': 'image'})==============================(.camel) [lyz@dev10 toolkits]$ python wechat_official_toolkit.py-2025-09-01 02:41:48,494 - root - WARNING - Invalid or missing `max_tokens` in `model_config_dict`. Defaulting to 999_999_999 tokens.+2025-09-01 02:41:48,494 - root - WARNING - Invalid or missing `max_tokens` in+`model_config_dict`. Defaulting to 999_999_999 tokens.Text Message Response:I've successfully completed your request! Here's what I did:-1. **Retrieved the follower list**: I got the list of all followers, which shows there are 6 total followers.+1. **Retrieved the follower list**: I got the list of all followers, which+shows there are 6 total followers.-2. **Identified the fifth follower**: From the list, the fifth follower has the OpenID: `oKSAF2******rEJI`+2. **Identified the fifth follower**: From the list, the fifth follower has+the OpenID: `oKSAF2******rEJI`-3. **Sent a welcome message**: I successfully sent a welcome message to the fifth follower with the content: "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!"+3. **Sent a welcome message**: I successfully sent a welcome message to the+fifth follower with the content: "Welcome! Thank you for following our WeChat+Official Account. We're excited to have you join our community!"-The message was delivered successfully to the fifth follower in your follower list.+The message was delivered successfully to the fifth follower in your follower+list.Tool calls:1. get_followers_list({'next_openid': ''})- 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome! Thank you for following our WeChat Official Account. We're excited to have you join our community!", 'msgtype': 'text'})+ 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': "Welcome!+ Thank you for following our WeChat Official Account. We're excited to have+ you join our community!", 'msgtype': 'text'})==============================@@ -131,24 +154,31 @@ Image Upload and Send Response:Perfect! I've successfully completed both tasks:-1. **Retrieved followers list**: Found 6 followers total, with the fifth follower having OpenID: `oKSAF2******rEJI`+1. **Retrieved followers list**: Found 6 followers total, with the fifth+follower having OpenID: `oKSAF2******rEJI`-2. **Sent welcome message**: Successfully sent a welcome text message to the fifth follower.+2. **Sent welcome message**: Successfully sent a welcome text message to the+fifth follower.-3. **Uploaded image**: Successfully uploaded the CAMEL logo image as temporary media with media_id: `A_6Hlu******MW_ubO`+3. **Uploaded image**: Successfully uploaded the CAMEL logo image as temporary+media with media_id: `A_6Hlu******MW_ubO`4. **Sent image**: Successfully sent the uploaded image to the fifth follower.-Both the welcome message and the CAMEL logo image have been delivered to the fifth follower!+Both the welcome message and the CAMEL logo image have been delivered to the+fifth follower!Tool calls:- 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': False, 'description': None})- 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content': 'A_6Hlu******MW_ubO', 'msgtype': 'image'})+ 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/+ CAMEL_logo.jpg', 'permanent': False, 'description': None})+ 2. send_customer_message({'openid': 'oKSAF2******rEJI', 'content':+ 'A_6Hlu******MW_ubO', 'msgtype': 'image'})==============================User Info Response:-I've retrieved the detailed information about the fifth follower. Here are the key details:+I've retrieved the detailed information about the fifth follower. Here are the+key details:**Language Preference:**- Language: zh_CN (Chinese, mainland China)@@ -168,7 +198,8 @@ I've retrieved the detailed information about the fifth follower. Here are the k- Tags: No tags assigned- Custom Remark: None-The follower is actively subscribed and prefers Chinese (mainland China) language. They joined the account by scanning a QR code.+The follower is actively subscribed and prefers Chinese (mainland China)+language. They joined the account by scanning a QR code.Tool calls:1. get_user_info({'openid': 'oKSAF2******rEJI', 'lang': 'en'})@@ -179,12 +210,14 @@ Permanent Media Upload Response:Perfect! I've successfully completed both tasks:## 1. Image Upload (Permanent Media)-The image `/home/lyz/Camel/CAMEL_logo.jpg` has been uploaded as permanent media with the following details:+The image `/home/lyz/Camel/CAMEL_logo.jpg` has been uploaded as permanent+media with the following details:- **Media ID**: `Rd1Ljw******mBUw_`- **URL**: `https://mmbiz.qpic.cn/.../0?wx_fmt=jpeg`## 2. Image Media List-I retrieved the list of all permanent image media files. Here's what's currently in your media library:+I retrieved the list of all permanent image media files. Here's what's+currently in your media library:**Total Count**: 5 image files@@ -210,9 +243,11 @@ I retrieved the list of all permanent image media files. Here's what's currently- Media ID: `Rd1Ljw******QKlyt`- Update Time: 1756539999-All files appear to be the same CAMEL logo image uploaded at different times. The most recent upload is now available for use in your WeChat communications.+All files appear to be the same CAMEL logo image uploaded at different times.+The most recent upload is now available for use in your WeChat communications.Tool calls:- 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/CAMEL_logo.jpg', 'permanent': True, 'description': ''})+ 1. upload_wechat_media({'media_type': 'image', 'file_path': '/home/lyz/Camel/+ CAMEL_logo.jpg', 'permanent': True, 'description': ''})2. get_media_list({'media_type': 'image', 'offset': 0, 'count': 20})-"""\ No newline at end of file+"""diff --git a/test/toolkits/test_wechat_official_toolkit.py b/test/toolkits/test_wechat_official_toolkit.pyindex 0b34db0a2..0b192cbb0 100644--- a/test/toolkits/test_wechat_official_toolkit.py+++ b/test/toolkits/test_wechat_official_toolkit.py@@ -21,6 +21,7 @@ from camel.toolkits.wechat_official_toolkit import (_get_wechat_access_token,)+@pytest.fixture(autouse=True)def set_env_vars(monkeypatch):"""Set up environment variables for testing."""@@ -47,7 +48,7 @@ def test_get_access_token(mock_get):mock_response = MagicMock()mock_response.json.return_value = {'access_token': 'test_token',- 'expires_in': 7200+ 'expires_in': 7200,}mock_get.return_value = mock_response@@ -59,7 +60,7 @@ def test_get_access_token(mock_get):def test_send_message(mock_request):"""Test sending customer message."""mock_request.return_value = {'errcode': 0}-+toolkit = WeChatOfficialToolkit()result = toolkit.send_customer_message('test_openid', 'Hello', 'text')assert 'Message sent successfully' in result@@ -70,7 +71,7 @@ def test_get_user_info(mock_request):"""Test getting user information."""expected_data = {'openid': 'test_openid', 'nickname': 'Test User'}mock_request.return_value = expected_data-+toolkit = WeChatOfficialToolkit()result = toolkit.get_user_info('test_openid')assert result == expected_data@@ -79,6 +80,6 @@ def test_get_user_info(mock_request):def test_missing_credentials(monkeypatch):"""Test initialization with missing credentials."""monkeypatch.delenv("WECHAT_APP_ID", raising=False)-+with pytest.raises(ValueError, match="WeChat credentials missing"):WeChatOfficialToolkit()