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: Discord bot rag (#660)

Will Shang6318c3792474
diff --git a/camel/bots/discord_bot.py b/camel/bots/discord_bot.py
deleted file mode 100644
index 323e6d337..000000000
--- a/camel/bots/discord_bot.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# =========== 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 TYPE_CHECKING, List, Optional
-
-from camel.agents import ChatAgent
-from camel.messages import BaseMessage
-
-if TYPE_CHECKING:
- from discord import Message
-
-
-class DiscordBot:
- r"""Represents a Discord bot that is powered by an agent.
-
- Attributes:
- chat_agent (ChatAgent): Chat agent that will power the bot.
- channel_ids (List[int], optional): The channel IDs that the bot will
- listen to.
- discord_token (str, optional): The bot token.
- """
-
- def __init__(
- self,
- chat_agent: ChatAgent,
- channel_ids: Optional[List[int]] = None,
- discord_token: Optional[str] = None,
- ) -> None:
- self.chat_agent = chat_agent
- self.token = discord_token or os.getenv('DISCORD_TOKEN')
- self.channel_ids = channel_ids
-
- if not self.token:
- raise ValueError(
- "`DISCORD_TOKEN` not found in environment variables. Get it"
- " here: `https://discord.com/developers/applications`."
- )
-
- try:
- import discord
- except ImportError:
- raise ImportError(
- "Please install `discord` first. You can install it by running"
- " `python3 -m pip install -U discord.py`."
- )
- intents = discord.Intents.default()
- intents.message_content = True
- self.client = discord.Client(intents=intents)
-
- # Register event handlers
- self.client.event(self.on_ready)
- self.client.event(self.on_message)
-
- def run(self) -> None:
- r"""Start the Discord bot using its token.
-
- This method starts the Discord bot by running the client with the
- provided token.
- """
- self.client.run(self.token) # type: ignore[arg-type]
-
- async def on_ready(self) -> None:
- r"""This method is called when the bot has successfully connected to
- the Discord server.
-
- It prints a message indicating that the bot has logged in and displays
- the username of the bot.
- """
- print(f'We have logged in as {self.client.user}')
-
- async def on_message(self, message: 'Message') -> None:
- r"""Event handler for when a message is received.
-
- Args:
- message (discord.Message): The message object received.
- """
- if message.author == self.client.user:
- return
-
- if self.channel_ids and message.channel.id not in self.channel_ids:
- return
-
- if not self.client.user or not self.client.user.mentioned_in(message):
- return
-
- self.chat_agent.reset()
-
- user_msg = BaseMessage.make_user_message(
- role_name="User", content=message.content
- )
- assistant_response = self.chat_agent.step(user_msg)
- await message.channel.send(assistant_response.msg.content)
diff --git a/camel/bots/__init__.py b/examples/bots/__init__.py
similarity index 100%
rename from camel/bots/__init__.py
rename to examples/bots/__init__.py
diff --git a/examples/bots/discord_bot.py b/examples/bots/discord_bot.py
new file mode 100644
index 000000000..a528c047f
--- /dev/null
+++ b/examples/bots/discord_bot.py
@@ -0,0 +1,198 @@
+# =========== 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 TYPE_CHECKING, List, Optional, Union
+
+from camel.agents import ChatAgent
+from camel.messages import BaseMessage
+from camel.retrievers import AutoRetriever
+
+if TYPE_CHECKING:
+ from discord import Message
+
+
+class DiscordBot:
+ r"""Represents a Discord bot that is powered by a CAMEL `ChatAgent`.
+
+ Attributes:
+ chat_agent (ChatAgent): Chat agent that will power the bot.
+ channel_ids (List[int], optional): The channel IDs that the bot will
+ listen to.
+ discord_token (str, optional): The bot token.
+ auto_retriever (AutoRetriever): AutoRetriever instance for RAG.
+ vector_storage_local_path (Union[str, List[str]]): The paths to the
+ contents for RAG.
+ top_k (int): Top choice for the RAG response.
+ return_detailed_info (bool): If show detailed info of the RAG response.
+ """
+
+ def __init__(
+ self,
+ chat_agent: ChatAgent,
+ channel_ids: Optional[List[int]] = None,
+ discord_token: Optional[str] = None,
+ auto_retriever: Optional[AutoRetriever] = None,
+ vector_storage_local_path: Union[str, List[str]] = "",
+ top_k: int = 1,
+ return_detailed_info: bool = True,
+ ) -> None:
+ self.chat_agent = chat_agent
+ self.token = discord_token or os.getenv('DISCORD_TOKEN')
+ self.channel_ids = channel_ids
+ self.auto_retriever = auto_retriever
+ self.vector_storage_local_path = vector_storage_local_path
+ self.top_k = top_k
+ self.return_detailed_info = return_detailed_info
+
+ if not self.token:
+ raise ValueError(
+ "`DISCORD_TOKEN` not found in environment variables. Get it"
+ " here: `https://discord.com/developers/applications`."
+ )
+
+ try:
+ import discord
+ except ImportError:
+ raise ImportError(
+ "Please install `discord` first. You can install it by running"
+ " `python3 -m pip install -U discord.py`."
+ )
+ intents = discord.Intents.default()
+ intents.message_content = True
+ self.client = discord.Client(intents=intents)
+
+ # Register event handlers
+ self.client.event(self.on_ready)
+ self.client.event(self.on_message)
+
+ def run(self) -> None:
+ r"""Start the Discord bot using its token.
+
+ This method starts the Discord bot by running the client with the
+ provided token.
+ """
+ self.client.run(self.token) # type: ignore[arg-type]
+
+ async def on_ready(self) -> None:
+ r"""This method is called when the bot has successfully connected to
+ the Discord server.
+
+ It prints a message indicating that the bot has logged in and displays
+ the username of the bot.
+ """
+ print(f'We have logged in as {self.client.user}')
+
+ async def on_message(self, message: 'Message') -> None:
+ r"""Event handler for when a message is received.
+
+ Args:
+ message (discord.Message): The message object received.
+ """
+
+ # If the message author is the bot itself,
+ # do not respond to this message
+ if message.author == self.client.user:
+ return
+
+ # If allowed channel IDs are provided,
+ # only respond to messages in those channels
+ if self.channel_ids and message.channel.id not in self.channel_ids:
+ return
+
+ # Only respond to messages that mention the bot
+ if not self.client.user or not self.client.user.mentioned_in(message):
+ return
+
+ user_raw_msg = message.content
+
+ if self.auto_retriever:
+ retrieved_content = self.auto_retriever.run_vector_retriever(
+ query=user_raw_msg,
+ vector_storage_local_path=self.content_input_paths,
+ top_k=self.top_k,
+ return_detailed_info=self.return_detailed_info,
+ )
+ user_raw_msg = (
+ f"Here is the query to you: {user_raw_msg}\n"
+ f"Based on the retrieved content: {retrieved_content}, \n"
+ f"answer the query from {message.author.name}"
+ )
+
+ user_msg = BaseMessage.make_user_message(
+ role_name="User", content=user_raw_msg
+ )
+ assistant_response = self.chat_agent.step(user_msg)
+ await message.channel.send(assistant_response.msg.content)
+
+
+if __name__ == "__main__":
+ assistant_sys_msg = BaseMessage.make_assistant_message(
+ role_name="Assistant",
+ content='''
+ Objective:
+ You are a customer service bot designed to assist users
+ with inquiries related to our open-source project.
+ Your responses should be informative, concise, and helpful.
+
+ Instructions:
+ Understand User Queries: Carefully read and understand the
+ user's question. Focus on keywords and context to
+ determine the user's intent.
+ Search for Relevant Information: Use the provided dataset
+ and refer to the RAG (file to find answers that
+ closely match the user's query. The RAG file contains
+ detailed interactions and should be your primary
+ resource for crafting responses.
+ Provide Clear and Concise Responses: Your answers should
+ be clear and to the point. Avoid overly technical
+ language unless the user's query indicates
+ familiarity with technical terms.
+ Encourage Engagement: Where applicable, encourage users
+ to contribute to the project or seek further
+ assistance.
+
+ Response Structure:
+ Greeting: Begin with a polite greeting or acknowledgment.
+ Main Response: Provide the main answer to the user's query.
+ Additional Information: Offer any extra tips or direct the
+ user to additional resources if necessary.
+ Closing: Close the response politely, encouraging
+ further engagement if appropriate.
+ bd
+ Tone:
+ Professional: Maintain a professional tone that
+ instills confidence in the user.
+ Friendly: Be approachable and friendly to make users
+ feel comfortable.
+ Helpful: Always aim to be as helpful as possible,
+ guiding users to solutions.
+ ''',
+ )
+
+ agent = ChatAgent(
+ assistant_sys_msg,
+ message_window_size=10,
+ )
+ # Uncommented the folowing code and offer storage information
+ # for RAG functionality
+ # auto_retriever = AutoRetriever(
+ # url_and_api_key=("Your QDRANT URI", "Your QDRANT Token"),
+ # storage_type=StorageType.QDRANT,
+ # )
+ bot = DiscordBot(
+ agent,
+ # auto_retriever=auto_retriever,
+ # vector_storage_local_path=["local_data/"],
+ )
+ bot.run()
diff --git a/examples/bots/discord_bot_example.py b/examples/bots/discord_bot_example.py
deleted file mode 100644
index 52d2b1e3d..000000000
--- a/examples/bots/discord_bot_example.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# =========== 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.bots.discord_bot import DiscordBot
-from camel.messages import BaseMessage
-
-
-def main(model=None) -> None:
- assistant_sys_msg = BaseMessage.make_assistant_message(
- role_name="Assistant",
- content="You are a helpful assistant.",
- )
-
- agent = ChatAgent(assistant_sys_msg, model_type=model)
- bot = DiscordBot(agent)
- bot.run()
-
-
-if __name__ == "__main__":
- main()
diff --git a/camel/bots/telegram_bot.py b/examples/bots/telegram_bot.py
similarity index 100%
rename from camel/bots/telegram_bot.py
rename to examples/bots/telegram_bot.py
diff --git a/examples/bots/telegram_bot_example.py b/examples/bots/telegram_bot_example.py
deleted file mode 100644
index da7d45940..000000000
--- a/examples/bots/telegram_bot_example.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# =========== 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.bots.telegram_bot import TelegramBot
-from camel.messages import BaseMessage
-
-
-def main(model=None) -> None:
- assistant_sys_msg = BaseMessage.make_assistant_message(
- role_name="Assistant",
- content="You are a helpful assistant.",
- )
-
- agent = ChatAgent(assistant_sys_msg, model_type=model)
- bot = TelegramBot(agent)
- bot.run()
-
-
-if __name__ == "__main__":
- main()
diff --git a/test/bots/test_discord_bot.py b/examples/test/bots/test_discord_bot.py
similarity index 99%
rename from test/bots/test_discord_bot.py
rename to examples/test/bots/test_discord_bot.py
index e20172e90..96737d0a1 100644
--- a/test/bots/test_discord_bot.py
+++ b/examples/test/bots/test_discord_bot.py
@@ -17,7 +17,7 @@ import unittest
from unittest.mock import AsyncMock, MagicMock, patch
from camel.agents import ChatAgent
-from camel.bots.discord_bot import DiscordBot
+from examples.bots.discord_bot import DiscordBot
class TestDiscordBot(unittest.TestCase):
diff --git a/test/bots/test_telegram_bot.py b/examples/test/bots/test_telegram_bot.py
similarity index 98%
rename from test/bots/test_telegram_bot.py
rename to examples/test/bots/test_telegram_bot.py
index 8a3901b9c..c9b9f9074 100644
--- a/test/bots/test_telegram_bot.py
+++ b/examples/test/bots/test_telegram_bot.py
@@ -15,8 +15,8 @@ import unittest
from unittest.mock import MagicMock, patch
from camel.agents import ChatAgent
-from camel.bots.telegram_bot import TelegramBot
from camel.messages import BaseMessage
+from examples.bots.telegram_bot import TelegramBot
class TestTelegramBot(unittest.TestCase):