camel-ai 0.2.34__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.

@@ -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
+ )
@@ -90,6 +90,30 @@ class BaseTokenCounter(ABC):
90
90
  """
91
91
  pass
92
92
 
93
+ @abstractmethod
94
+ def encode(self, text: str) -> List[int]:
95
+ r"""Encode text into token IDs.
96
+
97
+ Args:
98
+ text (str): The text to encode.
99
+
100
+ Returns:
101
+ List[int]: List of token IDs.
102
+ """
103
+ pass
104
+
105
+ @abstractmethod
106
+ def decode(self, token_ids: List[int]) -> str:
107
+ r"""Decode token IDs back to text.
108
+
109
+ Args:
110
+ token_ids (List[int]): List of token IDs to decode.
111
+
112
+ Returns:
113
+ str: Decoded text.
114
+ """
115
+ pass
116
+
93
117
 
94
118
  class OpenAITokenCounter(BaseTokenCounter):
95
119
  def __init__(self, model: UnifiedModelType):
@@ -227,6 +251,28 @@ class OpenAITokenCounter(BaseTokenCounter):
227
251
  total = EXTRA_TOKENS + SQUARE_TOKENS * h * w
228
252
  return total
229
253
 
254
+ def encode(self, text: str) -> List[int]:
255
+ r"""Encode text into token IDs.
256
+
257
+ Args:
258
+ text (str): The text to encode.
259
+
260
+ Returns:
261
+ List[int]: List of token IDs.
262
+ """
263
+ return self.encoding.encode(text, disallowed_special=())
264
+
265
+ def decode(self, token_ids: List[int]) -> str:
266
+ r"""Decode token IDs back to text.
267
+
268
+ Args:
269
+ token_ids (List[int]): List of token IDs to decode.
270
+
271
+ Returns:
272
+ str: Decoded text.
273
+ """
274
+ return self.encoding.decode(token_ids)
275
+
230
276
 
231
277
  class AnthropicTokenCounter(BaseTokenCounter):
232
278
  @dependencies_required('anthropic')
@@ -266,6 +312,33 @@ class AnthropicTokenCounter(BaseTokenCounter):
266
312
  model=self.model,
267
313
  ).input_tokens
268
314
 
315
+ def encode(self, text: str) -> List[int]:
316
+ r"""Encode text into token IDs.
317
+
318
+ Args:
319
+ text (str): The text to encode.
320
+
321
+ Returns:
322
+ List[int]: List of token IDs.
323
+ """
324
+ raise NotImplementedError(
325
+ "The Anthropic API does not provide direct access to token IDs. "
326
+ "Use count_tokens_from_messages() for token counting instead."
327
+ )
328
+
329
+ def decode(self, token_ids: List[int]) -> str:
330
+ r"""Decode token IDs back to text.
331
+
332
+ Args:
333
+ token_ids (List[int]): List of token IDs to decode.
334
+
335
+ Returns:
336
+ str: Decoded text.
337
+ """
338
+ raise NotImplementedError(
339
+ "The Anthropic API does not provide functionality to decode token IDs."
340
+ )
341
+
269
342
 
270
343
  class LiteLLMTokenCounter(BaseTokenCounter):
271
344
  def __init__(self, model_type: UnifiedModelType):
@@ -319,6 +392,32 @@ class LiteLLMTokenCounter(BaseTokenCounter):
319
392
  """
320
393
  return self.completion_cost(completion_response=response)
321
394
 
395
+ def encode(self, text: str) -> List[int]:
396
+ r"""Encode text into token IDs.
397
+
398
+ Args:
399
+ text (str): The text to encode.
400
+
401
+ Returns:
402
+ List[int]: List of token IDs.
403
+ """
404
+ from litellm import encoding
405
+
406
+ return encoding.encode(text, disallowed_special=())
407
+
408
+ def decode(self, token_ids: List[int]) -> str:
409
+ r"""Decode token IDs back to text.
410
+
411
+ Args:
412
+ token_ids (List[int]): List of token IDs to decode.
413
+
414
+ Returns:
415
+ str: Decoded text.
416
+ """
417
+ from litellm import encoding
418
+
419
+ return encoding.decode(token_ids)
420
+
322
421
 
323
422
  class MistralTokenCounter(BaseTokenCounter):
324
423
  def __init__(self, model_type: ModelType):
@@ -390,3 +489,37 @@ class MistralTokenCounter(BaseTokenCounter):
390
489
  )
391
490
 
392
491
  return mistral_request
492
+
493
+ def encode(self, text: str) -> List[int]:
494
+ r"""Encode text into token IDs.
495
+
496
+ Args:
497
+ text (str): The text to encode.
498
+
499
+ Returns:
500
+ List[int]: List of token IDs.
501
+ """
502
+ # Use the Mistral tokenizer to encode the text
503
+ return self.tokenizer.encode_chat_completion(
504
+ ChatCompletionRequest(
505
+ model=self.model_type,
506
+ messages=[
507
+ {
508
+ "role": "user",
509
+ "content": text,
510
+ }
511
+ ],
512
+ )
513
+ )
514
+
515
+ def decode(self, token_ids: List[int]) -> str:
516
+ r"""Decode token IDs back to text.
517
+
518
+ Args:
519
+ token_ids (List[int]): List of token IDs to decode.
520
+
521
+ Returns:
522
+ str: Decoded text.
523
+ """
524
+ # Use the Mistral tokenizer to decode the tokens
525
+ return self.tokenizer.decode(token_ids)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: camel-ai
3
- Version: 0.2.34
3
+ Version: 0.2.35
4
4
  Summary: Communicative Agents for AI Society Study
5
5
  Project-URL: Homepage, https://www.camel-ai.org/
6
6
  Project-URL: Repository, https://github.com/camel-ai/camel