camel-ai 0.2.36__py3-none-any.whl → 0.2.38__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 (84) hide show
  1. camel/__init__.py +1 -1
  2. camel/agents/__init__.py +2 -0
  3. camel/agents/repo_agent.py +579 -0
  4. camel/configs/aiml_config.py +20 -19
  5. camel/configs/anthropic_config.py +25 -27
  6. camel/configs/cohere_config.py +11 -10
  7. camel/configs/deepseek_config.py +16 -16
  8. camel/configs/gemini_config.py +8 -8
  9. camel/configs/groq_config.py +18 -19
  10. camel/configs/internlm_config.py +8 -8
  11. camel/configs/litellm_config.py +26 -24
  12. camel/configs/mistral_config.py +8 -8
  13. camel/configs/moonshot_config.py +11 -11
  14. camel/configs/nvidia_config.py +13 -13
  15. camel/configs/ollama_config.py +14 -15
  16. camel/configs/openai_config.py +3 -3
  17. camel/configs/openrouter_config.py +9 -9
  18. camel/configs/qwen_config.py +8 -8
  19. camel/configs/reka_config.py +12 -11
  20. camel/configs/samba_config.py +14 -14
  21. camel/configs/sglang_config.py +15 -16
  22. camel/configs/siliconflow_config.py +18 -17
  23. camel/configs/togetherai_config.py +18 -19
  24. camel/configs/vllm_config.py +18 -19
  25. camel/configs/yi_config.py +7 -8
  26. camel/configs/zhipuai_config.py +8 -9
  27. camel/datagen/evol_instruct/__init__.py +20 -0
  28. camel/datagen/evol_instruct/evol_instruct.py +424 -0
  29. camel/datagen/evol_instruct/scorer.py +166 -0
  30. camel/datagen/evol_instruct/templates.py +268 -0
  31. camel/datasets/static_dataset.py +25 -23
  32. camel/environments/models.py +10 -1
  33. camel/environments/single_step.py +296 -136
  34. camel/extractors/__init__.py +16 -1
  35. camel/interpreters/docker_interpreter.py +1 -1
  36. camel/interpreters/e2b_interpreter.py +1 -1
  37. camel/interpreters/subprocess_interpreter.py +1 -1
  38. camel/loaders/__init__.py +2 -2
  39. camel/loaders/{panda_reader.py → pandas_reader.py} +61 -30
  40. camel/memories/context_creators/score_based.py +198 -67
  41. camel/models/aiml_model.py +9 -3
  42. camel/models/anthropic_model.py +11 -3
  43. camel/models/azure_openai_model.py +9 -3
  44. camel/models/base_audio_model.py +6 -0
  45. camel/models/base_model.py +4 -0
  46. camel/models/deepseek_model.py +9 -3
  47. camel/models/gemini_model.py +9 -3
  48. camel/models/groq_model.py +9 -3
  49. camel/models/internlm_model.py +8 -2
  50. camel/models/model_factory.py +4 -0
  51. camel/models/moonshot_model.py +8 -2
  52. camel/models/nemotron_model.py +9 -3
  53. camel/models/nvidia_model.py +9 -3
  54. camel/models/ollama_model.py +9 -3
  55. camel/models/openai_audio_models.py +5 -3
  56. camel/models/openai_compatible_model.py +9 -3
  57. camel/models/openai_model.py +9 -3
  58. camel/models/openrouter_model.py +9 -3
  59. camel/models/qwen_model.py +9 -3
  60. camel/models/samba_model.py +9 -3
  61. camel/models/sglang_model.py +11 -4
  62. camel/models/siliconflow_model.py +8 -2
  63. camel/models/stub_model.py +2 -1
  64. camel/models/togetherai_model.py +9 -3
  65. camel/models/vllm_model.py +9 -3
  66. camel/models/yi_model.py +9 -3
  67. camel/models/zhipuai_model.py +9 -3
  68. camel/retrievers/auto_retriever.py +14 -0
  69. camel/storages/__init__.py +2 -0
  70. camel/storages/vectordb_storages/__init__.py +2 -0
  71. camel/storages/vectordb_storages/tidb.py +332 -0
  72. camel/toolkits/__init__.py +7 -0
  73. camel/toolkits/browser_toolkit.py +84 -61
  74. camel/toolkits/openai_agent_toolkit.py +131 -0
  75. camel/toolkits/searxng_toolkit.py +207 -0
  76. camel/toolkits/thinking_toolkit.py +230 -0
  77. camel/types/enums.py +4 -0
  78. camel/utils/chunker/code_chunker.py +9 -15
  79. camel/verifiers/base.py +28 -5
  80. camel/verifiers/python_verifier.py +321 -68
  81. {camel_ai-0.2.36.dist-info → camel_ai-0.2.38.dist-info}/METADATA +103 -8
  82. {camel_ai-0.2.36.dist-info → camel_ai-0.2.38.dist-info}/RECORD +84 -75
  83. {camel_ai-0.2.36.dist-info → camel_ai-0.2.38.dist-info}/WHEEL +0 -0
  84. {camel_ai-0.2.36.dist-info → camel_ai-0.2.38.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,268 @@
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 dataclasses import dataclass
17
+ from typing import Dict, List, Union
18
+
19
+
20
+ # flake8: noqa
21
+ @dataclass(frozen=True)
22
+ class BaseEvolInstructTemplates(ABC):
23
+ r"""Abstract base class for evolution instruction templates.
24
+
25
+ This class defines a required structure for prompt transformation templates
26
+ - `EVOL_METHODS`: A dictionary mapping method keys to their descriptions.
27
+ - `STRATEGY`: A dictionary defining strategies and associated methods.
28
+
29
+ Subclasses should define concrete templates for specific domains.
30
+ """
31
+
32
+ @property
33
+ @abstractmethod
34
+ def EVOL_METHODS(self) -> Dict[str, str]:
35
+ r"""A dictionary mapping evolution method keys to their descriptions."""
36
+ pass
37
+
38
+ @property
39
+ @abstractmethod
40
+ def STRATEGY(self) -> Dict[str, Dict[str, Union[str, List[str]]]]:
41
+ r"""A dictionary defining strategies and their corresponding methods."""
42
+ pass
43
+
44
+
45
+ # flake8: noqa
46
+ @dataclass(frozen=True)
47
+ class EvolInstructTemplates(BaseEvolInstructTemplates):
48
+ r"""Contains templates for EvolInstruct prompt transformations.
49
+
50
+ References:
51
+ - WizardLM: Empowering Large Language Models to Follow Complex
52
+ Instructions
53
+ https://arxiv.org/pdf/2304.12244
54
+ - eva: Evolving Alignment via Asymmetric Self-Play
55
+ https://arxiv.org/abs/2411.00062
56
+ """
57
+
58
+ # High-level instructions on in-depth/in-breadth evolving
59
+ INST_IN_DEPTH = (
60
+ "Please act as an expert Prompt Creator.\n"
61
+ "Your objective is to rewrite a given prompt into a more complex "
62
+ "version to make those large language models (e.g., gemini) a bit "
63
+ "harder to handle.\n"
64
+ "But the rewritten prompt must be reasonable and must be understood "
65
+ "and responded by humans.\n"
66
+ "Your rewriting cannot omit the non-text parts such as the table and "
67
+ "code in #Given Prompt#, if there is any."
68
+ "You should try your best not to make the #Rewritten Prompt# become "
69
+ "verbose, "
70
+ "The #Rewritten Prompt# should be roughly the similar length or a "
71
+ "little bit more than that of #Given Prompt#.\n"
72
+ "The #Rewritten Prompt# must sound like a real human user's prompt; "
73
+ "DON'T make it like sound machine-generated."
74
+ "Specifically, you SHOULD complicate the given prompt using the "
75
+ "following method: "
76
+ "\n{method}\n"
77
+ "The rewritten prompt should reflect meaningful changes across its "
78
+ "structure, ensuring the entire sentence feels sufficiently different "
79
+ "from the original. "
80
+ "Again, make sure the rewritten prompt is more CHALLENGING."
81
+ "Respond with your rewritten prompt directly. "
82
+ "#Given Prompt#:\n{prompt}\n"
83
+ "#Rewritten Prompt#:\n"
84
+ ).lstrip()
85
+
86
+ INST_IN_BREADTH = (
87
+ "Please act as an expert Prompt Creator.\n"
88
+ "Your objective is to generate a brand-new prompt based on the #Given "
89
+ "Prompt#. "
90
+ "The purpose of this task is to promote diversity and generality of "
91
+ "training prompts for language models, helping it practice with "
92
+ "varied challenges and perspectives.\n"
93
+ "The LENGTH and complexity of the #Created Prompt# should be similar "
94
+ "to that of the #Given Prompt#.\n"
95
+ "The #Created Prompt# must be reasonable, interpretable, and solvable "
96
+ "by humans.\n"
97
+ "The #Created Prompt# must sound like a real human user's prompt; "
98
+ "DON'T make it sound like machine-generated."
99
+ "Follow the method described below to guide your creation:\n"
100
+ "{method}\n"
101
+ "The created prompt should reflect meaningful changes across its "
102
+ "structure, ensuring the entire sentence feels sufficiently different "
103
+ "from the original. "
104
+ "Respond with your created prompt directly.\n"
105
+ "#Given Prompt#:\n{prompt}\n"
106
+ "#Created Prompt#:\n"
107
+ ).lstrip()
108
+
109
+ # Sub-method instructions (following the eva paper setting)
110
+ IN_BREADTH_KEYS = [
111
+ 'persona',
112
+ 'shift-in',
113
+ 'shift-out',
114
+ 'mix',
115
+ 'abstract',
116
+ ]
117
+
118
+ IN_DEPTH_KEYS = [
119
+ 'constraints',
120
+ 'deepening',
121
+ 'concretizing',
122
+ 'reasoning',
123
+ 'expansion',
124
+ ]
125
+
126
+ STRATEGY = {
127
+ "IN-DEPTH": {
128
+ 'meta_instruction': INST_IN_DEPTH,
129
+ 'methods': IN_DEPTH_KEYS,
130
+ },
131
+ "IN-BREADTH": {
132
+ 'meta_instruction': INST_IN_BREADTH,
133
+ 'methods': IN_BREADTH_KEYS,
134
+ },
135
+ }
136
+
137
+ EVOL_METHODS = {
138
+ "persona": (
139
+ "Reframe the #Given Prompt# as if written by a user with a "
140
+ "completely different persona, background, or expertise. Adjust "
141
+ "the tone, style, phrasing, or anything you feel proper to "
142
+ "reflect this change. The changes should make the prompt feel "
143
+ "like it was authored by someone entirely new."
144
+ ),
145
+ "shift-in": (
146
+ "Shift the high-level idea of the #Given Prompt# to explore a "
147
+ "different subdomain or context within the same domain. Ensure "
148
+ "the new topic still challenges the model to reason or provide "
149
+ "knowledge relevant to the domain."
150
+ ),
151
+ "shift-out": (
152
+ "Shift the high-level idea of the #Given Prompt# to a completely "
153
+ "different topic in a different setting. The new topic may "
154
+ "challenge the model with similar reasoning or contextual "
155
+ "understanding but in a novel way."
156
+ ),
157
+ "mix": (
158
+ "Combine the high-level concept of the #Given Prompt# with "
159
+ "elements from a different domain. Introduce novel scenarios or "
160
+ "contexts to create diversity while maintaining relevance to the "
161
+ "original idea."
162
+ ),
163
+ "abstract": (
164
+ "Turn the #Given Prompt# into a more abstract or generalized "
165
+ "version, removing specific details while preserving its intent. "
166
+ "Ensure the new prompt encourages broader, principle-driven "
167
+ "reasoning."
168
+ ),
169
+ "constraints": (
170
+ "Add one or more significant constraints or requirements into the "
171
+ "'#Given Prompt#'. The added constraints must meaningfully alter "
172
+ "how the model would respond. For example, specify additional "
173
+ "rules, contexts, or limitations that demand creative adjustments."
174
+ ),
175
+ "deepening": (
176
+ "If the #Given Prompt# contains inquiries about certain issues, "
177
+ "increase the depth and breadth of the inquiry. Make the question "
178
+ "require a more detailed, multi-layered, or comprehensive response"
179
+ ". For instance, break the problem into sub-problems or require "
180
+ "connections between unrelated concepts."
181
+ ),
182
+ "concretizing": (
183
+ "Replace general concepts in the #Given Prompt# with more specific"
184
+ " and detailed concepts. Ensure that the change makes the problem "
185
+ "more defined and concrete, leaving less room for ambiguity. For "
186
+ "example, replace 'a device' with 'a wearable fitness tracker "
187
+ "with GPS'."
188
+ ),
189
+ "reasoning": (
190
+ "Add one or more reasoning steps into the '#Given Prompt#'. "
191
+ "Explicitly rewrite it to demand multi-step reasoning or justify "
192
+ "intermediate steps in the solution. For instance, if the original"
193
+ " prompt is a simple query, make the response require a "
194
+ "step-by-step breakdown of logic or calculations."
195
+ ),
196
+ "expansion": (
197
+ "Expand the #Given Prompt# by including additional perspectives, "
198
+ "domains, or layers of complexity. For example, if the original "
199
+ "prompt focuses on a single scenario, add related scenarios or ask"
200
+ " the model to compare different situations."
201
+ ),
202
+ }
203
+
204
+
205
+ # flake8: noqa
206
+ @dataclass(frozen=True)
207
+ class MathEvolInstructTemplates(BaseEvolInstructTemplates):
208
+ r"""Contains templates for MathEvolInstruct prompt transformations."""
209
+
210
+ # Meta-instructions for in-depth evolving
211
+ INST_IN_DEPTH = (
212
+ "Please act as a math expert. Your objective is to create a new math "
213
+ "problem that is more challenging yet concise than the given math "
214
+ "problem. Ensure that the mathematical content (including any "
215
+ "equations or figures) is preserved, and rephrase the problem to "
216
+ "increase its complexity and depth. The generated problem should be "
217
+ "clearly stated, strictly mathematical, and suitable for solving with "
218
+ "symbolic computation (e.g., using sympy). You will be given a method "
219
+ "to guide your creation. Make sure to follow the method strictly. "
220
+ "Consolidate any multiple parts into one integrated question that "
221
+ "ask for one definitive answer. Respond with your generated problem "
222
+ "directly. "
223
+ "#Original Problem#:\n{prompt}\n"
224
+ "#Generated Problem#:\n"
225
+ ).lstrip()
226
+
227
+ EVOL_METHODS = {
228
+ "constraints": (
229
+ "Add one or more significant constraints or requirements into the "
230
+ "'#Given Prompt#'. The added constraints must meaningfully alter "
231
+ "how the model would respond. For example, specify additional "
232
+ "rules, contexts, or limitations that demand creative adjustments."
233
+ ),
234
+ "deepening": (
235
+ "Increase the difficulty of the #Given Prompt# by integrating "
236
+ "additional layers of reasoning and rigor. Refine the problem so "
237
+ "that all added difficulty is consolidated into a single coherent "
238
+ "question requiring one final answer, avoiding fragmentation into "
239
+ "multiple sub-problems."
240
+ ),
241
+ "expansion": (
242
+ "Expand the #Given Prompt# by incorporating additional "
243
+ "perspectives or layers of complexity into the problem statement. "
244
+ "Ensure that the revised problem remains a single, unified "
245
+ "question with one final answer, rather than a series of separate "
246
+ "sub-questions."
247
+ ),
248
+ "condense": (
249
+ "Reformulate the given math problem into a well-structured and "
250
+ "formally stated mathematical question.\n"
251
+ "- Present the problem in a structured and rigorous mathematical "
252
+ "format.\n"
253
+ "- Removing unnecessary instructions, explanations, or hints.\n"
254
+ "- If the given problem contains several sub-questions, make "
255
+ "necessary changes to let the problem could be answered with one "
256
+ "number or expression by removing the sub-questions or combining "
257
+ "them into one."
258
+ ),
259
+ }
260
+
261
+ IN_DEPTH_KEYS = ['constraints', 'deepening', 'expansion']
262
+
263
+ STRATEGY = {
264
+ "IN-DEPTH": {
265
+ 'meta_instruction': INST_IN_DEPTH,
266
+ 'methods': IN_DEPTH_KEYS,
267
+ },
268
+ }
@@ -153,17 +153,6 @@ class StaticDataset(Dataset):
153
153
  return None
154
154
 
155
155
  rationale = item.get('rationale')
156
- if not isinstance(rationale, str):
157
- if self._strict:
158
- raise ValueError(
159
- f"Sample at index {idx} has invalid 'rationale': "
160
- f"expected str, got {type(rationale)}"
161
- )
162
- else:
163
- logger.warning(
164
- f"Skipping sample at index {idx}: invalid 'rationale'"
165
- )
166
- return None
167
156
 
168
157
  final_answer = item.get('final_answer')
169
158
  if not isinstance(final_answer, str):
@@ -207,25 +196,33 @@ class StaticDataset(Dataset):
207
196
  r"""Return the size of the dataset."""
208
197
  return self._length
209
198
 
210
- def __getitem__(self, idx: int) -> DataPoint:
211
- r"""Retrieve a datapoint by index.
199
+ def __getitem__(
200
+ self, idx: Union[int, slice]
201
+ ) -> Union[DataPoint, List[DataPoint]]:
202
+ r"""Retrieve a datapoint or a batch of datapoints by index or slice.
212
203
 
213
204
  Args:
214
- idx (int): Index of the datapoint.
205
+ idx (Union[int, slice]): Index or slice of the datapoint(s).
215
206
 
216
207
  Returns:
217
- DataPoint: The datapoint corresponding to the given index.
208
+ List[DataPoint]: A list of `DataPoint` objects.
218
209
 
219
210
  Raises:
220
- IndexError: If :obj:`idx` is out of bounds (negative or greater
221
- than dataset length - 1).
211
+ IndexError: If an integer `idx` is out of bounds.
222
212
  """
213
+ if isinstance(idx, int):
214
+ if idx < 0 or idx >= self._length:
215
+ raise IndexError(
216
+ f"Index {idx} out of bounds for dataset "
217
+ f"of size {self._length}"
218
+ )
219
+ return self.data[idx]
223
220
 
224
- if idx < 0 or idx >= self._length:
225
- raise IndexError(
226
- f"Index {idx} out of bounds for dataset of size {self._length}"
227
- )
228
- return self.data[idx]
221
+ elif isinstance(idx, slice):
222
+ return self.data[idx.start : idx.stop : idx.step]
223
+
224
+ else:
225
+ raise TypeError(f"Indexing type {type(idx)} not supported.")
229
226
 
230
227
  def sample(self) -> DataPoint:
231
228
  r"""Sample a random datapoint from the dataset.
@@ -240,7 +237,12 @@ class StaticDataset(Dataset):
240
237
  if self._length == 0:
241
238
  raise RuntimeError("Dataset is empty, cannot sample.")
242
239
  idx = self._rng.randint(0, self._length - 1)
243
- return self[idx]
240
+ sample = self[idx]
241
+ if not isinstance(sample, DataPoint):
242
+ raise TypeError(
243
+ f"Expected DataPoint instance, got {type(sample).__name__}"
244
+ )
245
+ return sample
244
246
 
245
247
  @property
246
248
  def metadata(self) -> Dict[str, Any]:
@@ -13,7 +13,7 @@
13
13
  # ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
14
14
 
15
15
  from datetime import datetime, timezone
16
- from typing import Any, Dict, Optional, Protocol
16
+ from typing import Any, Dict, Optional, Protocol, Tuple
17
17
 
18
18
  from pydantic import BaseModel, Field
19
19
 
@@ -33,6 +33,8 @@ class Action(BaseModel):
33
33
  generated (UTC).
34
34
  """
35
35
 
36
+ index: Optional[int] = Field(default=None, description="...")
37
+
36
38
  llm_response: str = Field(description="Generated response from the LLM")
37
39
  metadata: Dict[str, Any] = Field(
38
40
  default_factory=dict,
@@ -84,6 +86,13 @@ class StepResult(BaseModel):
84
86
  description="Additional information about the step",
85
87
  )
86
88
 
89
+ def as_tuple(
90
+ self,
91
+ ) -> Tuple[Observation, float, bool, Dict[str, Any]]:
92
+ r"""Returns all fields of the model as a tuple, in declaration order"""
93
+ self.info["rewards_dict"] = self.rewards_dict
94
+ return (self.observation, self.reward, self.done, self.info)
95
+
87
96
 
88
97
  class Environment(Protocol):
89
98
  async def reset(self) -> Observation: