camel-ai 0.1.5.5__py3-none-any.whl → 0.1.5.9__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of camel-ai might be problematic. Click here for more details.
- camel/__init__.py +1 -1
- camel/agents/chat_agent.py +3 -3
- camel/agents/critic_agent.py +1 -1
- camel/agents/deductive_reasoner_agent.py +4 -4
- camel/agents/embodied_agent.py +1 -1
- camel/agents/knowledge_graph_agent.py +13 -17
- camel/agents/role_assignment_agent.py +1 -1
- camel/agents/search_agent.py +4 -5
- camel/agents/task_agent.py +5 -6
- camel/configs/__init__.py +15 -0
- camel/configs/gemini_config.py +98 -0
- camel/configs/groq_config.py +119 -0
- camel/configs/litellm_config.py +1 -1
- camel/configs/mistral_config.py +81 -0
- camel/configs/ollama_config.py +1 -1
- camel/configs/openai_config.py +1 -1
- camel/configs/vllm_config.py +103 -0
- camel/configs/zhipuai_config.py +1 -1
- camel/embeddings/__init__.py +2 -0
- camel/embeddings/mistral_embedding.py +89 -0
- camel/interpreters/__init__.py +2 -0
- camel/interpreters/ipython_interpreter.py +167 -0
- camel/models/__init__.py +10 -0
- camel/models/anthropic_model.py +7 -2
- camel/models/azure_openai_model.py +152 -0
- camel/models/base_model.py +9 -2
- camel/models/gemini_model.py +215 -0
- camel/models/groq_model.py +131 -0
- camel/models/litellm_model.py +26 -4
- camel/models/mistral_model.py +169 -0
- camel/models/model_factory.py +33 -5
- camel/models/ollama_model.py +21 -2
- camel/models/open_source_model.py +11 -3
- camel/models/openai_model.py +7 -2
- camel/models/stub_model.py +4 -4
- camel/models/vllm_model.py +138 -0
- camel/models/zhipuai_model.py +7 -4
- camel/prompts/__init__.py +2 -2
- camel/prompts/task_prompt_template.py +4 -4
- camel/prompts/{descripte_video_prompt.py → video_description_prompt.py} +1 -1
- camel/retrievers/auto_retriever.py +2 -0
- camel/storages/graph_storages/neo4j_graph.py +5 -0
- camel/toolkits/__init__.py +36 -0
- camel/toolkits/base.py +1 -1
- camel/toolkits/code_execution.py +1 -1
- camel/toolkits/github_toolkit.py +3 -2
- camel/toolkits/google_maps_toolkit.py +367 -0
- camel/toolkits/math_toolkit.py +79 -0
- camel/toolkits/open_api_toolkit.py +548 -0
- camel/toolkits/retrieval_toolkit.py +76 -0
- camel/toolkits/search_toolkit.py +326 -0
- camel/toolkits/slack_toolkit.py +308 -0
- camel/toolkits/twitter_toolkit.py +522 -0
- camel/toolkits/weather_toolkit.py +173 -0
- camel/types/enums.py +163 -30
- camel/utils/__init__.py +4 -0
- camel/utils/async_func.py +1 -1
- camel/utils/token_counting.py +182 -40
- {camel_ai-0.1.5.5.dist-info → camel_ai-0.1.5.9.dist-info}/METADATA +43 -3
- camel_ai-0.1.5.9.dist-info/RECORD +165 -0
- camel/functions/__init__.py +0 -51
- camel/functions/google_maps_function.py +0 -335
- camel/functions/math_functions.py +0 -61
- camel/functions/open_api_function.py +0 -508
- camel/functions/retrieval_functions.py +0 -61
- camel/functions/search_functions.py +0 -298
- camel/functions/slack_functions.py +0 -286
- camel/functions/twitter_function.py +0 -479
- camel/functions/weather_functions.py +0 -144
- camel_ai-0.1.5.5.dist-info/RECORD +0 -155
- /camel/{functions → toolkits}/open_api_specs/biztoc/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/biztoc/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/biztoc/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/coursera/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/coursera/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/create_qr_code/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/create_qr_code/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/klarna/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/klarna/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/nasa_apod/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/nasa_apod/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/get_classes.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/outschool/paths/search_teachers.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/security_config.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/speak/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/speak/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/ai-plugin.json +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/openapi.yaml +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/paths/__init__.py +0 -0
- /camel/{functions → toolkits}/open_api_specs/web_scraper/paths/scraper.py +0 -0
- /camel/{functions → toolkits}/openai_function.py +0 -0
- {camel_ai-0.1.5.5.dist-info → camel_ai-0.1.5.9.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
import os
|
|
15
|
+
from typing import Any, Dict, List
|
|
16
|
+
|
|
17
|
+
from camel.toolkits.base import BaseToolkit
|
|
18
|
+
from camel.toolkits.openai_function import OpenAIFunction
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SearchToolkit(BaseToolkit):
|
|
22
|
+
r"""A class representing a toolkit for web search.
|
|
23
|
+
|
|
24
|
+
This class provides methods for searching information on the web using
|
|
25
|
+
search engines like Google, DuckDuckGo, Wikipedia and Wolfram Alpha.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def search_wiki(self, entity: str) -> str:
|
|
29
|
+
r"""Search the entity in WikiPedia and return the summary of the
|
|
30
|
+
required page, containing factual information about
|
|
31
|
+
the given entity.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
entity (str): The entity to be searched.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
str: The search result. If the page corresponding to the entity
|
|
38
|
+
exists, return the summary of this entity in a string.
|
|
39
|
+
"""
|
|
40
|
+
try:
|
|
41
|
+
import wikipedia
|
|
42
|
+
except ImportError:
|
|
43
|
+
raise ImportError(
|
|
44
|
+
"Please install `wikipedia` first. You can install it "
|
|
45
|
+
"by running `pip install wikipedia`."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
result: str
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
result = wikipedia.summary(entity, sentences=5, auto_suggest=False)
|
|
52
|
+
except wikipedia.exceptions.DisambiguationError as e:
|
|
53
|
+
result = wikipedia.summary(
|
|
54
|
+
e.options[0], sentences=5, auto_suggest=False
|
|
55
|
+
)
|
|
56
|
+
except wikipedia.exceptions.PageError:
|
|
57
|
+
result = (
|
|
58
|
+
"There is no page in Wikipedia corresponding to entity "
|
|
59
|
+
f"{entity}, please specify another word to describe the"
|
|
60
|
+
" entity to be searched."
|
|
61
|
+
)
|
|
62
|
+
except wikipedia.exceptions.WikipediaException as e:
|
|
63
|
+
result = f"An exception occurred during the search: {e}"
|
|
64
|
+
|
|
65
|
+
return result
|
|
66
|
+
|
|
67
|
+
def search_duckduckgo(
|
|
68
|
+
self, query: str, source: str = "text", max_results: int = 10
|
|
69
|
+
) -> List[Dict[str, Any]]:
|
|
70
|
+
r"""Use DuckDuckGo search engine to search information for
|
|
71
|
+
the given query.
|
|
72
|
+
|
|
73
|
+
This function queries the DuckDuckGo API for related topics to
|
|
74
|
+
the given search term. The results are formatted into a list of
|
|
75
|
+
dictionaries, each representing a search result.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
query (str): The query to be searched.
|
|
79
|
+
source (str): The type of information to query (e.g., "text",
|
|
80
|
+
"images", "videos"). Defaults to "text".
|
|
81
|
+
max_results (int): Max number of results, defaults to `10`.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
List[Dict[str, Any]]: A list of dictionaries where each dictionary
|
|
85
|
+
represents a search result.
|
|
86
|
+
"""
|
|
87
|
+
from duckduckgo_search import DDGS
|
|
88
|
+
from requests.exceptions import RequestException
|
|
89
|
+
|
|
90
|
+
ddgs = DDGS()
|
|
91
|
+
responses: List[Dict[str, Any]] = []
|
|
92
|
+
|
|
93
|
+
if source == "text":
|
|
94
|
+
try:
|
|
95
|
+
results = ddgs.text(keywords=query, max_results=max_results)
|
|
96
|
+
except RequestException as e:
|
|
97
|
+
# Handle specific exceptions or general request exceptions
|
|
98
|
+
responses.append({"error": f"duckduckgo search failed.{e}"})
|
|
99
|
+
|
|
100
|
+
# Iterate over results found
|
|
101
|
+
for i, result in enumerate(results, start=1):
|
|
102
|
+
# Creating a response object with a similar structure
|
|
103
|
+
response = {
|
|
104
|
+
"result_id": i,
|
|
105
|
+
"title": result["title"],
|
|
106
|
+
"description": result["body"],
|
|
107
|
+
"url": result["href"],
|
|
108
|
+
}
|
|
109
|
+
responses.append(response)
|
|
110
|
+
|
|
111
|
+
elif source == "images":
|
|
112
|
+
try:
|
|
113
|
+
results = ddgs.images(keywords=query, max_results=max_results)
|
|
114
|
+
except RequestException as e:
|
|
115
|
+
# Handle specific exceptions or general request exceptions
|
|
116
|
+
responses.append({"error": f"duckduckgo search failed.{e}"})
|
|
117
|
+
|
|
118
|
+
# Iterate over results found
|
|
119
|
+
for i, result in enumerate(results, start=1):
|
|
120
|
+
# Creating a response object with a similar structure
|
|
121
|
+
response = {
|
|
122
|
+
"result_id": i,
|
|
123
|
+
"title": result["title"],
|
|
124
|
+
"image": result["image"],
|
|
125
|
+
"url": result["url"],
|
|
126
|
+
"source": result["source"],
|
|
127
|
+
}
|
|
128
|
+
responses.append(response)
|
|
129
|
+
|
|
130
|
+
elif source == "videos":
|
|
131
|
+
try:
|
|
132
|
+
results = ddgs.videos(keywords=query, max_results=max_results)
|
|
133
|
+
except RequestException as e:
|
|
134
|
+
# Handle specific exceptions or general request exceptions
|
|
135
|
+
responses.append({"error": f"duckduckgo search failed.{e}"})
|
|
136
|
+
|
|
137
|
+
# Iterate over results found
|
|
138
|
+
for i, result in enumerate(results, start=1):
|
|
139
|
+
# Creating a response object with a similar structure
|
|
140
|
+
response = {
|
|
141
|
+
"result_id": i,
|
|
142
|
+
"title": result["title"],
|
|
143
|
+
"description": result["description"],
|
|
144
|
+
"embed_url": result["embed_url"],
|
|
145
|
+
"publisher": result["publisher"],
|
|
146
|
+
"duration": result["duration"],
|
|
147
|
+
"published": result["published"],
|
|
148
|
+
}
|
|
149
|
+
responses.append(response)
|
|
150
|
+
|
|
151
|
+
# If no answer found, return an empty list
|
|
152
|
+
return responses
|
|
153
|
+
|
|
154
|
+
def search_google(
|
|
155
|
+
self, query: str, num_result_pages: int = 10
|
|
156
|
+
) -> List[Dict[str, Any]]:
|
|
157
|
+
r"""Use Google search engine to search information for the given query.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
query (str): The query to be searched.
|
|
161
|
+
num_result_pages (int): The number of result pages to retrieve.
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
List[Dict[str, Any]]: A list of dictionaries where each dictionary
|
|
165
|
+
represents a website.
|
|
166
|
+
Each dictionary contains the following keys:
|
|
167
|
+
- 'result_id': A number in order.
|
|
168
|
+
- 'title': The title of the website.
|
|
169
|
+
- 'description': A brief description of the website.
|
|
170
|
+
- 'long_description': More detail of the website.
|
|
171
|
+
- 'url': The URL of the website.
|
|
172
|
+
|
|
173
|
+
Example:
|
|
174
|
+
{
|
|
175
|
+
'result_id': 1,
|
|
176
|
+
'title': 'OpenAI',
|
|
177
|
+
'description': 'An organization focused on ensuring that
|
|
178
|
+
artificial general intelligence benefits all of humanity.',
|
|
179
|
+
'long_description': 'OpenAI is a non-profit artificial
|
|
180
|
+
intelligence research company. Our goal is to advance
|
|
181
|
+
digital intelligence in the way that is most likely to
|
|
182
|
+
benefit humanity as a whole',
|
|
183
|
+
'url': 'https://www.openai.com'
|
|
184
|
+
}
|
|
185
|
+
title, description, url of a website.
|
|
186
|
+
"""
|
|
187
|
+
import requests
|
|
188
|
+
|
|
189
|
+
# https://developers.google.com/custom-search/v1/overview
|
|
190
|
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
|
191
|
+
# https://cse.google.com/cse/all
|
|
192
|
+
SEARCH_ENGINE_ID = os.getenv("SEARCH_ENGINE_ID")
|
|
193
|
+
|
|
194
|
+
# Using the first page
|
|
195
|
+
start_page_idx = 1
|
|
196
|
+
# Different language may get different result
|
|
197
|
+
search_language = "en"
|
|
198
|
+
# How many pages to return
|
|
199
|
+
num_result_pages = 10
|
|
200
|
+
# Constructing the URL
|
|
201
|
+
# Doc: https://developers.google.com/custom-search/v1/using_rest
|
|
202
|
+
url = (
|
|
203
|
+
f"https://www.googleapis.com/customsearch/v1?"
|
|
204
|
+
f"key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}&start="
|
|
205
|
+
f"{start_page_idx}&lr={search_language}&num={num_result_pages}"
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
responses = []
|
|
209
|
+
# Fetch the results given the URL
|
|
210
|
+
try:
|
|
211
|
+
# Make the get
|
|
212
|
+
result = requests.get(url)
|
|
213
|
+
data = result.json()
|
|
214
|
+
|
|
215
|
+
# Get the result items
|
|
216
|
+
if "items" in data:
|
|
217
|
+
search_items = data.get("items")
|
|
218
|
+
|
|
219
|
+
# Iterate over 10 results found
|
|
220
|
+
for i, search_item in enumerate(search_items, start=1):
|
|
221
|
+
if (
|
|
222
|
+
"og:description"
|
|
223
|
+
in search_item["pagemap"]["metatags"][0]
|
|
224
|
+
):
|
|
225
|
+
long_description = search_item["pagemap"]["metatags"][
|
|
226
|
+
0
|
|
227
|
+
]["og:description"]
|
|
228
|
+
else:
|
|
229
|
+
long_description = "N/A"
|
|
230
|
+
# Get the page title
|
|
231
|
+
title = search_item.get("title")
|
|
232
|
+
# Page snippet
|
|
233
|
+
snippet = search_item.get("snippet")
|
|
234
|
+
|
|
235
|
+
# Extract the page url
|
|
236
|
+
link = search_item.get("link")
|
|
237
|
+
response = {
|
|
238
|
+
"result_id": i,
|
|
239
|
+
"title": title,
|
|
240
|
+
"description": snippet,
|
|
241
|
+
"long_description": long_description,
|
|
242
|
+
"url": link,
|
|
243
|
+
}
|
|
244
|
+
responses.append(response)
|
|
245
|
+
else:
|
|
246
|
+
responses.append({"error": "google search failed."})
|
|
247
|
+
|
|
248
|
+
except requests.RequestException:
|
|
249
|
+
# Handle specific exceptions or general request exceptions
|
|
250
|
+
responses.append({"error": "google search failed."})
|
|
251
|
+
# If no answer found, return an empty list
|
|
252
|
+
return responses
|
|
253
|
+
|
|
254
|
+
def query_wolfram_alpha(self, query: str, is_detailed: bool) -> str:
|
|
255
|
+
r"""Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is an
|
|
256
|
+
answer engine developed by Wolfram Research. It is offered as an online
|
|
257
|
+
service that answers factual queries by computing answers from
|
|
258
|
+
externally sourced data.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
query (str): The query to send to Wolfram Alpha.
|
|
262
|
+
is_detailed (bool): Whether to include additional details in the
|
|
263
|
+
result.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
str: The result from Wolfram Alpha, formatted as a string.
|
|
267
|
+
"""
|
|
268
|
+
try:
|
|
269
|
+
import wolframalpha
|
|
270
|
+
except ImportError:
|
|
271
|
+
raise ImportError(
|
|
272
|
+
"Please install `wolframalpha` first. You can install it by"
|
|
273
|
+
" running `pip install wolframalpha`."
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
WOLFRAMALPHA_APP_ID = os.environ.get('WOLFRAMALPHA_APP_ID')
|
|
277
|
+
if not WOLFRAMALPHA_APP_ID:
|
|
278
|
+
raise ValueError(
|
|
279
|
+
"`WOLFRAMALPHA_APP_ID` not found in environment "
|
|
280
|
+
"variables. Get `WOLFRAMALPHA_APP_ID` here: "
|
|
281
|
+
"`https://products.wolframalpha.com/api/`."
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
try:
|
|
285
|
+
client = wolframalpha.Client(WOLFRAMALPHA_APP_ID)
|
|
286
|
+
res = client.query(query)
|
|
287
|
+
assumption = next(res.pods).text or "No assumption made."
|
|
288
|
+
answer = next(res.results).text or "No answer found."
|
|
289
|
+
except Exception as e:
|
|
290
|
+
if isinstance(e, StopIteration):
|
|
291
|
+
return "Wolfram Alpha wasn't able to answer it"
|
|
292
|
+
else:
|
|
293
|
+
error_message = (
|
|
294
|
+
f"Wolfram Alpha wasn't able to answer it" f"{e!s}."
|
|
295
|
+
)
|
|
296
|
+
return error_message
|
|
297
|
+
|
|
298
|
+
result = f"Assumption:\n{assumption}\n\nAnswer:\n{answer}"
|
|
299
|
+
|
|
300
|
+
# Add additional details in the result
|
|
301
|
+
if is_detailed:
|
|
302
|
+
result += '\n'
|
|
303
|
+
for pod in res.pods:
|
|
304
|
+
result += '\n' + pod['@title'] + ':\n'
|
|
305
|
+
for sub in pod.subpods:
|
|
306
|
+
result += (sub.plaintext or "None") + '\n'
|
|
307
|
+
|
|
308
|
+
return result.rstrip() # Remove trailing whitespace
|
|
309
|
+
|
|
310
|
+
def get_tools(self) -> List[OpenAIFunction]:
|
|
311
|
+
r"""Returns a list of OpenAIFunction objects representing the
|
|
312
|
+
functions in the toolkit.
|
|
313
|
+
|
|
314
|
+
Returns:
|
|
315
|
+
List[OpenAIFunction]: A list of OpenAIFunction objects
|
|
316
|
+
representing the functions in the toolkit.
|
|
317
|
+
"""
|
|
318
|
+
return [
|
|
319
|
+
OpenAIFunction(self.search_wiki),
|
|
320
|
+
OpenAIFunction(self.search_google),
|
|
321
|
+
OpenAIFunction(self.search_duckduckgo),
|
|
322
|
+
OpenAIFunction(self.query_wolfram_alpha),
|
|
323
|
+
]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
SEARCH_FUNCS: List[OpenAIFunction] = SearchToolkit().get_tools()
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
2
|
+
# Licensed under the Apache License, Version 2.0 (the “License”);
|
|
3
|
+
# you may not use this file except in compliance with the License.
|
|
4
|
+
# You may obtain a copy of the License at
|
|
5
|
+
#
|
|
6
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
7
|
+
#
|
|
8
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
9
|
+
# distributed under the License is distributed on an “AS IS” BASIS,
|
|
10
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
11
|
+
# See the License for the specific language governing permissions and
|
|
12
|
+
# limitations under the License.
|
|
13
|
+
# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
from typing import TYPE_CHECKING, List, Optional
|
|
21
|
+
|
|
22
|
+
from camel.toolkits.base import BaseToolkit
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from ssl import SSLContext
|
|
26
|
+
|
|
27
|
+
from slack_sdk import WebClient
|
|
28
|
+
|
|
29
|
+
from camel.toolkits import OpenAIFunction
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class SlackToolkit(BaseToolkit):
|
|
35
|
+
r"""A class representing a toolkit for Slack operations.
|
|
36
|
+
|
|
37
|
+
This class provides methods for Slack operations such as creating a new
|
|
38
|
+
channel, joining an existing channel, leaving a channel.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def _login_slack(
|
|
42
|
+
self,
|
|
43
|
+
slack_token: Optional[str] = None,
|
|
44
|
+
ssl: Optional[SSLContext] = None,
|
|
45
|
+
) -> WebClient:
|
|
46
|
+
r"""Authenticate using the Slack API.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
slack_token (str, optional): The Slack API token.
|
|
50
|
+
If not provided, it attempts to retrieve the token from
|
|
51
|
+
the environment variable SLACK_BOT_TOKEN or SLACK_USER_TOKEN.
|
|
52
|
+
ssl (SSLContext, optional): SSL context for secure connections.
|
|
53
|
+
Defaults to `None`.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
WebClient: A WebClient object for interacting with Slack API.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
ImportError: If slack_sdk package is not installed.
|
|
60
|
+
KeyError: If SLACK_BOT_TOKEN or SLACK_USER_TOKEN
|
|
61
|
+
environment variables are not set.
|
|
62
|
+
"""
|
|
63
|
+
try:
|
|
64
|
+
from slack_sdk import WebClient
|
|
65
|
+
except ImportError as e:
|
|
66
|
+
raise ImportError(
|
|
67
|
+
"Cannot import slack_sdk. Please install the package with \
|
|
68
|
+
`pip install slack_sdk`."
|
|
69
|
+
) from e
|
|
70
|
+
if not slack_token:
|
|
71
|
+
slack_token = os.environ.get("SLACK_BOT_TOKEN") or os.environ.get(
|
|
72
|
+
"SLACK_USER_TOKEN"
|
|
73
|
+
)
|
|
74
|
+
if not slack_token:
|
|
75
|
+
raise KeyError(
|
|
76
|
+
"SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment "
|
|
77
|
+
"variable not set."
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
client = WebClient(token=slack_token, ssl=ssl)
|
|
81
|
+
logger.info("Slack login successful.")
|
|
82
|
+
return client
|
|
83
|
+
|
|
84
|
+
def create_slack_channel(
|
|
85
|
+
self, name: str, is_private: Optional[bool] = True
|
|
86
|
+
) -> str:
|
|
87
|
+
r"""Creates a new slack channel, either public or private.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
name (str): Name of the public or private channel to create.
|
|
91
|
+
is_private (bool, optional): Whether to create a private channel
|
|
92
|
+
instead of a public one. Defaults to `True`.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
str: JSON string containing information about Slack
|
|
96
|
+
channel created.
|
|
97
|
+
|
|
98
|
+
Raises:
|
|
99
|
+
SlackApiError: If there is an error during get slack channel
|
|
100
|
+
information.
|
|
101
|
+
"""
|
|
102
|
+
from slack_sdk.errors import SlackApiError
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
slack_client = self._login_slack()
|
|
106
|
+
response = slack_client.conversations_create(
|
|
107
|
+
name=name, is_private=is_private
|
|
108
|
+
)
|
|
109
|
+
channel_id = response["channel"]["id"]
|
|
110
|
+
response = slack_client.conversations_archive(channel=channel_id)
|
|
111
|
+
return str(response)
|
|
112
|
+
except SlackApiError as e:
|
|
113
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
114
|
+
|
|
115
|
+
def join_slack_channel(self, channel_id: str) -> str:
|
|
116
|
+
r"""Joins an existing Slack channel.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
channel_id (str): The ID of the Slack channel to join.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
str: A confirmation message indicating whether join successfully
|
|
123
|
+
or an error message.
|
|
124
|
+
|
|
125
|
+
Raises:
|
|
126
|
+
SlackApiError: If there is an error during get slack channel
|
|
127
|
+
information.
|
|
128
|
+
"""
|
|
129
|
+
from slack_sdk.errors import SlackApiError
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
slack_client = self._login_slack()
|
|
133
|
+
response = slack_client.conversations_join(channel=channel_id)
|
|
134
|
+
return str(response)
|
|
135
|
+
except SlackApiError as e:
|
|
136
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
137
|
+
|
|
138
|
+
def leave_slack_channel(self, channel_id: str) -> str:
|
|
139
|
+
r"""Leaves an existing Slack channel.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
channel_id (str): The ID of the Slack channel to leave.
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
str: A confirmation message indicating whether leave successfully
|
|
146
|
+
or an error message.
|
|
147
|
+
|
|
148
|
+
Raises:
|
|
149
|
+
SlackApiError: If there is an error during get slack channel
|
|
150
|
+
information.
|
|
151
|
+
"""
|
|
152
|
+
from slack_sdk.errors import SlackApiError
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
slack_client = self._login_slack()
|
|
156
|
+
response = slack_client.conversations_leave(channel=channel_id)
|
|
157
|
+
return str(response)
|
|
158
|
+
except SlackApiError as e:
|
|
159
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
160
|
+
|
|
161
|
+
def get_slack_channel_information(self) -> str:
|
|
162
|
+
r"""Retrieve Slack channels and return relevant information in JSON
|
|
163
|
+
format.
|
|
164
|
+
|
|
165
|
+
Returns:
|
|
166
|
+
str: JSON string containing information about Slack channels.
|
|
167
|
+
|
|
168
|
+
Raises:
|
|
169
|
+
SlackApiError: If there is an error during get slack channel
|
|
170
|
+
information.
|
|
171
|
+
"""
|
|
172
|
+
from slack_sdk.errors import SlackApiError
|
|
173
|
+
|
|
174
|
+
try:
|
|
175
|
+
slack_client = self._login_slack()
|
|
176
|
+
response = slack_client.conversations_list()
|
|
177
|
+
conversations = response["channels"]
|
|
178
|
+
# Filtering conversations and extracting required information
|
|
179
|
+
filtered_result = [
|
|
180
|
+
{
|
|
181
|
+
key: conversation[key]
|
|
182
|
+
for key in ("id", "name", "created", "num_members")
|
|
183
|
+
}
|
|
184
|
+
for conversation in conversations
|
|
185
|
+
if all(
|
|
186
|
+
key in conversation
|
|
187
|
+
for key in ("id", "name", "created", "num_members")
|
|
188
|
+
)
|
|
189
|
+
]
|
|
190
|
+
return json.dumps(filtered_result, ensure_ascii=False)
|
|
191
|
+
except SlackApiError as e:
|
|
192
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
193
|
+
|
|
194
|
+
def get_slack_channel_message(self, channel_id: str) -> str:
|
|
195
|
+
r"""Retrieve messages from a Slack channel.
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
channel_id (str): The ID of the Slack channel to retrieve messages
|
|
199
|
+
from.
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
str: JSON string containing filtered message data.
|
|
203
|
+
|
|
204
|
+
Raises:
|
|
205
|
+
SlackApiError: If there is an error during get
|
|
206
|
+
slack channel message.
|
|
207
|
+
"""
|
|
208
|
+
from slack_sdk.errors import SlackApiError
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
slack_client = self._login_slack()
|
|
212
|
+
result = slack_client.conversations_history(channel=channel_id)
|
|
213
|
+
messages = result["messages"]
|
|
214
|
+
filtered_messages = [
|
|
215
|
+
{key: message[key] for key in ("user", "text", "ts")}
|
|
216
|
+
for message in messages
|
|
217
|
+
if all(key in message for key in ("user", "text", "ts"))
|
|
218
|
+
]
|
|
219
|
+
return json.dumps(filtered_messages, ensure_ascii=False)
|
|
220
|
+
except SlackApiError as e:
|
|
221
|
+
return f"Error retrieving messages: {e.response['error']}"
|
|
222
|
+
|
|
223
|
+
def send_slack_message(
|
|
224
|
+
self,
|
|
225
|
+
message: str,
|
|
226
|
+
channel_id: str,
|
|
227
|
+
user: Optional[str] = None,
|
|
228
|
+
) -> str:
|
|
229
|
+
r"""Send a message to a Slack channel.
|
|
230
|
+
|
|
231
|
+
Args:
|
|
232
|
+
message (str): The message to send.
|
|
233
|
+
channel_id (str): The ID of the Slack channel to send message.
|
|
234
|
+
user (Optional[str]): The user ID of the recipient.
|
|
235
|
+
Defaults to `None`.
|
|
236
|
+
|
|
237
|
+
Returns:
|
|
238
|
+
str: A confirmation message indicating whether the message was sent
|
|
239
|
+
successfully or an error message.
|
|
240
|
+
|
|
241
|
+
Raises:
|
|
242
|
+
SlackApiError: If an error occurs while sending the message.
|
|
243
|
+
"""
|
|
244
|
+
from slack_sdk.errors import SlackApiError
|
|
245
|
+
|
|
246
|
+
try:
|
|
247
|
+
slack_client = self._login_slack()
|
|
248
|
+
if user:
|
|
249
|
+
response = slack_client.chat_postEphemeral(
|
|
250
|
+
channel=channel_id, text=message, user=user
|
|
251
|
+
)
|
|
252
|
+
else:
|
|
253
|
+
response = slack_client.chat_postMessage(
|
|
254
|
+
channel=channel_id, text=message
|
|
255
|
+
)
|
|
256
|
+
return str(response)
|
|
257
|
+
except SlackApiError as e:
|
|
258
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
259
|
+
|
|
260
|
+
def delete_slack_message(
|
|
261
|
+
self,
|
|
262
|
+
time_stamp: str,
|
|
263
|
+
channel_id: str,
|
|
264
|
+
) -> str:
|
|
265
|
+
r"""Delete a message to a Slack channel.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
time_stamp (str): Timestamp of the message to be deleted.
|
|
269
|
+
channel_id (str): The ID of the Slack channel to delete message.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
str: A confirmation message indicating whether the message
|
|
273
|
+
was delete successfully or an error message.
|
|
274
|
+
|
|
275
|
+
Raises:
|
|
276
|
+
SlackApiError: If an error occurs while sending the message.
|
|
277
|
+
"""
|
|
278
|
+
from slack_sdk.errors import SlackApiError
|
|
279
|
+
|
|
280
|
+
try:
|
|
281
|
+
slack_client = self._login_slack()
|
|
282
|
+
response = slack_client.chat_delete(
|
|
283
|
+
channel=channel_id, ts=time_stamp
|
|
284
|
+
)
|
|
285
|
+
return str(response)
|
|
286
|
+
except SlackApiError as e:
|
|
287
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
288
|
+
|
|
289
|
+
def get_tools(self) -> List[OpenAIFunction]:
|
|
290
|
+
r"""Returns a list of OpenAIFunction objects representing the
|
|
291
|
+
functions in the toolkit.
|
|
292
|
+
|
|
293
|
+
Returns:
|
|
294
|
+
List[OpenAIFunction]: A list of OpenAIFunction objects
|
|
295
|
+
representing the functions in the toolkit.
|
|
296
|
+
"""
|
|
297
|
+
return [
|
|
298
|
+
OpenAIFunction(self.create_slack_channel),
|
|
299
|
+
OpenAIFunction(self.join_slack_channel),
|
|
300
|
+
OpenAIFunction(self.leave_slack_channel),
|
|
301
|
+
OpenAIFunction(self.get_slack_channel_information),
|
|
302
|
+
OpenAIFunction(self.get_slack_channel_message),
|
|
303
|
+
OpenAIFunction(self.send_slack_message),
|
|
304
|
+
OpenAIFunction(self.delete_slack_message),
|
|
305
|
+
]
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
SLACK_FUNCS: List[OpenAIFunction] = SlackToolkit().get_tools()
|