camel-ai 0.1.1__py3-none-any.whl → 0.1.4__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 -11
- camel/agents/__init__.py +7 -5
- camel/agents/chat_agent.py +134 -86
- camel/agents/critic_agent.py +28 -17
- camel/agents/deductive_reasoner_agent.py +235 -0
- camel/agents/embodied_agent.py +92 -40
- camel/agents/knowledge_graph_agent.py +221 -0
- camel/agents/role_assignment_agent.py +27 -17
- camel/agents/task_agent.py +60 -34
- camel/agents/tool_agents/base.py +0 -1
- camel/agents/tool_agents/hugging_face_tool_agent.py +7 -4
- camel/configs/__init__.py +29 -0
- camel/configs/anthropic_config.py +73 -0
- camel/configs/base_config.py +22 -0
- camel/{configs.py → configs/openai_config.py} +37 -64
- camel/embeddings/__init__.py +2 -0
- camel/embeddings/base.py +3 -2
- camel/embeddings/openai_embedding.py +10 -5
- camel/embeddings/sentence_transformers_embeddings.py +65 -0
- camel/functions/__init__.py +18 -3
- camel/functions/google_maps_function.py +335 -0
- camel/functions/math_functions.py +7 -7
- camel/functions/open_api_function.py +380 -0
- camel/functions/open_api_specs/coursera/__init__.py +13 -0
- camel/functions/open_api_specs/coursera/openapi.yaml +82 -0
- camel/functions/open_api_specs/klarna/__init__.py +13 -0
- camel/functions/open_api_specs/klarna/openapi.yaml +87 -0
- camel/functions/open_api_specs/speak/__init__.py +13 -0
- camel/functions/open_api_specs/speak/openapi.yaml +151 -0
- camel/functions/openai_function.py +346 -42
- camel/functions/retrieval_functions.py +61 -0
- camel/functions/search_functions.py +100 -35
- camel/functions/slack_functions.py +275 -0
- camel/functions/twitter_function.py +484 -0
- camel/functions/weather_functions.py +36 -23
- camel/generators.py +65 -46
- camel/human.py +17 -11
- camel/interpreters/__init__.py +25 -0
- camel/interpreters/base.py +49 -0
- camel/{utils/python_interpreter.py → interpreters/internal_python_interpreter.py} +129 -48
- camel/interpreters/interpreter_error.py +19 -0
- camel/interpreters/subprocess_interpreter.py +190 -0
- camel/loaders/__init__.py +22 -0
- camel/{functions/base_io_functions.py → loaders/base_io.py} +38 -35
- camel/{functions/unstructured_io_fuctions.py → loaders/unstructured_io.py} +199 -110
- camel/memories/__init__.py +17 -7
- camel/memories/agent_memories.py +156 -0
- camel/memories/base.py +97 -32
- camel/memories/blocks/__init__.py +21 -0
- camel/memories/{chat_history_memory.py → blocks/chat_history_block.py} +34 -34
- camel/memories/blocks/vectordb_block.py +101 -0
- camel/memories/context_creators/__init__.py +3 -2
- camel/memories/context_creators/score_based.py +32 -20
- camel/memories/records.py +6 -5
- camel/messages/__init__.py +2 -2
- camel/messages/base.py +99 -16
- camel/messages/func_message.py +7 -4
- camel/models/__init__.py +6 -2
- camel/models/anthropic_model.py +146 -0
- camel/models/base_model.py +10 -3
- camel/models/model_factory.py +17 -11
- camel/models/open_source_model.py +25 -13
- camel/models/openai_audio_models.py +251 -0
- camel/models/openai_model.py +20 -13
- camel/models/stub_model.py +10 -5
- camel/prompts/__init__.py +7 -5
- camel/prompts/ai_society.py +21 -14
- camel/prompts/base.py +54 -47
- camel/prompts/code.py +22 -14
- camel/prompts/evaluation.py +8 -5
- camel/prompts/misalignment.py +26 -19
- camel/prompts/object_recognition.py +35 -0
- camel/prompts/prompt_templates.py +14 -8
- camel/prompts/role_description_prompt_template.py +16 -10
- camel/prompts/solution_extraction.py +9 -5
- camel/prompts/task_prompt_template.py +24 -21
- camel/prompts/translation.py +9 -5
- camel/responses/agent_responses.py +5 -2
- camel/retrievers/__init__.py +26 -0
- camel/retrievers/auto_retriever.py +330 -0
- camel/retrievers/base.py +69 -0
- camel/retrievers/bm25_retriever.py +140 -0
- camel/retrievers/cohere_rerank_retriever.py +108 -0
- camel/retrievers/vector_retriever.py +183 -0
- camel/societies/__init__.py +1 -1
- camel/societies/babyagi_playing.py +56 -32
- camel/societies/role_playing.py +188 -133
- camel/storages/__init__.py +18 -0
- camel/storages/graph_storages/__init__.py +23 -0
- camel/storages/graph_storages/base.py +82 -0
- camel/storages/graph_storages/graph_element.py +74 -0
- camel/storages/graph_storages/neo4j_graph.py +582 -0
- camel/storages/key_value_storages/base.py +1 -2
- camel/storages/key_value_storages/in_memory.py +1 -2
- camel/storages/key_value_storages/json.py +8 -13
- camel/storages/vectordb_storages/__init__.py +33 -0
- camel/storages/vectordb_storages/base.py +202 -0
- camel/storages/vectordb_storages/milvus.py +396 -0
- camel/storages/vectordb_storages/qdrant.py +373 -0
- camel/terminators/__init__.py +1 -1
- camel/terminators/base.py +2 -3
- camel/terminators/response_terminator.py +21 -12
- camel/terminators/token_limit_terminator.py +5 -3
- camel/toolkits/__init__.py +21 -0
- camel/toolkits/base.py +22 -0
- camel/toolkits/github_toolkit.py +245 -0
- camel/types/__init__.py +18 -6
- camel/types/enums.py +129 -15
- camel/types/openai_types.py +10 -5
- camel/utils/__init__.py +20 -13
- camel/utils/commons.py +170 -85
- camel/utils/token_counting.py +135 -15
- {camel_ai-0.1.1.dist-info → camel_ai-0.1.4.dist-info}/METADATA +123 -75
- camel_ai-0.1.4.dist-info/RECORD +119 -0
- {camel_ai-0.1.1.dist-info → camel_ai-0.1.4.dist-info}/WHEEL +1 -1
- camel/memories/context_creators/base.py +0 -72
- camel_ai-0.1.1.dist-info/RECORD +0 -75
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
import os
|
|
15
15
|
from typing import Any, Dict, List
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
from camel.functions import OpenAIFunction
|
|
17
|
+
from camel.agents import ChatAgent
|
|
18
|
+
from camel.functions.openai_function import OpenAIFunction
|
|
19
19
|
from camel.messages import BaseMessage
|
|
20
20
|
from camel.prompts import TextPrompt
|
|
21
21
|
|
|
@@ -25,10 +25,10 @@ def search_wiki(entity: str) -> str:
|
|
|
25
25
|
required page, containing factual information about the given entity.
|
|
26
26
|
|
|
27
27
|
Args:
|
|
28
|
-
entity (
|
|
28
|
+
entity (str): The entity to be searched.
|
|
29
29
|
|
|
30
30
|
Returns:
|
|
31
|
-
|
|
31
|
+
str: The search result. If the page corresponding to the entity
|
|
32
32
|
exists, return the summary of this entity in a string.
|
|
33
33
|
"""
|
|
34
34
|
try:
|
|
@@ -36,19 +36,23 @@ def search_wiki(entity: str) -> str:
|
|
|
36
36
|
except ImportError:
|
|
37
37
|
raise ImportError(
|
|
38
38
|
"Please install `wikipedia` first. You can install it by running "
|
|
39
|
-
"`pip install wikipedia`."
|
|
39
|
+
"`pip install wikipedia`."
|
|
40
|
+
)
|
|
40
41
|
|
|
41
42
|
result: str
|
|
42
43
|
|
|
43
44
|
try:
|
|
44
45
|
result = wikipedia.summary(entity, sentences=5, auto_suggest=False)
|
|
45
46
|
except wikipedia.exceptions.DisambiguationError as e:
|
|
46
|
-
result = wikipedia.summary(
|
|
47
|
-
|
|
47
|
+
result = wikipedia.summary(
|
|
48
|
+
e.options[0], sentences=5, auto_suggest=False
|
|
49
|
+
)
|
|
48
50
|
except wikipedia.exceptions.PageError:
|
|
49
|
-
result = (
|
|
50
|
-
|
|
51
|
-
|
|
51
|
+
result = (
|
|
52
|
+
"There is no page in Wikipedia corresponding to entity "
|
|
53
|
+
f"{entity}, please specify another word to describe the"
|
|
54
|
+
" entity to be searched."
|
|
55
|
+
)
|
|
52
56
|
except wikipedia.exceptions.WikipediaException as e:
|
|
53
57
|
result = f"An exception occurred during the search: {e}"
|
|
54
58
|
|
|
@@ -59,7 +63,7 @@ def search_google(query: str) -> List[Dict[str, Any]]:
|
|
|
59
63
|
r"""Use Google search engine to search information for the given query.
|
|
60
64
|
|
|
61
65
|
Args:
|
|
62
|
-
query (
|
|
66
|
+
query (str): The query to be searched.
|
|
63
67
|
|
|
64
68
|
Returns:
|
|
65
69
|
List[Dict[str, Any]]: A list of dictionaries where each dictionary
|
|
@@ -83,7 +87,7 @@ def search_google(query: str) -> List[Dict[str, Any]]:
|
|
|
83
87
|
as a whole',
|
|
84
88
|
'url': 'https://www.openai.com'
|
|
85
89
|
}
|
|
86
|
-
title,
|
|
90
|
+
title, description, url of a website.
|
|
87
91
|
"""
|
|
88
92
|
import requests
|
|
89
93
|
|
|
@@ -100,9 +104,11 @@ def search_google(query: str) -> List[Dict[str, Any]]:
|
|
|
100
104
|
num_result_pages = 10
|
|
101
105
|
# Constructing the URL
|
|
102
106
|
# Doc: https://developers.google.com/custom-search/v1/using_rest
|
|
103
|
-
url =
|
|
104
|
-
|
|
105
|
-
|
|
107
|
+
url = (
|
|
108
|
+
f"https://www.googleapis.com/customsearch/v1?"
|
|
109
|
+
f"key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}&start="
|
|
110
|
+
f"{start_page_idx}&lr={search_language}&num={num_result_pages}"
|
|
111
|
+
)
|
|
106
112
|
|
|
107
113
|
responses = []
|
|
108
114
|
# Fetch the results given the URL
|
|
@@ -118,8 +124,9 @@ def search_google(query: str) -> List[Dict[str, Any]]:
|
|
|
118
124
|
# Iterate over 10 results found
|
|
119
125
|
for i, search_item in enumerate(search_items, start=1):
|
|
120
126
|
if "og:description" in search_item["pagemap"]["metatags"][0]:
|
|
121
|
-
long_description =
|
|
122
|
-
|
|
127
|
+
long_description = search_item["pagemap"]["metatags"][0][
|
|
128
|
+
"og:description"
|
|
129
|
+
]
|
|
123
130
|
else:
|
|
124
131
|
long_description = "N/A"
|
|
125
132
|
# Get the page title
|
|
@@ -134,7 +141,7 @@ def search_google(query: str) -> List[Dict[str, Any]]:
|
|
|
134
141
|
"title": title,
|
|
135
142
|
"description": snippet,
|
|
136
143
|
"long_description": long_description,
|
|
137
|
-
"url": link
|
|
144
|
+
"url": link,
|
|
138
145
|
}
|
|
139
146
|
responses.append(response)
|
|
140
147
|
else:
|
|
@@ -150,10 +157,10 @@ def text_extract_from_web(url: str) -> str:
|
|
|
150
157
|
r"""Get the text information from given url.
|
|
151
158
|
|
|
152
159
|
Args:
|
|
153
|
-
url (
|
|
160
|
+
url (str): The website you want to search.
|
|
154
161
|
|
|
155
162
|
Returns:
|
|
156
|
-
|
|
163
|
+
str: All texts extract from the web.
|
|
157
164
|
"""
|
|
158
165
|
import requests
|
|
159
166
|
from bs4 import BeautifulSoup
|
|
@@ -171,8 +178,9 @@ def text_extract_from_web(url: str) -> str:
|
|
|
171
178
|
text = soup.get_text()
|
|
172
179
|
# Strip text
|
|
173
180
|
lines = (line.strip() for line in text.splitlines())
|
|
174
|
-
chunks = (
|
|
175
|
-
|
|
181
|
+
chunks = (
|
|
182
|
+
phrase.strip() for line in lines for phrase in line.split(" ")
|
|
183
|
+
)
|
|
176
184
|
text = ".".join(chunk for chunk in chunks if chunk)
|
|
177
185
|
|
|
178
186
|
except requests.RequestException:
|
|
@@ -186,11 +194,11 @@ def create_chunks(text: str, n: int) -> List[str]:
|
|
|
186
194
|
r"""Returns successive n-sized chunks from provided text."
|
|
187
195
|
|
|
188
196
|
Args:
|
|
189
|
-
text (
|
|
197
|
+
text (str): The text to be split.
|
|
190
198
|
n (int): The max length of a single chunk.
|
|
191
199
|
|
|
192
200
|
Returns:
|
|
193
|
-
List[str]: A list of
|
|
201
|
+
List[str]: A list of split texts.
|
|
194
202
|
"""
|
|
195
203
|
|
|
196
204
|
chunks = []
|
|
@@ -220,7 +228,7 @@ def prompt_single_step_agent(prompt: str) -> str:
|
|
|
220
228
|
role_name="Assistant",
|
|
221
229
|
content="You are a helpful assistant.",
|
|
222
230
|
)
|
|
223
|
-
agent =
|
|
231
|
+
agent = ChatAgent(assistant_sys_msg)
|
|
224
232
|
agent.reset()
|
|
225
233
|
|
|
226
234
|
user_msg = BaseMessage.make_user_message(
|
|
@@ -238,15 +246,16 @@ def summarize_text(text: str, query: str) -> str:
|
|
|
238
246
|
given.
|
|
239
247
|
|
|
240
248
|
Args:
|
|
241
|
-
text (
|
|
242
|
-
query (
|
|
249
|
+
text (str): Text to summarize.
|
|
250
|
+
query (str): What information you want.
|
|
243
251
|
|
|
244
252
|
Returns:
|
|
245
|
-
|
|
253
|
+
str: Strings with information.
|
|
246
254
|
"""
|
|
247
255
|
summary_prompt = TextPrompt(
|
|
248
256
|
'''Gather information from this text that relative to the question, but
|
|
249
|
-
do not directly answer the question.\nquestion: {query}\ntext '''
|
|
257
|
+
do not directly answer the question.\nquestion: {query}\ntext '''
|
|
258
|
+
)
|
|
250
259
|
summary_prompt = summary_prompt.format(query=query)
|
|
251
260
|
# Max length of each chunk
|
|
252
261
|
max_len = 3000
|
|
@@ -261,7 +270,8 @@ def summarize_text(text: str, query: str) -> str:
|
|
|
261
270
|
# Final summarise
|
|
262
271
|
final_prompt = TextPrompt(
|
|
263
272
|
'''Here are some summarized texts which split from one text, Using the
|
|
264
|
-
information to answer the question: {query}.\n\nText: '''
|
|
273
|
+
information to answer the question: {query}.\n\nText: '''
|
|
274
|
+
)
|
|
265
275
|
final_prompt = final_prompt.format(query=query)
|
|
266
276
|
prompt = final_prompt + results
|
|
267
277
|
|
|
@@ -276,10 +286,10 @@ def search_google_and_summarize(query: str) -> str:
|
|
|
276
286
|
internet, and then return a summarized answer.
|
|
277
287
|
|
|
278
288
|
Args:
|
|
279
|
-
query (
|
|
289
|
+
query (str): Question you want to be answered.
|
|
280
290
|
|
|
281
291
|
Returns:
|
|
282
|
-
|
|
292
|
+
str: Summarized information from webs.
|
|
283
293
|
"""
|
|
284
294
|
# Google search will return a list of urls
|
|
285
295
|
responses = search_google(query)
|
|
@@ -294,7 +304,8 @@ def search_google_and_summarize(query: str) -> str:
|
|
|
294
304
|
# Let chatgpt decide whether to continue search or not
|
|
295
305
|
prompt = TextPrompt(
|
|
296
306
|
'''Do you think the answer: {answer} can answer the query:
|
|
297
|
-
{query}. Use only 'yes' or 'no' to answer.'''
|
|
307
|
+
{query}. Use only 'yes' or 'no' to answer.'''
|
|
308
|
+
)
|
|
298
309
|
prompt = prompt.format(answer=answer, query=query)
|
|
299
310
|
reply = prompt_single_step_agent(prompt)
|
|
300
311
|
if "yes" in str(reply).lower():
|
|
@@ -303,7 +314,61 @@ def search_google_and_summarize(query: str) -> str:
|
|
|
303
314
|
return "Failed to find the answer from google search."
|
|
304
315
|
|
|
305
316
|
|
|
317
|
+
def query_wolfram_alpha(query: str, is_detailed: bool) -> str:
|
|
318
|
+
r"""Queries Wolfram|Alpha and returns the result. Wolfram|Alpha is an
|
|
319
|
+
answer engine developed by Wolfram Research. It is offered as an online
|
|
320
|
+
service that answers factual queries by computing answers from externally
|
|
321
|
+
sourced data.
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
query (str): The query to send to Wolfram Alpha.
|
|
325
|
+
is_detailed (bool): Whether to include additional details in the
|
|
326
|
+
result.
|
|
327
|
+
|
|
328
|
+
Returns:
|
|
329
|
+
str: The result from Wolfram Alpha, formatted as a string.
|
|
330
|
+
"""
|
|
331
|
+
try:
|
|
332
|
+
import wolframalpha
|
|
333
|
+
except ImportError:
|
|
334
|
+
raise ImportError(
|
|
335
|
+
"Please install `wolframalpha` first. You can install it by running `pip install wolframalpha`."
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
WOLFRAMALPHA_APP_ID = os.environ.get('WOLFRAMALPHA_APP_ID')
|
|
339
|
+
if not WOLFRAMALPHA_APP_ID:
|
|
340
|
+
raise ValueError(
|
|
341
|
+
"`WOLFRAMALPHA_APP_ID` not found in environment "
|
|
342
|
+
"variables. Get `WOLFRAMALPHA_APP_ID` here: "
|
|
343
|
+
"`https://products.wolframalpha.com/api/`."
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
try:
|
|
347
|
+
client = wolframalpha.Client(WOLFRAMALPHA_APP_ID)
|
|
348
|
+
res = client.query(query)
|
|
349
|
+
assumption = next(res.pods).text or "No assumption made."
|
|
350
|
+
answer = next(res.results).text or "No answer found."
|
|
351
|
+
except Exception as e:
|
|
352
|
+
if isinstance(e, StopIteration):
|
|
353
|
+
return "Wolfram Alpha wasn't able to answer it"
|
|
354
|
+
else:
|
|
355
|
+
error_message = f"Wolfram Alpha wasn't able to answer it" f"{e!s}."
|
|
356
|
+
return error_message
|
|
357
|
+
|
|
358
|
+
result = f"Assumption:\n{assumption}\n\nAnswer:\n{answer}"
|
|
359
|
+
|
|
360
|
+
# Add additional details in the result
|
|
361
|
+
if is_detailed:
|
|
362
|
+
result += '\n'
|
|
363
|
+
for pod in res.pods:
|
|
364
|
+
result += '\n' + pod['@title'] + ':\n'
|
|
365
|
+
for sub in pod.subpods:
|
|
366
|
+
result += (sub.plaintext or "None") + '\n'
|
|
367
|
+
|
|
368
|
+
return result.rstrip() # Remove trailing whitespace
|
|
369
|
+
|
|
370
|
+
|
|
306
371
|
SEARCH_FUNCS: List[OpenAIFunction] = [
|
|
307
|
-
OpenAIFunction(func)
|
|
308
|
-
for func in [search_wiki, search_google_and_summarize]
|
|
372
|
+
OpenAIFunction(func) # type: ignore[arg-type]
|
|
373
|
+
for func in [search_wiki, search_google_and_summarize, query_wolfram_alpha]
|
|
309
374
|
]
|
|
@@ -0,0 +1,275 @@
|
|
|
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
|
+
if TYPE_CHECKING:
|
|
23
|
+
from ssl import SSLContext
|
|
24
|
+
|
|
25
|
+
from slack_sdk import WebClient
|
|
26
|
+
|
|
27
|
+
from slack_sdk.errors import SlackApiError
|
|
28
|
+
|
|
29
|
+
from camel.functions import OpenAIFunction
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _login_slack(
|
|
35
|
+
slack_token: Optional[str] = None,
|
|
36
|
+
ssl: Optional[SSLContext] = None,
|
|
37
|
+
) -> WebClient:
|
|
38
|
+
r"""Authenticate using the Slack API.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
slack_token (str, optional): The Slack API token. If not provided, it
|
|
42
|
+
attempts to retrieve the token from the environment variable
|
|
43
|
+
SLACK_BOT_TOKEN or SLACK_USER_TOKEN.
|
|
44
|
+
ssl (SSLContext, optional): SSL context for secure connections.
|
|
45
|
+
Defaults to `None`.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
WebClient: A WebClient object for interacting with Slack API.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
ImportError: If slack_sdk package is not installed.
|
|
52
|
+
KeyError: If SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variables
|
|
53
|
+
are not set.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
from slack_sdk import WebClient
|
|
57
|
+
except ImportError as e:
|
|
58
|
+
raise ImportError(
|
|
59
|
+
"Cannot import slack_sdk. Please install the package with \
|
|
60
|
+
`pip install slack_sdk`."
|
|
61
|
+
) from e
|
|
62
|
+
if not slack_token:
|
|
63
|
+
slack_token = os.environ.get("SLACK_BOT_TOKEN") or os.environ.get(
|
|
64
|
+
"SLACK_USER_TOKEN"
|
|
65
|
+
)
|
|
66
|
+
if not slack_token:
|
|
67
|
+
raise KeyError(
|
|
68
|
+
"SLACK_BOT_TOKEN or SLACK_USER_TOKEN environment variable not set."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
client = WebClient(token=slack_token, ssl=ssl)
|
|
72
|
+
logger.info("Slack login successful.")
|
|
73
|
+
return client
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def create_slack_channel(name: str, is_private: Optional[bool] = True) -> str:
|
|
77
|
+
r"""Creates a new slack channel, either public or private.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
name (str): Name of the public or private channel to create.
|
|
81
|
+
is_private (bool, optional): Whether to create a private channel
|
|
82
|
+
instead of a public one. Defaults to `True`.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
str: JSON string containing information about Slack channel created.
|
|
86
|
+
|
|
87
|
+
Raises:
|
|
88
|
+
SlackApiError: If there is an error during get slack channel
|
|
89
|
+
information.
|
|
90
|
+
"""
|
|
91
|
+
try:
|
|
92
|
+
slack_client = _login_slack()
|
|
93
|
+
response = slack_client.conversations_create(
|
|
94
|
+
name=name, is_private=is_private
|
|
95
|
+
)
|
|
96
|
+
channel_id = response["channel"]["id"]
|
|
97
|
+
response = slack_client.conversations_archive(channel=channel_id)
|
|
98
|
+
return str(response)
|
|
99
|
+
except SlackApiError as e:
|
|
100
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def join_slack_channel(channel_id: str) -> str:
|
|
104
|
+
r"""Joins an existing Slack channel.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
channel_id (str): The ID of the Slack channel to join.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
str: A confirmation message indicating whether join successfully or an
|
|
111
|
+
error message.
|
|
112
|
+
|
|
113
|
+
Raises:
|
|
114
|
+
SlackApiError: If there is an error during get slack channel
|
|
115
|
+
information.
|
|
116
|
+
"""
|
|
117
|
+
try:
|
|
118
|
+
slack_client = _login_slack()
|
|
119
|
+
response = slack_client.conversations_join(channel=channel_id)
|
|
120
|
+
return str(response)
|
|
121
|
+
except SlackApiError as e:
|
|
122
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def leave_slack_channel(channel_id: str) -> str:
|
|
126
|
+
r"""Leaves an existing Slack channel.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
channel_id (str): The ID of the Slack channel to leave.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
str: A confirmation message indicating whether leave successfully or an
|
|
133
|
+
error message.
|
|
134
|
+
|
|
135
|
+
Raises:
|
|
136
|
+
SlackApiError: If there is an error during get slack channel
|
|
137
|
+
information.
|
|
138
|
+
"""
|
|
139
|
+
try:
|
|
140
|
+
slack_client = _login_slack()
|
|
141
|
+
response = slack_client.conversations_leave(channel=channel_id)
|
|
142
|
+
return str(response)
|
|
143
|
+
except SlackApiError as e:
|
|
144
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def get_slack_channel_information() -> str:
|
|
148
|
+
r"""Retrieve Slack channels and return relevant information in JSON format.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
str: JSON string containing information about Slack channels.
|
|
152
|
+
|
|
153
|
+
Raises:
|
|
154
|
+
SlackApiError: If there is an error during get slack channel
|
|
155
|
+
information.
|
|
156
|
+
"""
|
|
157
|
+
try:
|
|
158
|
+
slack_client = _login_slack()
|
|
159
|
+
response = slack_client.conversations_list()
|
|
160
|
+
conversations = response["channels"]
|
|
161
|
+
# Filtering conversations and extracting required information
|
|
162
|
+
filtered_result = [
|
|
163
|
+
{
|
|
164
|
+
key: conversation[key]
|
|
165
|
+
for key in ("id", "name", "created", "num_members")
|
|
166
|
+
}
|
|
167
|
+
for conversation in conversations
|
|
168
|
+
if all(
|
|
169
|
+
key in conversation
|
|
170
|
+
for key in ("id", "name", "created", "num_members")
|
|
171
|
+
)
|
|
172
|
+
]
|
|
173
|
+
return json.dumps(filtered_result, ensure_ascii=False)
|
|
174
|
+
except SlackApiError as e:
|
|
175
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def get_slack_channel_message(channel_id: str) -> str:
|
|
179
|
+
r"""Retrieve messages from a Slack channel.
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
channel_id (str): The ID of the Slack channel to retrieve messages
|
|
183
|
+
from.
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
str: JSON string containing filtered message data.
|
|
187
|
+
|
|
188
|
+
Raises:
|
|
189
|
+
SlackApiError: If there is an error during get slack channel message.
|
|
190
|
+
"""
|
|
191
|
+
try:
|
|
192
|
+
slack_client = _login_slack()
|
|
193
|
+
result = slack_client.conversations_history(channel=channel_id)
|
|
194
|
+
messages = result["messages"]
|
|
195
|
+
filtered_messages = [
|
|
196
|
+
{key: message[key] for key in ("user", "text", "ts")}
|
|
197
|
+
for message in messages
|
|
198
|
+
if all(key in message for key in ("user", "text", "ts"))
|
|
199
|
+
]
|
|
200
|
+
return json.dumps(filtered_messages, ensure_ascii=False)
|
|
201
|
+
except SlackApiError as e:
|
|
202
|
+
return f"Error retrieving messages: {e.response['error']}"
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def send_slack_message(
|
|
206
|
+
message: str,
|
|
207
|
+
channel_id: str,
|
|
208
|
+
user: Optional[str] = None,
|
|
209
|
+
) -> str:
|
|
210
|
+
r"""Send a message to a Slack channel.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
message (str): The message to send.
|
|
214
|
+
channel_id (str): The ID of the Slack channel to send message.
|
|
215
|
+
user (Optional[str]): The user ID of the recipient. Defaults to `None`.
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
str: A confirmation message indicating whether the message was sent
|
|
219
|
+
successfully or an error message.
|
|
220
|
+
|
|
221
|
+
Raises:
|
|
222
|
+
SlackApiError: If an error occurs while sending the message.
|
|
223
|
+
"""
|
|
224
|
+
try:
|
|
225
|
+
slack_client = _login_slack()
|
|
226
|
+
if user:
|
|
227
|
+
response = slack_client.chat_postEphemeral(
|
|
228
|
+
channel=channel_id, text=message, user=user
|
|
229
|
+
)
|
|
230
|
+
else:
|
|
231
|
+
response = slack_client.chat_postMessage(
|
|
232
|
+
channel=channel_id, text=message
|
|
233
|
+
)
|
|
234
|
+
return str(response)
|
|
235
|
+
except SlackApiError as e:
|
|
236
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def delete_slack_message(
|
|
240
|
+
time_stamp: str,
|
|
241
|
+
channel_id: str,
|
|
242
|
+
) -> str:
|
|
243
|
+
r"""Delete a message to a Slack channel.
|
|
244
|
+
|
|
245
|
+
Args:
|
|
246
|
+
time_stamp (str): Timestamp of the message to be deleted.
|
|
247
|
+
channel_id (str): The ID of the Slack channel to delete message.
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
str: A confirmation message indicating whether the message was delete
|
|
251
|
+
successfully or an error message.
|
|
252
|
+
|
|
253
|
+
Raises:
|
|
254
|
+
SlackApiError: If an error occurs while sending the message.
|
|
255
|
+
"""
|
|
256
|
+
try:
|
|
257
|
+
slack_client = _login_slack()
|
|
258
|
+
response = slack_client.chat_delete(channel=channel_id, ts=time_stamp)
|
|
259
|
+
return str(response)
|
|
260
|
+
except SlackApiError as e:
|
|
261
|
+
return f"Error creating conversation: {e.response['error']}"
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
SLACK_FUNCS: List[OpenAIFunction] = [
|
|
265
|
+
OpenAIFunction(func) # type: ignore[arg-type]
|
|
266
|
+
for func in [
|
|
267
|
+
create_slack_channel,
|
|
268
|
+
join_slack_channel,
|
|
269
|
+
leave_slack_channel,
|
|
270
|
+
get_slack_channel_information,
|
|
271
|
+
get_slack_channel_message,
|
|
272
|
+
send_slack_message,
|
|
273
|
+
delete_slack_message,
|
|
274
|
+
]
|
|
275
|
+
]
|