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

@@ -26,7 +26,7 @@ from camel.types import (
26
26
  )
27
27
 
28
28
 
29
- class _CamelJSONEncoder(json.JSONEncoder):
29
+ class CamelJSONEncoder(json.JSONEncoder):
30
30
  r"""A custom JSON encoder for serializing specifically enumerated types.
31
31
  Ensures enumerated types can be stored in and retrieved from JSON format.
32
32
  """
@@ -62,7 +62,7 @@ class JsonStorage(BaseKeyValueStorage):
62
62
  def _json_object_hook(self, d) -> Any:
63
63
  if "__enum__" in d:
64
64
  name, member = d["__enum__"].split(".")
65
- return getattr(_CamelJSONEncoder.CAMEL_ENUMS[name], member)
65
+ return getattr(CamelJSONEncoder.CAMEL_ENUMS[name], member)
66
66
  else:
67
67
  return d
68
68
 
@@ -75,11 +75,7 @@ class JsonStorage(BaseKeyValueStorage):
75
75
  """
76
76
  with self.json_path.open("a") as f:
77
77
  f.writelines(
78
- [
79
- json.dumps(r, cls=_CamelJSONEncoder, ensure_ascii=False)
80
- + "\n"
81
- for r in records
82
- ]
78
+ [json.dumps(r, cls=CamelJSONEncoder) + "\n" for r in records]
83
79
  )
84
80
 
85
81
  def load(self) -> List[Dict[str, Any]]:
@@ -87,7 +87,11 @@ class VectorDBQueryResult(BaseModel):
87
87
  ) -> "VectorDBQueryResult":
88
88
  r"""A class method to construct a `VectorDBQueryResult` instance."""
89
89
  return cls(
90
- record=VectorRecord(vector=vector, id=id, payload=payload),
90
+ record=VectorRecord(
91
+ vector=vector,
92
+ id=id,
93
+ payload=payload,
94
+ ),
91
95
  similarity=similarity,
92
96
  )
93
97
 
@@ -50,6 +50,7 @@ from .semantic_scholar_toolkit import SemanticScholarToolkit
50
50
  from .zapier_toolkit import ZapierToolkit
51
51
  from .sympy_toolkit import SymPyToolkit
52
52
  from .mineru_toolkit import MinerUToolkit
53
+ from .memory_toolkit import MemoryToolkit
53
54
  from .audio_analysis_toolkit import AudioAnalysisToolkit
54
55
  from .excel_toolkit import ExcelToolkit
55
56
  from .video_analysis_toolkit import VideoAnalysisToolkit
@@ -60,7 +61,6 @@ from .file_write_toolkit import FileWriteToolkit
60
61
  from .terminal_toolkit import TerminalToolkit
61
62
  from .pubmed_toolkit import PubMedToolkit
62
63
 
63
-
64
64
  __all__ = [
65
65
  'BaseToolkit',
66
66
  'FunctionTool',
@@ -97,6 +97,7 @@ __all__ = [
97
97
  'ZapierToolkit',
98
98
  'SymPyToolkit',
99
99
  'MinerUToolkit',
100
+ 'MemoryToolkit',
100
101
  'MCPToolkit',
101
102
  'MCPToolkitManager',
102
103
  'AudioAnalysisToolkit',
@@ -13,6 +13,7 @@
13
13
  # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
 
15
15
 
16
+ import re
16
17
  from datetime import datetime
17
18
  from pathlib import Path
18
19
  from typing import List, Optional, Union
@@ -69,17 +70,22 @@ class FileWriteToolkit(BaseToolkit):
69
70
  r"""Convert the given string path to a Path object.
70
71
 
71
72
  If the provided path is not absolute, it is made relative to the
72
- default output directory.
73
+ default output directory. The filename part is sanitized to replace
74
+ spaces and special characters with underscores, ensuring safe usage
75
+ in downstream processing.
73
76
 
74
77
  Args:
75
78
  file_path (str): The file path to resolve.
76
79
 
77
80
  Returns:
78
- Path: A fully resolved (absolute) Path object.
81
+ Path: A fully resolved (absolute) and sanitized Path object.
79
82
  """
80
83
  path_obj = Path(file_path)
81
84
  if not path_obj.is_absolute():
82
85
  path_obj = self.output_dir / path_obj
86
+
87
+ sanitized_filename = self._sanitize_filename(path_obj.name)
88
+ path_obj = path_obj.parent / sanitized_filename
83
89
  return path_obj.resolve()
84
90
 
85
91
  def _write_text_file(
@@ -369,3 +375,19 @@ class FileWriteToolkit(BaseToolkit):
369
375
  return [
370
376
  FunctionTool(self.write_to_file),
371
377
  ]
378
+
379
+ def _sanitize_filename(self, filename: str) -> str:
380
+ r"""Sanitize a filename by replacing any character that is not
381
+ alphanumeric, a dot (.), hyphen (-), or underscore (_) with an
382
+ underscore (_).
383
+
384
+ Args:
385
+ filename (str): The original filename which may contain spaces or
386
+ special characters.
387
+
388
+ Returns:
389
+ str: The sanitized filename with disallowed characters replaced by
390
+ underscores.
391
+ """
392
+ safe = re.sub(r'[^\w\-.]', '_', filename)
393
+ return safe
@@ -110,9 +110,21 @@ class GithubToolkit(BaseToolkit):
110
110
  successfully or not.
111
111
  """
112
112
  sb = self.repo.get_branch(self.repo.default_branch)
113
- self.repo.create_git_ref(
114
- ref=f"refs/heads/{branch_name}", sha=sb.commit.sha
115
- )
113
+ from github import GithubException
114
+
115
+ try:
116
+ self.repo.create_git_ref(
117
+ ref=f"refs/heads/{branch_name}", sha=sb.commit.sha
118
+ )
119
+ except GithubException as e:
120
+ if e.message == "Reference already exists":
121
+ # agent might have pushed the branch separately.
122
+ logger.warning(
123
+ f"Branch {branch_name} already exists. "
124
+ "Continuing with the existing branch."
125
+ )
126
+ else:
127
+ raise
116
128
 
117
129
  file = self.repo.get_contents(file_path)
118
130
 
@@ -0,0 +1,129 @@
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 json
15
+ from typing import TYPE_CHECKING, Optional
16
+
17
+ from camel.memories import (
18
+ ChatHistoryMemory,
19
+ MemoryRecord,
20
+ ScoreBasedContextCreator,
21
+ )
22
+ from camel.toolkits.base import BaseToolkit
23
+ from camel.toolkits.function_tool import FunctionTool
24
+
25
+ if TYPE_CHECKING:
26
+ from camel.agents import ChatAgent
27
+
28
+
29
+ class MemoryToolkit(BaseToolkit):
30
+ r"""A toolkit that provides methods for saving, loading, and clearing a
31
+ ChatAgent's memory.
32
+ These methods are exposed as FunctionTool objects for
33
+ function calling. Internally, it calls:
34
+ - agent.save_memory(path)
35
+ - agent.load_memory(new_memory_obj)
36
+ - agent.load_memory_from_path(path)
37
+ - agent.clear_memory()
38
+
39
+ Args:
40
+ agent (ChatAgent): The chat agent whose memory will be managed.
41
+ timeout (Optional[float], optional): Maximum execution time allowed for
42
+ toolkit operations in seconds. If None, no timeout is applied.
43
+ (default: :obj:`None`)
44
+ """
45
+
46
+ def __init__(self, agent: 'ChatAgent', timeout: Optional[float] = None):
47
+ super().__init__(timeout=timeout)
48
+ self.agent = agent
49
+
50
+ def save(self, path: str) -> str:
51
+ r"""Saves the agent's current memory to a JSON file.
52
+
53
+ Args:
54
+ path (str): The file path to save the memory to.
55
+
56
+ Returns:
57
+ str: Confirmation message.
58
+ """
59
+ self.agent.save_memory(path)
60
+ return f"Memory saved to {path}"
61
+
62
+ def load(self, memory_json: str) -> str:
63
+ r"""Loads memory into the agent from a JSON string.
64
+
65
+ Args:
66
+ memory_json (str): A JSON string containing memory records.
67
+
68
+ Returns:
69
+ str: Confirmation or error message.
70
+ """
71
+ try:
72
+ data = json.loads(memory_json.strip())
73
+ if not isinstance(data, list):
74
+ return "[ERROR] Memory data should be a list of records."
75
+
76
+ # Build a fresh ChatHistoryMemory
77
+ context_creator = ScoreBasedContextCreator(
78
+ token_counter=self.agent.model_backend.token_counter,
79
+ token_limit=self.agent.model_backend.token_limit,
80
+ )
81
+ new_memory = ChatHistoryMemory(context_creator)
82
+
83
+ # Convert each record dict -> MemoryRecord
84
+ for record_dict in data:
85
+ record = MemoryRecord.from_dict(record_dict)
86
+ new_memory.write_record(record)
87
+
88
+ # Load into the agent
89
+ self.agent.load_memory(new_memory)
90
+ return "Loaded memory from provided JSON string."
91
+ except json.JSONDecodeError:
92
+ return "[ERROR] Invalid JSON string provided."
93
+ except Exception as e:
94
+ return f"[ERROR] Failed to load memory: {e!s}"
95
+
96
+ def load_from_path(self, path: str) -> str:
97
+ r"""Loads the agent's memory from a JSON file.
98
+
99
+ Args:
100
+ path (str): The file path to load the memory from.
101
+
102
+ Returns:
103
+ str: Confirmation message.
104
+ """
105
+ self.agent.load_memory_from_path(path)
106
+ return f"Memory loaded from {path}"
107
+
108
+ def clear_memory(self) -> str:
109
+ r"""Clears the agent's memory.
110
+
111
+ Returns:
112
+ str: Confirmation message.
113
+ """
114
+ self.agent.clear_memory()
115
+ return "Memory has been cleared."
116
+
117
+ def get_tools(self) -> list[FunctionTool]:
118
+ r"""Expose the memory management methods as function tools
119
+ for the ChatAgent.
120
+
121
+ Returns:
122
+ list[FunctionTool]: List of FunctionTool objects.
123
+ """
124
+ return [
125
+ FunctionTool(self.save),
126
+ FunctionTool(self.load),
127
+ FunctionTool(self.load_from_path),
128
+ FunctionTool(self.clear_memory),
129
+ ]
@@ -0,0 +1,22 @@
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 .base import BaseChunker
15
+ from .code_chunker import CodeChunker
16
+ from .uio_chunker import UnstructuredIOChunker
17
+
18
+ __all__ = [
19
+ "BaseChunker",
20
+ "CodeChunker",
21
+ "UnstructuredIOChunker",
22
+ ]
@@ -0,0 +1,24 @@
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 abc import ABC, abstractmethod
15
+ from typing import Any
16
+
17
+
18
+ class BaseChunker(ABC):
19
+ r"""An abstract base class for all CAMEL chunkers."""
20
+
21
+ @abstractmethod
22
+ def chunk(self, content: Any) -> Any:
23
+ r"""Chunk the given content"""
24
+ pass
@@ -0,0 +1,193 @@
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 re
15
+ from typing import List, Optional
16
+
17
+ from unstructured.documents.elements import Element, ElementMetadata
18
+
19
+ from camel.messages import OpenAIUserMessage
20
+ from camel.types import ModelType
21
+ from camel.utils import BaseTokenCounter, OpenAITokenCounter
22
+
23
+ from .base import BaseChunker
24
+
25
+
26
+ class CodeChunker(BaseChunker):
27
+ r"""A class for chunking code or text while respecting structure
28
+ and token limits.
29
+
30
+ This class ensures that structured elements such as functions,
31
+ classes, and regions are not arbitrarily split across chunks.
32
+ It also handles oversized lines and Base64-encoded images.
33
+
34
+ Attributes:
35
+ chunk_size (int, optional): The maximum token size per chunk.
36
+ (default: :obj:`8192`)
37
+ token_counter (BaseTokenCounter, optional): The tokenizer used for
38
+ token counting, if `None`, OpenAITokenCounter will be used.
39
+ (default: :obj:`None`)
40
+ remove_image: (bool, optional): If the chunker should skip the images.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ chunk_size: int = 8192,
46
+ token_counter: Optional[BaseTokenCounter] = None,
47
+ remove_image: Optional[bool] = True,
48
+ ):
49
+ self.chunk_size = chunk_size
50
+ self.token_counter = (
51
+ token_counter
52
+ if token_counter
53
+ else OpenAITokenCounter(model=ModelType.GPT_4O_MINI)
54
+ )
55
+ self.remove_image = remove_image
56
+ self.struct_pattern = re.compile(
57
+ r'^\s*(?:(def|class|function)\s+\w+|'
58
+ r'(public|private|protected)\s+[\w<>]+\s+\w+\s*\(|'
59
+ r'\b(interface|enum|namespace)\s+\w+|'
60
+ r'#\s*(region|endregion)\b)'
61
+ )
62
+ self.image_pattern = re.compile(
63
+ r'!\[.*?\]\((?:data:image/[^;]+;base64,[a-zA-Z0-9+/]+=*|[^)]+)\)'
64
+ )
65
+
66
+ def count_tokens(self, text: str):
67
+ r"""Counts the number of tokens in the given text.
68
+
69
+ Args:
70
+ text (str): The input text to be tokenized.
71
+
72
+ Returns:
73
+ int: The number of tokens in the input text.
74
+ """
75
+ return self.token_counter.count_tokens_from_messages(
76
+ [OpenAIUserMessage(role="user", name="user", content=text)]
77
+ )
78
+
79
+ def _split_oversized(self, line: str) -> List[str]:
80
+ r"""Splits an oversized line into multiple chunks based on token limits
81
+
82
+ Args:
83
+ line (str): The oversized line to be split.
84
+
85
+ Returns:
86
+ List[str]: A list of smaller chunks after splitting the
87
+ oversized line.
88
+ """
89
+ tokens = self.token_counter.encode(line)
90
+ chunks = []
91
+ buffer = []
92
+ current_count = 0
93
+
94
+ for token in tokens:
95
+ buffer.append(token)
96
+ current_count += 1
97
+
98
+ if current_count >= self.chunk_size:
99
+ chunks.append(self.token_counter.decode(buffer).strip())
100
+ buffer = []
101
+ current_count = 0
102
+
103
+ if buffer:
104
+ chunks.append(self.token_counter.decode(buffer))
105
+ return chunks
106
+
107
+ def chunk(self, content: List[str]) -> List[Element]:
108
+ r"""Splits the content into smaller chunks while preserving
109
+ structure and adhering to token constraints.
110
+
111
+ Args:
112
+ content (List[str]): The content to be chunked.
113
+
114
+ Returns:
115
+ List[str]: A list of chunked text segments.
116
+ """
117
+ content_str = "\n".join(map(str, content))
118
+ chunks = []
119
+ current_chunk: list[str] = []
120
+ current_tokens = 0
121
+ struct_buffer: list[str] = []
122
+ struct_tokens = 0
123
+
124
+ for line in content_str.splitlines(keepends=True):
125
+ if self.remove_image:
126
+ if self.image_pattern.match(line):
127
+ continue
128
+
129
+ line_tokens = self.count_tokens(line)
130
+
131
+ if line_tokens > self.chunk_size:
132
+ if current_chunk:
133
+ chunks.append("".join(current_chunk))
134
+ current_chunk = []
135
+ current_tokens = 0
136
+ chunks.extend(self._split_oversized(line))
137
+ continue
138
+
139
+ if self.struct_pattern.match(line):
140
+ if struct_buffer:
141
+ if current_tokens + struct_tokens <= self.chunk_size:
142
+ current_chunk.extend(struct_buffer)
143
+ current_tokens += struct_tokens
144
+ else:
145
+ if current_chunk:
146
+ chunks.append("".join(current_chunk))
147
+ current_chunk = struct_buffer.copy()
148
+ current_tokens = struct_tokens
149
+ struct_buffer = []
150
+ struct_tokens = 0
151
+
152
+ struct_buffer.append(line)
153
+ struct_tokens += line_tokens
154
+ else:
155
+ if struct_buffer:
156
+ struct_buffer.append(line)
157
+ struct_tokens += line_tokens
158
+ else:
159
+ if current_tokens + line_tokens > self.chunk_size:
160
+ chunks.append("".join(current_chunk))
161
+ current_chunk = [line]
162
+ current_tokens = line_tokens
163
+ else:
164
+ current_chunk.append(line)
165
+ current_tokens += line_tokens
166
+
167
+ if struct_buffer:
168
+ if current_tokens + struct_tokens <= self.chunk_size:
169
+ current_chunk.extend(struct_buffer)
170
+ else:
171
+ if current_chunk:
172
+ chunks.append("".join(current_chunk))
173
+ current_chunk = struct_buffer
174
+
175
+ if current_chunk:
176
+ chunks.append("".join(current_chunk))
177
+
178
+ final_chunks = []
179
+ for chunk in chunks:
180
+ chunk_token = self.count_tokens(chunk)
181
+ if chunk_token > self.chunk_size:
182
+ final_chunks.extend(self._split_oversized(chunk))
183
+ else:
184
+ final_chunks.append(chunk)
185
+
186
+ # TODO: need to reconsider how to correctly form metadata (maybe need
187
+ # to decouple the connection with unstructuredIO)
188
+ chunked_elements = []
189
+ for chunk in final_chunks:
190
+ element = Element(metadata=ElementMetadata())
191
+ element.text = chunk
192
+ chunked_elements.append(element)
193
+ return chunked_elements
@@ -0,0 +1,66 @@
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 unstructured.documents.elements import Element
17
+
18
+ from camel.loaders import UnstructuredIO
19
+ from camel.utils.chunker import BaseChunker
20
+
21
+
22
+ class UnstructuredIOChunker(BaseChunker):
23
+ r"""A class for chunking text while respecting structure and
24
+ character limits.
25
+
26
+ This class ensures that structured elements, such as document sections
27
+ and titles, are not arbitrarily split across chunks. It utilizes the
28
+ `UnstructuredIO` class to process and segment elements while maintaining
29
+ readability and coherence. The chunking method can be adjusted based on
30
+ the provided `chunk_type` parameter.
31
+
32
+ Args:
33
+ chunk_type (str, optional): The method used for chunking text.
34
+ (default: :obj:`"chunk_by_title"`)
35
+ max_characters (int, optional): The maximum number of characters
36
+ allowed per chunk. (default: :obj:`500`)
37
+ metadata_filename (Optional[str], optional): An optional filename
38
+ for storing metadata related to chunking. (default: :obj:`None`)
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ chunk_type: str = "chunk_by_title",
44
+ max_characters: int = 500,
45
+ metadata_filename: Optional[str] = None,
46
+ ):
47
+ self.uio = UnstructuredIO()
48
+ self.chunk_type = chunk_type
49
+ self.max_characters = max_characters
50
+ self.metadata_filename = metadata_filename
51
+
52
+ def chunk(self, content: List[Element]) -> List[Element]:
53
+ r"""Splits the content into smaller chunks while preserving
54
+ structure and adhering to token constraints.
55
+
56
+ Args:
57
+ content (List[Element]): The content to be chunked.
58
+
59
+ Returns:
60
+ List[Element]: A list of chunked text segments.
61
+ """
62
+ return self.uio.chunk_elements(
63
+ chunk_type=self.chunk_type,
64
+ elements=content,
65
+ max_characters=self.max_characters,
66
+ )