camel-ai 0.2.9__py3-none-any.whl → 0.2.10__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.

Files changed (236) hide show
  1. camel/__init__.py +5 -5
  2. camel/agents/__init__.py +4 -4
  3. camel/agents/base.py +4 -4
  4. camel/agents/chat_agent.py +32 -37
  5. camel/agents/critic_agent.py +4 -4
  6. camel/agents/deductive_reasoner_agent.py +4 -4
  7. camel/agents/embodied_agent.py +4 -4
  8. camel/agents/knowledge_graph_agent.py +4 -4
  9. camel/agents/role_assignment_agent.py +4 -4
  10. camel/agents/search_agent.py +4 -4
  11. camel/agents/task_agent.py +4 -4
  12. camel/agents/tool_agents/__init__.py +4 -4
  13. camel/agents/tool_agents/base.py +4 -4
  14. camel/agents/tool_agents/hugging_face_tool_agent.py +4 -4
  15. camel/bots/__init__.py +4 -4
  16. camel/bots/discord_app.py +4 -4
  17. camel/bots/slack/__init__.py +4 -4
  18. camel/bots/slack/models.py +4 -4
  19. camel/bots/slack/slack_app.py +4 -4
  20. camel/bots/telegram_bot.py +4 -4
  21. camel/configs/__init__.py +10 -4
  22. camel/configs/anthropic_config.py +4 -4
  23. camel/configs/base_config.py +4 -4
  24. camel/configs/cohere_config.py +76 -0
  25. camel/configs/deepseek_config.py +134 -0
  26. camel/configs/gemini_config.py +85 -127
  27. camel/configs/groq_config.py +4 -4
  28. camel/configs/litellm_config.py +4 -4
  29. camel/configs/mistral_config.py +4 -4
  30. camel/configs/ollama_config.py +4 -4
  31. camel/configs/openai_config.py +32 -7
  32. camel/configs/qwen_config.py +4 -4
  33. camel/configs/reka_config.py +4 -4
  34. camel/configs/samba_config.py +4 -4
  35. camel/configs/togetherai_config.py +4 -4
  36. camel/configs/vllm_config.py +4 -4
  37. camel/configs/yi_config.py +4 -4
  38. camel/configs/zhipuai_config.py +4 -4
  39. camel/embeddings/__init__.py +6 -4
  40. camel/embeddings/base.py +4 -4
  41. camel/embeddings/mistral_embedding.py +4 -4
  42. camel/embeddings/openai_compatible_embedding.py +91 -0
  43. camel/embeddings/openai_embedding.py +4 -4
  44. camel/embeddings/sentence_transformers_embeddings.py +4 -4
  45. camel/embeddings/vlm_embedding.py +4 -4
  46. camel/generators.py +4 -4
  47. camel/human.py +4 -4
  48. camel/interpreters/__init__.py +4 -4
  49. camel/interpreters/base.py +4 -4
  50. camel/interpreters/docker_interpreter.py +4 -4
  51. camel/interpreters/internal_python_interpreter.py +4 -4
  52. camel/interpreters/interpreter_error.py +4 -4
  53. camel/interpreters/ipython_interpreter.py +4 -4
  54. camel/interpreters/subprocess_interpreter.py +4 -4
  55. camel/loaders/__init__.py +4 -4
  56. camel/loaders/apify_reader.py +4 -4
  57. camel/loaders/base_io.py +4 -4
  58. camel/loaders/chunkr_reader.py +4 -4
  59. camel/loaders/firecrawl_reader.py +4 -4
  60. camel/loaders/jina_url_reader.py +4 -4
  61. camel/loaders/unstructured_io.py +4 -4
  62. camel/memories/__init__.py +4 -4
  63. camel/memories/agent_memories.py +4 -4
  64. camel/memories/base.py +4 -4
  65. camel/memories/blocks/__init__.py +4 -4
  66. camel/memories/blocks/chat_history_block.py +4 -4
  67. camel/memories/blocks/vectordb_block.py +4 -4
  68. camel/memories/context_creators/__init__.py +4 -4
  69. camel/memories/context_creators/score_based.py +4 -4
  70. camel/memories/records.py +4 -4
  71. camel/messages/__init__.py +20 -4
  72. camel/messages/base.py +108 -4
  73. camel/messages/conversion/__init__.py +29 -0
  74. camel/messages/conversion/models.py +178 -0
  75. camel/messages/conversion/sharegpt/__init__.py +20 -0
  76. camel/messages/conversion/sharegpt/function_call_formatter.py +49 -0
  77. camel/messages/conversion/sharegpt/hermes/__init__.py +19 -0
  78. camel/messages/conversion/sharegpt/hermes/hermes_function_formatter.py +128 -0
  79. camel/messages/func_message.py +50 -4
  80. camel/models/__init__.py +8 -4
  81. camel/models/anthropic_model.py +4 -4
  82. camel/models/azure_openai_model.py +4 -4
  83. camel/models/base_model.py +4 -4
  84. camel/models/cohere_model.py +282 -0
  85. camel/models/deepseek_model.py +139 -0
  86. camel/models/gemini_model.py +61 -146
  87. camel/models/groq_model.py +4 -4
  88. camel/models/litellm_model.py +4 -4
  89. camel/models/mistral_model.py +4 -4
  90. camel/models/model_factory.py +10 -4
  91. camel/models/nemotron_model.py +4 -4
  92. camel/models/ollama_model.py +4 -4
  93. camel/models/openai_audio_models.py +4 -4
  94. camel/models/openai_compatible_model.py +4 -4
  95. camel/models/openai_model.py +42 -4
  96. camel/models/qwen_model.py +4 -4
  97. camel/models/reka_model.py +4 -4
  98. camel/models/samba_model.py +6 -5
  99. camel/models/stub_model.py +4 -4
  100. camel/models/togetherai_model.py +4 -4
  101. camel/models/vllm_model.py +4 -4
  102. camel/models/yi_model.py +4 -4
  103. camel/models/zhipuai_model.py +4 -4
  104. camel/personas/__init__.py +17 -0
  105. camel/personas/persona.py +103 -0
  106. camel/personas/persona_hub.py +293 -0
  107. camel/prompts/__init__.py +6 -4
  108. camel/prompts/ai_society.py +4 -4
  109. camel/prompts/base.py +4 -4
  110. camel/prompts/code.py +4 -4
  111. camel/prompts/evaluation.py +4 -4
  112. camel/prompts/generate_text_embedding_data.py +4 -4
  113. camel/prompts/image_craft.py +4 -4
  114. camel/prompts/misalignment.py +4 -4
  115. camel/prompts/multi_condition_image_craft.py +4 -4
  116. camel/prompts/object_recognition.py +4 -4
  117. camel/prompts/persona_hub.py +61 -0
  118. camel/prompts/prompt_templates.py +4 -4
  119. camel/prompts/role_description_prompt_template.py +4 -4
  120. camel/prompts/solution_extraction.py +4 -4
  121. camel/prompts/task_prompt_template.py +4 -4
  122. camel/prompts/translation.py +4 -4
  123. camel/prompts/video_description_prompt.py +4 -4
  124. camel/responses/__init__.py +4 -4
  125. camel/responses/agent_responses.py +4 -4
  126. camel/retrievers/__init__.py +4 -4
  127. camel/retrievers/auto_retriever.py +4 -4
  128. camel/retrievers/base.py +4 -4
  129. camel/retrievers/bm25_retriever.py +4 -4
  130. camel/retrievers/cohere_rerank_retriever.py +7 -9
  131. camel/retrievers/vector_retriever.py +4 -4
  132. camel/runtime/__init__.py +29 -0
  133. camel/runtime/api.py +93 -0
  134. camel/runtime/base.py +45 -0
  135. camel/runtime/configs.py +56 -0
  136. camel/runtime/docker_runtime.py +404 -0
  137. camel/runtime/llm_guard_runtime.py +199 -0
  138. camel/runtime/remote_http_runtime.py +204 -0
  139. camel/runtime/utils/__init__.py +20 -0
  140. camel/runtime/utils/function_risk_toolkit.py +58 -0
  141. camel/runtime/utils/ignore_risk_toolkit.py +72 -0
  142. camel/schemas/__init__.py +17 -0
  143. camel/schemas/base.py +45 -0
  144. camel/schemas/openai_converter.py +116 -0
  145. camel/societies/__init__.py +4 -4
  146. camel/societies/babyagi_playing.py +4 -4
  147. camel/societies/role_playing.py +4 -4
  148. camel/societies/workforce/__init__.py +4 -4
  149. camel/societies/workforce/base.py +4 -4
  150. camel/societies/workforce/prompts.py +4 -4
  151. camel/societies/workforce/role_playing_worker.py +4 -4
  152. camel/societies/workforce/single_agent_worker.py +4 -4
  153. camel/societies/workforce/task_channel.py +4 -4
  154. camel/societies/workforce/utils.py +4 -4
  155. camel/societies/workforce/worker.py +4 -4
  156. camel/societies/workforce/workforce.py +7 -7
  157. camel/storages/__init__.py +4 -4
  158. camel/storages/graph_storages/__init__.py +4 -4
  159. camel/storages/graph_storages/base.py +4 -4
  160. camel/storages/graph_storages/graph_element.py +4 -4
  161. camel/storages/graph_storages/nebula_graph.py +4 -4
  162. camel/storages/graph_storages/neo4j_graph.py +4 -4
  163. camel/storages/key_value_storages/__init__.py +4 -4
  164. camel/storages/key_value_storages/base.py +4 -4
  165. camel/storages/key_value_storages/in_memory.py +4 -4
  166. camel/storages/key_value_storages/json.py +4 -4
  167. camel/storages/key_value_storages/redis.py +4 -4
  168. camel/storages/object_storages/__init__.py +4 -4
  169. camel/storages/object_storages/amazon_s3.py +4 -4
  170. camel/storages/object_storages/azure_blob.py +4 -4
  171. camel/storages/object_storages/base.py +4 -4
  172. camel/storages/object_storages/google_cloud.py +4 -4
  173. camel/storages/vectordb_storages/__init__.py +4 -4
  174. camel/storages/vectordb_storages/base.py +4 -4
  175. camel/storages/vectordb_storages/milvus.py +4 -4
  176. camel/storages/vectordb_storages/qdrant.py +4 -4
  177. camel/tasks/__init__.py +4 -4
  178. camel/tasks/task.py +4 -4
  179. camel/tasks/task_prompt.py +4 -4
  180. camel/terminators/__init__.py +4 -4
  181. camel/terminators/base.py +4 -4
  182. camel/terminators/response_terminator.py +4 -4
  183. camel/terminators/token_limit_terminator.py +4 -4
  184. camel/toolkits/__init__.py +13 -17
  185. camel/toolkits/arxiv_toolkit.py +4 -4
  186. camel/toolkits/ask_news_toolkit.py +7 -18
  187. camel/toolkits/base.py +4 -4
  188. camel/toolkits/code_execution.py +20 -7
  189. camel/toolkits/dalle_toolkit.py +4 -7
  190. camel/toolkits/data_commons_toolkit.py +4 -4
  191. camel/toolkits/function_tool.py +220 -69
  192. camel/toolkits/github_toolkit.py +4 -4
  193. camel/toolkits/google_maps_toolkit.py +4 -4
  194. camel/toolkits/google_scholar_toolkit.py +4 -4
  195. camel/toolkits/human_toolkit.py +52 -0
  196. camel/toolkits/linkedin_toolkit.py +4 -4
  197. camel/toolkits/math_toolkit.py +4 -7
  198. camel/toolkits/notion_toolkit.py +4 -4
  199. camel/toolkits/open_api_specs/biztoc/__init__.py +4 -4
  200. camel/toolkits/open_api_specs/coursera/__init__.py +4 -4
  201. camel/toolkits/open_api_specs/create_qr_code/__init__.py +4 -4
  202. camel/toolkits/open_api_specs/klarna/__init__.py +4 -4
  203. camel/toolkits/open_api_specs/nasa_apod/__init__.py +4 -4
  204. camel/toolkits/open_api_specs/outschool/__init__.py +4 -4
  205. camel/toolkits/open_api_specs/outschool/paths/__init__.py +4 -4
  206. camel/toolkits/open_api_specs/outschool/paths/get_classes.py +4 -4
  207. camel/toolkits/open_api_specs/outschool/paths/search_teachers.py +4 -4
  208. camel/toolkits/open_api_specs/security_config.py +4 -4
  209. camel/toolkits/open_api_specs/speak/__init__.py +4 -4
  210. camel/toolkits/open_api_specs/web_scraper/__init__.py +4 -4
  211. camel/toolkits/open_api_specs/web_scraper/paths/__init__.py +4 -4
  212. camel/toolkits/open_api_specs/web_scraper/paths/scraper.py +4 -4
  213. camel/toolkits/open_api_toolkit.py +4 -4
  214. camel/toolkits/reddit_toolkit.py +4 -4
  215. camel/toolkits/retrieval_toolkit.py +4 -4
  216. camel/toolkits/search_toolkit.py +49 -29
  217. camel/toolkits/slack_toolkit.py +4 -4
  218. camel/toolkits/twitter_toolkit.py +10 -13
  219. camel/toolkits/video_toolkit.py +211 -0
  220. camel/toolkits/weather_toolkit.py +4 -7
  221. camel/toolkits/whatsapp_toolkit.py +6 -6
  222. camel/types/__init__.py +6 -4
  223. camel/types/enums.py +77 -7
  224. camel/types/openai_types.py +6 -4
  225. camel/types/unified_model_type.py +9 -4
  226. camel/utils/__init__.py +35 -33
  227. camel/utils/async_func.py +4 -4
  228. camel/utils/commons.py +4 -4
  229. camel/utils/constants.py +4 -4
  230. camel/utils/response_format.py +63 -0
  231. camel/utils/token_counting.py +4 -4
  232. {camel_ai-0.2.9.dist-info → camel_ai-0.2.10.dist-info}/METADATA +108 -56
  233. camel_ai-0.2.10.dist-info/RECORD +246 -0
  234. camel_ai-0.2.9.dist-info/RECORD +0 -215
  235. {camel_ai-0.2.9.dist-info → camel_ai-0.2.10.dist-info}/LICENSE +0 -0
  236. {camel_ai-0.2.9.dist-info → camel_ai-0.2.10.dist-info}/WHEEL +0 -0
@@ -0,0 +1,204 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ import atexit
15
+ import json
16
+ import logging
17
+ import subprocess
18
+ import time
19
+ from functools import wraps
20
+ from pathlib import Path
21
+ from subprocess import Popen
22
+ from typing import Any, Dict, List, Optional, Union
23
+
24
+ import requests
25
+ from pydantic import BaseModel
26
+
27
+ from camel.runtime import BaseRuntime
28
+ from camel.toolkits.function_tool import FunctionTool
29
+
30
+ logger = logging.getLogger(__name__)
31
+
32
+
33
+ class RemoteHttpRuntime(BaseRuntime):
34
+ r"""A runtime that runs functions in a remote HTTP server.
35
+ You need to run the API server in the remote server first.
36
+
37
+ Args:
38
+ host (str): The host of the remote server.
39
+ port (int): The port of the remote server. (default::obj: `8000`)
40
+ python_exec (str): The python executable to run the API server.
41
+ (default::obj: `python3`)
42
+ """
43
+
44
+ def __init__(
45
+ self, host: str, port: int = 8000, python_exec: str = "python3"
46
+ ):
47
+ super().__init__()
48
+ self.host = host
49
+ self.port = port
50
+ self.python_exec = python_exec
51
+ self.api_path = Path(__file__).parent / "api.py"
52
+ self.entrypoint: Dict[str, str] = dict()
53
+ self.process: Optional[Popen] = None
54
+
55
+ def build(self) -> "RemoteHttpRuntime":
56
+ r"""Build the API server.
57
+
58
+ Returns:
59
+ RemoteHttpRuntime: The current runtime.
60
+ """
61
+ self.process = subprocess.Popen(
62
+ [
63
+ self.python_exec,
64
+ str(self.api_path),
65
+ *list(self.entrypoint.values()),
66
+ ]
67
+ )
68
+ atexit.register(self._cleanup)
69
+ return self
70
+
71
+ def _cleanup(self):
72
+ r"""Clean up the API server when exiting."""
73
+
74
+ if self.process and self.process.poll() is None:
75
+ self.process.terminate()
76
+ self.process.wait()
77
+ self.process = None
78
+
79
+ def add( # type: ignore[override]
80
+ self,
81
+ funcs: Union[FunctionTool, List[FunctionTool]],
82
+ entrypoint: str,
83
+ redirect_stdout: bool = False,
84
+ arguments: Optional[Dict[str, Any]] = None,
85
+ ) -> "RemoteHttpRuntime":
86
+ r"""Add a function or list of functions to the runtime.
87
+
88
+ Args:
89
+ funcs (Union[FunctionTool, List[FunctionTool]]): The function or
90
+ list of functions to add.
91
+ entrypoint (str): The entrypoint for the function.
92
+ redirect_stdout (bool): Whether to return the stdout of
93
+ the function. (default::obj: `False`)
94
+ arguments (Optional[Dict[str, Any]]): The arguments for the
95
+ function. (default::obj: `None`)
96
+
97
+ Returns:
98
+ RemoteHttpRuntime: The current runtime.
99
+ """
100
+ if not isinstance(funcs, list):
101
+ funcs = [funcs]
102
+ if arguments is not None:
103
+ entrypoint += json.dumps(arguments)
104
+
105
+ for func in funcs:
106
+ inner_func = func.func
107
+
108
+ # Create a wrapper that explicitly binds `func`
109
+ @wraps(inner_func)
110
+ def wrapper(
111
+ *args, func=func, redirect_stdout=redirect_stdout, **kwargs
112
+ ):
113
+ for key, value in kwargs.items():
114
+ if isinstance(value, BaseModel):
115
+ kwargs[key] = value.model_dump()
116
+
117
+ resp = requests.post(
118
+ f"http://{self.host}:{self.port}/{func.get_function_name()}",
119
+ json=dict(
120
+ args=args,
121
+ kwargs=kwargs,
122
+ redirect_stdout=redirect_stdout,
123
+ ),
124
+ )
125
+ if resp.status_code != 200:
126
+ logger.error(
127
+ f"""ailed to execute function:
128
+ {func.get_function_name()},
129
+ status code: {resp.status_code},
130
+ response: {resp.text}"""
131
+ )
132
+ return {
133
+ "error": f"""Failed to execute function:
134
+ {func.get_function_name()},
135
+ response: {resp.text}"""
136
+ }
137
+ data = resp.json()
138
+ if redirect_stdout:
139
+ print(data["stdout"])
140
+ return json.loads(data["output"])
141
+
142
+ func.func = wrapper
143
+ self.tools_map[func.get_function_name()] = func
144
+ self.entrypoint[func.get_function_name()] = entrypoint
145
+
146
+ return self
147
+
148
+ @property
149
+ def ok(self) -> bool:
150
+ r"""Check if the API Server is running.
151
+
152
+ Returns:
153
+ bool: Whether the API Server is running.
154
+ """
155
+ try:
156
+ _ = requests.get(f"http://{self.host}:{self.port}")
157
+ return True
158
+ except requests.exceptions.ConnectionError:
159
+ return False
160
+
161
+ def wait(self, timeout: int = 10) -> bool:
162
+ r"""Wait for the API Server to be ready.
163
+
164
+ Args:
165
+ timeout (int): The number of seconds to wait. (default::obj: `10`)
166
+
167
+ Returns:
168
+ bool: Whether the API Server is ready.
169
+ """
170
+ for _ in range(timeout):
171
+ if self.ok:
172
+ return True
173
+ time.sleep(1)
174
+ return False
175
+
176
+ def __del__(self):
177
+ r"""Clean up the API server when the object is deleted."""
178
+ self._cleanup()
179
+
180
+ def stop(self) -> "RemoteHttpRuntime":
181
+ r"""Stop the API server.
182
+
183
+ Returns:
184
+ RemoteHttpRuntime: The current runtime.
185
+ """
186
+ self._cleanup()
187
+ return self
188
+
189
+ def reset(self) -> "RemoteHttpRuntime":
190
+ r"""Reset the API server.
191
+
192
+ Returns:
193
+ RemoteHttpRuntime: The current runtime.
194
+ """
195
+ return self.stop().build()
196
+
197
+ @property
198
+ def docs(self) -> str:
199
+ r"""Get the URL for the API documentation.
200
+
201
+ Returns:
202
+ str: The URL for the API documentation.
203
+ """
204
+ return f"http://{self.host}:{self.port}/docs"
@@ -0,0 +1,20 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ from .function_risk_toolkit import FunctionRiskToolkit
15
+ from .ignore_risk_toolkit import IgnoreRiskToolkit
16
+
17
+ __all__ = [
18
+ "FunctionRiskToolkit",
19
+ "IgnoreRiskToolkit",
20
+ ]
@@ -0,0 +1,58 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ from typing import List, Optional
15
+
16
+ from camel.toolkits import FunctionTool
17
+ from camel.toolkits.base import BaseToolkit
18
+
19
+
20
+ class FunctionRiskToolkit(BaseToolkit):
21
+ r"""A toolkit for assessing the risk associated with functions.
22
+
23
+ Args:
24
+ verbose (Optional[bool]): Whether to print verbose output.
25
+ (default::obj:`False`)
26
+ """
27
+
28
+ def __init__(self, verbose: Optional[bool] = False):
29
+ self.verbose = verbose
30
+
31
+ def function_risk(self, score: int, reason: str):
32
+ r"""Provides an assessment of the potential risk associated
33
+ with a function.
34
+
35
+ Args:
36
+ score (int): The risk level associated with the function,
37
+ ranging from 1 to 3:
38
+ - 1: No harm
39
+ (e.g., simple math operations, content searches)
40
+ - 2: Minimal harm (e.g., accessing user files)
41
+ - 3: Risk present
42
+ (e.g., deleting files, modifying the file system)
43
+ reason (str): A brief explanation of the reasoning behind
44
+ the assigned score, describing the specific aspects that
45
+ contribute to the assessed risk.
46
+ """
47
+ if self.verbose:
48
+ print(f"Function risk assessment: {reason} (score: {score})")
49
+
50
+ def get_tools(self) -> List[FunctionTool]:
51
+ r"""Returns a list of FunctionTool objects representing the
52
+ functions in the toolkit.
53
+
54
+ Returns:
55
+ List[FunctionTool]: A list of FunctionTool objects
56
+ representing the functions in the toolkit.
57
+ """
58
+ return [FunctionTool(self.function_risk)]
@@ -0,0 +1,72 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+ from typing import Dict, List, Optional
15
+
16
+ from camel.toolkits import FunctionTool
17
+ from camel.toolkits.base import BaseToolkit
18
+
19
+
20
+ class IgnoreRiskToolkit(BaseToolkit):
21
+ r"""A toolkit for ignoring risks associated with functions.
22
+
23
+ Args:
24
+ function_names (Optional[List[str]]): A list of function names to
25
+ ignore risks for. (default::obj:`None`)
26
+ verbose (Optional[bool]): Whether to print verbose output.
27
+ (default::obj:`False`)
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ function_name: Optional[List[str]] = None,
33
+ verbose: Optional[bool] = False,
34
+ ):
35
+ self.verbose = verbose
36
+ self.function_names = function_name or []
37
+ self.ignored_risks: Dict[str, str] = dict()
38
+
39
+ def add(self, name: str):
40
+ r"""Adds a function to the toolkit.
41
+
42
+ Args:
43
+ name (str): The name of the function to add.
44
+ """
45
+ self.function_names.append(name)
46
+
47
+ def ignore_risk(self, name: str, reason: str) -> str:
48
+ r"""Force ignores the risk associated with named function. This ONLY
49
+ ignores the RISK for the NEXT Function Call.
50
+
51
+ Args:
52
+ name (str): The name of the function to ignore.
53
+ reason (str): A brief explanation of the reasoning
54
+ behind the decision to ignore the risk.
55
+ """
56
+ if name not in self.function_names:
57
+ raise ValueError(f"Function {name} not found in the toolkit.")
58
+
59
+ self.ignored_risks[name] = reason
60
+ if self.verbose:
61
+ print(f"Ignoring risk for function {name}: {reason}")
62
+ return f"Ignored risk for function {name}!"
63
+
64
+ def get_tools(self) -> List[FunctionTool]:
65
+ r"""Returns a list of FunctionTool objects representing the
66
+ functions in the toolkit.
67
+
68
+ Returns:
69
+ List[FunctionTool]: A list of FunctionTool objects representing
70
+ the functions in the toolkit.
71
+ """
72
+ return [FunctionTool(self.ignore_risk)]
@@ -0,0 +1,17 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+
15
+ from .openai_converter import OpenAISchemaConverter
16
+
17
+ __all__ = ["OpenAISchemaConverter"]
camel/schemas/base.py ADDED
@@ -0,0 +1,45 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+
15
+ from abc import ABC, abstractmethod
16
+ from typing import Any, Dict
17
+
18
+ from pydantic import BaseModel
19
+
20
+
21
+ class BaseConverter(ABC):
22
+ r"""A base class for schema outputs that includes functionality
23
+ for managing the response format.
24
+
25
+ Args:
26
+ output_schema (Optional[Type[BaseModel]], optional): The expected
27
+ format of the response. (default: :obj:`None`)
28
+ """
29
+
30
+ @abstractmethod
31
+ def convert(
32
+ self, content: str, *args: Any, **kwargs: Dict[str, Any]
33
+ ) -> BaseModel:
34
+ r"""Structures the input text into the expected response format.
35
+
36
+ Args:
37
+ text (str): The input text to be structured.
38
+ output_schema (Optional[Type[BaseModel]], optional):
39
+ The expected format of the response. Defaults to None.
40
+ prompt (Optional[str], optional): The prompt to be used.
41
+
42
+ Returns:
43
+ Optional[BaseModel]: The structured response.
44
+ """
45
+ pass
@@ -0,0 +1,116 @@
1
+ # ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
+
15
+ import os
16
+ from typing import Any, Callable, Dict, Optional, Type, Union
17
+
18
+ from pydantic import BaseModel
19
+
20
+ from camel.models import ModelFactory
21
+ from camel.types import ModelType
22
+ from camel.types.enums import ModelPlatformType
23
+ from camel.utils import (
24
+ api_keys_required,
25
+ get_pydantic_model,
26
+ )
27
+
28
+ from .base import BaseConverter
29
+
30
+ DEFAULT_CONVERTER_PROMPTS = """
31
+ Extract key entities and attributes from the provided text,
32
+ and convert them into a structured JSON format.
33
+ """
34
+
35
+
36
+ class OpenAISchemaConverter(BaseConverter):
37
+ r"""OpenAISchemaConverter is a class that converts a string or a function
38
+ into a BaseModel schema.
39
+
40
+ Args:
41
+ model_type (ModelType, optional): The model type to be used.
42
+ (default: ModelType.GPT_4O_MINI)
43
+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary
44
+ that will be fed into:obj:`openai.ChatCompletion.create()`. If
45
+ :obj:`None`, :obj:`ChatGPTConfig().as_dict()` will be used.
46
+ (default: :obj:`None`)
47
+ api_key (Optional[str], optional): The API key for authenticating
48
+ with the OpenAI service. (default: :obj:`None`)
49
+ output_schema (Optional[Type[BaseModel]], optional): The expected
50
+ format of the response. (default: :obj:`None`)
51
+ prompt (Optional[str], optional): The prompt to be used.
52
+ (default: :obj:`None`)
53
+
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ model_type: ModelType = ModelType.GPT_4O_MINI,
59
+ model_config_dict: Optional[Dict[str, Any]] = None,
60
+ api_key: Optional[str] = None,
61
+ ):
62
+ self.model_type = model_type
63
+ self.model_config_dict = model_config_dict or {}
64
+ api_key = api_key or os.environ.get("OPENAI_API_KEY")
65
+ self._client = ModelFactory.create( # type: ignore[attr-defined]
66
+ ModelPlatformType.OPENAI,
67
+ model_type,
68
+ api_key=api_key,
69
+ )._client
70
+ super().__init__()
71
+
72
+ @api_keys_required("OPENAI_API_KEY")
73
+ def convert( # type: ignore[override]
74
+ self,
75
+ content: str,
76
+ output_schema: Union[Type[BaseModel], str, Callable],
77
+ prompt: Optional[str] = DEFAULT_CONVERTER_PROMPTS,
78
+ ) -> BaseModel:
79
+ r"""Formats the input content into the expected BaseModel
80
+
81
+ Args:
82
+ content (str): The content to be formatted.
83
+ output_schema (Union[Type[BaseModel], str, Callable]): The expected
84
+ format of the response.
85
+
86
+ Returns:
87
+ BaseModel: The formatted response.
88
+ """
89
+ prompt = prompt or DEFAULT_CONVERTER_PROMPTS
90
+ if output_schema is None:
91
+ raise ValueError("Expected an output schema, got None.")
92
+ if not isinstance(output_schema, type):
93
+ output_schema = get_pydantic_model(output_schema)
94
+ elif not issubclass(output_schema, BaseModel):
95
+ raise ValueError(
96
+ f"Expected a BaseModel, got {type(output_schema)}"
97
+ )
98
+
99
+ self.model_config_dict["response_format"] = output_schema
100
+ response = self._client.beta.chat.completions.parse(
101
+ messages=[
102
+ {'role': 'system', 'content': prompt},
103
+ {'role': 'user', 'content': content},
104
+ ],
105
+ model=self.model_type,
106
+ **self.model_config_dict,
107
+ )
108
+
109
+ message = response.choices[0].message
110
+
111
+ if not isinstance(message.parsed, output_schema):
112
+ raise ValueError(
113
+ f"Expected a {output_schema}, got {type(message.parsed)}."
114
+ )
115
+
116
+ return message.parsed
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  from .babyagi_playing import BabyAGI
15
15
  from .role_playing import RolePlaying
16
16
 
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  from collections import deque
15
15
  from typing import Dict, List, Optional
16
16
 
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  import logging
15
15
  from typing import Dict, List, Optional, Sequence, Tuple, Union
16
16
 
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
 
15
15
  from .role_playing_worker import RolePlayingWorker
16
16
  from .single_agent_worker import SingleAgentWorker
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  from abc import ABC, abstractmethod
15
15
  from typing import Any
16
16
 
@@ -1,16 +1,16 @@
1
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
2
- # Licensed under the Apache License, Version 2.0 (the License);
1
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
3
  # you may not use this file except in compliance with the License.
4
4
  # You may obtain a copy of the License at
5
5
  #
6
6
  # http://www.apache.org/licenses/LICENSE-2.0
7
7
  #
8
8
  # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an AS IS BASIS,
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
10
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  # See the License for the specific language governing permissions and
12
12
  # limitations under the License.
13
- # =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========
13
+ # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
  from camel.prompts import TextPrompt
15
15
 
16
16
  # ruff: noqa: E501