camel-ai 0.2.11__py3-none-any.whl → 0.2.12__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of camel-ai might be problematic. Click here for more details.
- camel/__init__.py +1 -1
- camel/agents/chat_agent.py +13 -1
- camel/benchmarks/__init__.py +18 -0
- camel/benchmarks/base.py +152 -0
- camel/benchmarks/gaia.py +478 -0
- camel/configs/__init__.py +3 -0
- camel/configs/ollama_config.py +4 -2
- camel/configs/sglang_config.py +71 -0
- camel/data_collector/__init__.py +19 -0
- camel/data_collector/alpaca_collector.py +127 -0
- camel/data_collector/base.py +211 -0
- camel/data_collector/sharegpt_collector.py +205 -0
- camel/datahubs/__init__.py +23 -0
- camel/datahubs/base.py +136 -0
- camel/datahubs/huggingface.py +433 -0
- camel/datahubs/models.py +22 -0
- camel/interpreters/__init__.py +2 -0
- camel/interpreters/e2b_interpreter.py +136 -0
- camel/loaders/__init__.py +3 -1
- camel/loaders/base_io.py +41 -41
- camel/messages/__init__.py +2 -0
- camel/models/__init__.py +2 -0
- camel/models/anthropic_model.py +14 -4
- camel/models/base_model.py +28 -0
- camel/models/groq_model.py +1 -1
- camel/models/model_factory.py +3 -0
- camel/models/ollama_model.py +12 -0
- camel/models/openai_model.py +0 -26
- camel/models/reward/__init__.py +22 -0
- camel/models/reward/base_reward_model.py +58 -0
- camel/models/reward/evaluator.py +63 -0
- camel/models/reward/nemotron_model.py +112 -0
- camel/models/sglang_model.py +225 -0
- camel/models/vllm_model.py +1 -1
- camel/personas/persona_hub.py +2 -2
- camel/schemas/openai_converter.py +2 -2
- camel/societies/workforce/role_playing_worker.py +2 -2
- camel/societies/workforce/single_agent_worker.py +2 -2
- camel/societies/workforce/workforce.py +3 -3
- camel/storages/object_storages/amazon_s3.py +2 -2
- camel/storages/object_storages/azure_blob.py +2 -2
- camel/storages/object_storages/google_cloud.py +2 -2
- camel/toolkits/__init__.py +2 -0
- camel/toolkits/code_execution.py +5 -1
- camel/toolkits/function_tool.py +41 -0
- camel/toolkits/math_toolkit.py +47 -16
- camel/toolkits/search_toolkit.py +154 -2
- camel/toolkits/stripe_toolkit.py +273 -0
- camel/types/__init__.py +2 -0
- camel/types/enums.py +27 -2
- camel/utils/token_counting.py +22 -10
- {camel_ai-0.2.11.dist-info → camel_ai-0.2.12.dist-info}/METADATA +13 -6
- {camel_ai-0.2.11.dist-info → camel_ai-0.2.12.dist-info}/RECORD +55 -36
- {camel_ai-0.2.11.dist-info → camel_ai-0.2.12.dist-info}/LICENSE +0 -0
- {camel_ai-0.2.11.dist-info → camel_ai-0.2.12.dist-info}/WHEEL +0 -0
camel/benchmarks/gaia.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
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 json
|
|
16
|
+
import logging
|
|
17
|
+
import os
|
|
18
|
+
import random
|
|
19
|
+
import re
|
|
20
|
+
import string
|
|
21
|
+
import uuid
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, List, Literal, Optional, Protocol, Union
|
|
24
|
+
|
|
25
|
+
from tqdm import tqdm
|
|
26
|
+
|
|
27
|
+
from camel.agents import ChatAgent
|
|
28
|
+
from camel.benchmarks import BaseBenchmark
|
|
29
|
+
from camel.messages.base import BaseMessage
|
|
30
|
+
from camel.retrievers.auto_retriever import AutoRetriever
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class RetrieverProtocol(Protocol):
|
|
36
|
+
r"""Protocol for the retriever class. Any retriever class implementing
|
|
37
|
+
this protocol can be used in the benchmark class.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def retrieve(
|
|
41
|
+
self, query: str, contents: List[str], **kwargs: Dict[str, Any]
|
|
42
|
+
) -> Dict[str, Any]:
|
|
43
|
+
r"""Retrieve the relevant content for the query.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
query (str): The query to retrieve the content for.
|
|
47
|
+
contents (List[str]): The list of contents to search in.
|
|
48
|
+
**kwargs (Dict[str, Any]): Additional keyword arguments.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
Dict[str, Any]: The relevant content for the query.
|
|
52
|
+
"""
|
|
53
|
+
...
|
|
54
|
+
|
|
55
|
+
def reset(self, **kwargs) -> bool:
|
|
56
|
+
r"""Reset the retriever.
|
|
57
|
+
Some benchmarks may require resetting the retriever
|
|
58
|
+
after each query.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
**kwargs: Additional keyword arguments.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
bool: True if the reset was successful, False otherwise.
|
|
65
|
+
"""
|
|
66
|
+
...
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class DefaultGAIARetriever(AutoRetriever):
|
|
70
|
+
r"""Default retriever for the GAIA benchmark.
|
|
71
|
+
This retriever uses AutoRetriever in camel to retrieve the content based on
|
|
72
|
+
the query.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def retrieve(
|
|
76
|
+
self, query: str, contents: List[str], **kwargs: Any
|
|
77
|
+
) -> Dict[str, Any]:
|
|
78
|
+
r"""Retrieve the content based on the query.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
query (str): The query to search for.
|
|
82
|
+
contents (List[str]): The list of contents to search from.
|
|
83
|
+
**kwargs (Any): The keyword arguments to pass to the
|
|
84
|
+
retriever.
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
Dict[str, Any]: The retrieved content.
|
|
88
|
+
"""
|
|
89
|
+
return self.run_vector_retriever(query, contents, **kwargs) # type: ignore[arg-type]
|
|
90
|
+
|
|
91
|
+
def reset(self, **kwargs: Any) -> bool:
|
|
92
|
+
r"""Reset the retriever.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
**kwargs (Any): The keyword arguments to pass to the
|
|
96
|
+
retriever.
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
bool: Whether the reset was successful.
|
|
100
|
+
"""
|
|
101
|
+
path = Path(self.vector_storage_local_path or os.getcwd())
|
|
102
|
+
task_id = str(kwargs.get("task_id", uuid.uuid4()))
|
|
103
|
+
retriever_dir = path / task_id
|
|
104
|
+
if not retriever_dir.exists():
|
|
105
|
+
try:
|
|
106
|
+
retriever_dir.mkdir(parents=True)
|
|
107
|
+
except Exception as e:
|
|
108
|
+
logger.error(
|
|
109
|
+
"Error in creating directory: " + f"{retriever_dir}: {e!s}"
|
|
110
|
+
)
|
|
111
|
+
return False
|
|
112
|
+
self.vector_storage_local_path = str(retriever_dir)
|
|
113
|
+
return True
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class GAIABenchmark(BaseBenchmark):
|
|
117
|
+
r"""GAIA Benchmark adapted from `"GAIA: a benchmark for General AI
|
|
118
|
+
Assistants"
|
|
119
|
+
<https://huggingface.co/datasets/gaia-benchmark/GAIA>`_.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
data_dir (str): The directory to save the data.
|
|
123
|
+
save_to (str): The file to save the results.
|
|
124
|
+
retriever (Optional[RetrieverProtocol]): The retriever to use.
|
|
125
|
+
(default: :obj:`None`)
|
|
126
|
+
processes (int, optional): The number of processes to use.
|
|
127
|
+
(default: :obj:`1`)
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
data_dir: str,
|
|
133
|
+
save_to: str,
|
|
134
|
+
retriever: Optional[RetrieverProtocol] = None,
|
|
135
|
+
processes: int = 1,
|
|
136
|
+
):
|
|
137
|
+
r"""Initialize the GAIA benchmark.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
data_dir (str): The directory to save the data.
|
|
141
|
+
save_to (str): The file to save the results.
|
|
142
|
+
retriever (Optional[RetrieverProtocol], optional): The retriever to
|
|
143
|
+
use. (default: :obj:`None`)
|
|
144
|
+
processes (int, optional): The number of processes to use for
|
|
145
|
+
parallel processing. (default: :obj:`1`)
|
|
146
|
+
"""
|
|
147
|
+
super().__init__("gaia", data_dir, save_to, processes)
|
|
148
|
+
self.retriever = retriever or DefaultGAIARetriever()
|
|
149
|
+
|
|
150
|
+
def download(self):
|
|
151
|
+
r"""Download the GAIA dataset."""
|
|
152
|
+
from huggingface_hub import snapshot_download
|
|
153
|
+
|
|
154
|
+
snapshot_download(
|
|
155
|
+
repo_id="gaia-benchmark/GAIA",
|
|
156
|
+
repo_type="dataset",
|
|
157
|
+
local_dir=self.data_dir,
|
|
158
|
+
local_dir_use_symlinks=True,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def load(self, force_download=False):
|
|
162
|
+
r"""Load the GAIA dataset.
|
|
163
|
+
|
|
164
|
+
Args:
|
|
165
|
+
force_download (bool, optional): Whether to
|
|
166
|
+
force download the data.
|
|
167
|
+
"""
|
|
168
|
+
if force_download:
|
|
169
|
+
logger.info("Force downloading data.")
|
|
170
|
+
self.download()
|
|
171
|
+
|
|
172
|
+
# Define validation and test directories
|
|
173
|
+
valid_dir = self.data_dir / "2023/validation"
|
|
174
|
+
test_dir = self.data_dir / "2023/test"
|
|
175
|
+
|
|
176
|
+
# Check if directories exist; if not, download the data
|
|
177
|
+
if not valid_dir.is_dir() or not test_dir.is_dir():
|
|
178
|
+
logger.info("Data not found. Downloading data.")
|
|
179
|
+
self.download()
|
|
180
|
+
|
|
181
|
+
# Load metadata for both validation and test datasets
|
|
182
|
+
for path, label in zip([valid_dir, test_dir], ["valid", "test"]):
|
|
183
|
+
self._data[label] = []
|
|
184
|
+
with open(path / "metadata.jsonl", "r") as f:
|
|
185
|
+
lines = f.readlines()
|
|
186
|
+
for line in lines:
|
|
187
|
+
data = json.loads(line)
|
|
188
|
+
if data["task_id"] == "0-0-0-0-0":
|
|
189
|
+
continue
|
|
190
|
+
if data["file_name"]:
|
|
191
|
+
data["file_name"] = path / data["file_name"]
|
|
192
|
+
self._data[label].append(data)
|
|
193
|
+
return self
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def train(self):
|
|
197
|
+
r"""Get the training set."""
|
|
198
|
+
raise NotImplementedError("GAIA does not have a training set.")
|
|
199
|
+
|
|
200
|
+
def run( # type: ignore[override]
|
|
201
|
+
self,
|
|
202
|
+
agent: ChatAgent,
|
|
203
|
+
on: Literal["train", "valid", "test"],
|
|
204
|
+
level: Union[int, List[int], Literal["all"]],
|
|
205
|
+
randomize: bool = False,
|
|
206
|
+
subset: Optional[int] = None,
|
|
207
|
+
) -> Dict[str, Any]:
|
|
208
|
+
r"""Run the benchmark.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
agent (ChatAgent): The agent to run the benchmark.
|
|
212
|
+
on (Literal["valid", "test"]): The set to run the benchmark.
|
|
213
|
+
level (Union[int, List[int], Literal["all"]]): The level to run
|
|
214
|
+
the benchmark.
|
|
215
|
+
randomize (bool, optional): Whether to randomize the data.
|
|
216
|
+
(default: :obj:`False`)
|
|
217
|
+
subset (Optional[int], optional): The subset of data to run.
|
|
218
|
+
(default: :obj:`None`)
|
|
219
|
+
|
|
220
|
+
Returns:
|
|
221
|
+
Dict[str, Any]: The results of the benchmark.
|
|
222
|
+
"""
|
|
223
|
+
# Validate inputs
|
|
224
|
+
if on not in ["valid", "test"]:
|
|
225
|
+
raise ValueError(
|
|
226
|
+
f"Invalid value for `on`: {on}, expected 'valid' or 'test'."
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
levels = (
|
|
230
|
+
[1, 2, 3]
|
|
231
|
+
if level == "all"
|
|
232
|
+
else [level]
|
|
233
|
+
if isinstance(level, int)
|
|
234
|
+
else level
|
|
235
|
+
)
|
|
236
|
+
if not all(
|
|
237
|
+
isinstance(level, int) and level in [1, 2, 3] for level in levels
|
|
238
|
+
):
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"Invalid value for `level`: {level}, expected 1, 2, 3 "
|
|
241
|
+
"or 'all'."
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
logger.info(f"Running benchmark on {on} set at levels {levels}.")
|
|
245
|
+
datas = [data for data in self._data[on] if data["Level"] in levels]
|
|
246
|
+
|
|
247
|
+
# Shuffle and subset data if necessary
|
|
248
|
+
if randomize:
|
|
249
|
+
random.shuffle(datas)
|
|
250
|
+
if subset:
|
|
251
|
+
datas = datas[:subset]
|
|
252
|
+
|
|
253
|
+
logger.info(f"Number of tasks: {len(datas)}")
|
|
254
|
+
|
|
255
|
+
# Initialize results storage
|
|
256
|
+
self._results = []
|
|
257
|
+
|
|
258
|
+
# Process tasks
|
|
259
|
+
with open(self.save_to, "w") as f:
|
|
260
|
+
for task in tqdm(datas, desc="Running"):
|
|
261
|
+
if not self._prepare_task(task):
|
|
262
|
+
continue
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
result = agent.step(self._create_user_message(task))
|
|
266
|
+
self._process_result(agent, task, result, f)
|
|
267
|
+
except Exception as e:
|
|
268
|
+
self._handle_error(task, e, f)
|
|
269
|
+
finally:
|
|
270
|
+
agent.reset()
|
|
271
|
+
|
|
272
|
+
return self._generate_summary()
|
|
273
|
+
|
|
274
|
+
def _prepare_task(self, task: Dict[str, Any]) -> bool:
|
|
275
|
+
r"""Prepare the task by validating and enriching its data."""
|
|
276
|
+
if task["file_name"]:
|
|
277
|
+
file_path = Path(task["file_name"])
|
|
278
|
+
if not file_path.exists():
|
|
279
|
+
logger.info(
|
|
280
|
+
f"Skipping task because file not found: {file_path}"
|
|
281
|
+
)
|
|
282
|
+
return False
|
|
283
|
+
if file_path.suffix in ['.pdf', '.docx', '.doc', '.txt']:
|
|
284
|
+
if not self.retriever.reset(task_id=task["task_id"]):
|
|
285
|
+
return False
|
|
286
|
+
retrieved_info = self.retriever.retrieve(
|
|
287
|
+
query=task["Question"], contents=[task['file_name']]
|
|
288
|
+
)
|
|
289
|
+
retrieved_content = [
|
|
290
|
+
item["text"]
|
|
291
|
+
for item in retrieved_info.get("Retrieved Context", [])
|
|
292
|
+
]
|
|
293
|
+
if retrieved_content:
|
|
294
|
+
task["Question"] += "\n" + "\n".join(retrieved_content)
|
|
295
|
+
else:
|
|
296
|
+
logger.info(
|
|
297
|
+
f"Skipping task due to unsupported file "
|
|
298
|
+
f"format: {file_path.suffix}"
|
|
299
|
+
)
|
|
300
|
+
return False
|
|
301
|
+
return True
|
|
302
|
+
|
|
303
|
+
def _create_user_message(self, task: Dict[str, Any]) -> BaseMessage:
|
|
304
|
+
r"""Create a user message from a task."""
|
|
305
|
+
return BaseMessage.make_user_message(
|
|
306
|
+
role_name="User",
|
|
307
|
+
content=task["Question"],
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
def _process_result(
|
|
311
|
+
self,
|
|
312
|
+
agent: ChatAgent,
|
|
313
|
+
task: Dict[str, Any],
|
|
314
|
+
result: Any,
|
|
315
|
+
file_obj: Any,
|
|
316
|
+
) -> None:
|
|
317
|
+
r"""Process and store the result of a task."""
|
|
318
|
+
model_answer = self.get_final_answer(result.msgs[0].content)
|
|
319
|
+
final_answer = task["Final answer"]
|
|
320
|
+
score = self.question_scorer(model_answer, final_answer)
|
|
321
|
+
tool_calls = result.info.get("tool_calls", [])
|
|
322
|
+
|
|
323
|
+
result_data = {
|
|
324
|
+
"task_id": task["task_id"],
|
|
325
|
+
"question": task["Question"],
|
|
326
|
+
"level": task["Level"],
|
|
327
|
+
"model_answer": model_answer,
|
|
328
|
+
"ground_truth": final_answer,
|
|
329
|
+
"tool_calls": [tool.model_dump() for tool in tool_calls],
|
|
330
|
+
"error": None,
|
|
331
|
+
"score": int(score),
|
|
332
|
+
"history": agent.memory.get_context(),
|
|
333
|
+
}
|
|
334
|
+
self._results.append(result_data)
|
|
335
|
+
file_obj.write(json.dumps(result_data, indent=2) + "\n")
|
|
336
|
+
file_obj.flush()
|
|
337
|
+
|
|
338
|
+
def _handle_error(
|
|
339
|
+
self, task: Dict[str, Any], error: Exception, file_obj: Any
|
|
340
|
+
) -> None:
|
|
341
|
+
r"""Handle errors encountered during task processing."""
|
|
342
|
+
logger.warning(f"Error processing task {task['task_id']}: {error}")
|
|
343
|
+
error_data = {
|
|
344
|
+
"task_id": task["task_id"],
|
|
345
|
+
"question": task["Question"],
|
|
346
|
+
"level": task["Level"],
|
|
347
|
+
"model_answer": "ERROR",
|
|
348
|
+
"ground_truth": task["Final answer"],
|
|
349
|
+
"tool_calls": [],
|
|
350
|
+
"error": str(error),
|
|
351
|
+
"score": 0,
|
|
352
|
+
}
|
|
353
|
+
self._results.append(error_data)
|
|
354
|
+
file_obj.write(json.dumps(error_data, indent=2) + "\n")
|
|
355
|
+
file_obj.flush()
|
|
356
|
+
|
|
357
|
+
def _generate_summary(self) -> Dict[str, Any]:
|
|
358
|
+
r"""Generate and return a summary of the benchmark results."""
|
|
359
|
+
return {
|
|
360
|
+
"total": len(self._results),
|
|
361
|
+
"correct": sum(result["score"] for result in self._results),
|
|
362
|
+
"results": self._results,
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
def question_scorer(self, model_answer: str, ground_truth: str) -> bool:
|
|
366
|
+
r"""Scorer for the GAIA benchmark.
|
|
367
|
+
https://huggingface.co/spaces/gaia-benchmark/leaderboard/blob/main/
|
|
368
|
+
scorer.py
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
model_answer (str): The model answer.
|
|
372
|
+
ground_truth (str): The ground truth answer.
|
|
373
|
+
|
|
374
|
+
Returns:
|
|
375
|
+
bool: The score of the model
|
|
376
|
+
"""
|
|
377
|
+
|
|
378
|
+
def is_float(element: Any) -> bool:
|
|
379
|
+
try:
|
|
380
|
+
float(element)
|
|
381
|
+
return True
|
|
382
|
+
except ValueError:
|
|
383
|
+
return False
|
|
384
|
+
|
|
385
|
+
if is_float(ground_truth):
|
|
386
|
+
logger.info(f"Evaluating {model_answer} as a number.")
|
|
387
|
+
normalized_answer = self.normalize_number_str(model_answer)
|
|
388
|
+
return normalized_answer == float(ground_truth)
|
|
389
|
+
|
|
390
|
+
elif any(char in ground_truth for char in [",", ";"]):
|
|
391
|
+
logger.info(
|
|
392
|
+
f"Evaluating {model_answer} as a comma separated list."
|
|
393
|
+
)
|
|
394
|
+
gt_elems = self.split_string(ground_truth)
|
|
395
|
+
ma_elems = self.split_string(model_answer)
|
|
396
|
+
|
|
397
|
+
if len(gt_elems) != len(ma_elems):
|
|
398
|
+
logger.warning(
|
|
399
|
+
"Answer lists have different lengths, returning False.",
|
|
400
|
+
UserWarning,
|
|
401
|
+
)
|
|
402
|
+
return False
|
|
403
|
+
|
|
404
|
+
comparisons = []
|
|
405
|
+
for ma_elem, gt_elem in zip(ma_elems, gt_elems):
|
|
406
|
+
if is_float(gt_elem):
|
|
407
|
+
normalized_ma_elem = self.normalize_number_str(ma_elem)
|
|
408
|
+
comparisons.append(normalized_ma_elem == float(gt_elem))
|
|
409
|
+
else:
|
|
410
|
+
ma_elem = self.normalize_str(ma_elem, remove_punct=False)
|
|
411
|
+
gt_elem = self.normalize_str(gt_elem, remove_punct=False)
|
|
412
|
+
comparisons.append(ma_elem == gt_elem)
|
|
413
|
+
return all(comparisons)
|
|
414
|
+
else:
|
|
415
|
+
logger.info(f"Evaluating {model_answer} as a string.")
|
|
416
|
+
ma_elem = self.normalize_str(model_answer)
|
|
417
|
+
gt_elem = self.normalize_str(ground_truth)
|
|
418
|
+
return ma_elem == gt_elem
|
|
419
|
+
|
|
420
|
+
def normalize_number_str(self, number_str: str) -> float:
|
|
421
|
+
for char in ["$", "%", ","]:
|
|
422
|
+
number_str = number_str.replace(char, "")
|
|
423
|
+
try:
|
|
424
|
+
return float(number_str)
|
|
425
|
+
except ValueError:
|
|
426
|
+
logger.error(
|
|
427
|
+
f"String {number_str} cannot be normalized to number str."
|
|
428
|
+
)
|
|
429
|
+
return float("inf")
|
|
430
|
+
|
|
431
|
+
def split_string(
|
|
432
|
+
self, s: str, char_list: Optional[List[str]] = None
|
|
433
|
+
) -> list[str]:
|
|
434
|
+
r"""Split a string based on a list of characters.
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
s (str): The string to split.
|
|
438
|
+
char_list (Optional[List[str]], optional): T
|
|
439
|
+
he list of characters to split on.
|
|
440
|
+
(default: :obj:`None`)
|
|
441
|
+
"""
|
|
442
|
+
if char_list is None:
|
|
443
|
+
char_list = [",", ";"]
|
|
444
|
+
pattern = f"[{''.join(char_list)}]"
|
|
445
|
+
return re.split(pattern, s)
|
|
446
|
+
|
|
447
|
+
def normalize_str(self, input_str, remove_punct=True) -> str:
|
|
448
|
+
r"""Normalize a string.
|
|
449
|
+
|
|
450
|
+
Args:
|
|
451
|
+
input_str: The input string to normalize.
|
|
452
|
+
remove_punct: Whether to remove punctuation.
|
|
453
|
+
|
|
454
|
+
Returns:
|
|
455
|
+
str: The normalized string.
|
|
456
|
+
"""
|
|
457
|
+
no_spaces = re.sub(r"\s", "", input_str)
|
|
458
|
+
if remove_punct:
|
|
459
|
+
translator = str.maketrans("", "", string.punctuation)
|
|
460
|
+
return no_spaces.lower().translate(translator)
|
|
461
|
+
else:
|
|
462
|
+
return no_spaces.lower()
|
|
463
|
+
|
|
464
|
+
def get_final_answer(self, content: str) -> str:
|
|
465
|
+
r"""Get the final answer from the content.
|
|
466
|
+
|
|
467
|
+
Args:
|
|
468
|
+
content (str): The content to extract the final answer from.
|
|
469
|
+
|
|
470
|
+
Returns:
|
|
471
|
+
str: The final answer.
|
|
472
|
+
"""
|
|
473
|
+
final_answer_index = content.find("FINAL ANSWER")
|
|
474
|
+
if final_answer_index == -1:
|
|
475
|
+
return "FINAL ANSWER not found"
|
|
476
|
+
start_index = final_answer_index + len("FINAL ANSWER: ")
|
|
477
|
+
final_answer_content = content[start_index:].strip()
|
|
478
|
+
return final_answer_content
|
camel/configs/__init__.py
CHANGED
|
@@ -30,6 +30,7 @@ from .samba_config import (
|
|
|
30
30
|
SambaCloudAPIConfig,
|
|
31
31
|
SambaVerseAPIConfig,
|
|
32
32
|
)
|
|
33
|
+
from .sglang_config import SGLANG_API_PARAMS, SGLangConfig
|
|
33
34
|
from .togetherai_config import TOGETHERAI_API_PARAMS, TogetherAIConfig
|
|
34
35
|
from .vllm_config import VLLM_API_PARAMS, VLLMConfig
|
|
35
36
|
from .yi_config import YI_API_PARAMS, YiConfig
|
|
@@ -55,6 +56,8 @@ __all__ = [
|
|
|
55
56
|
'Gemini_API_PARAMS',
|
|
56
57
|
'VLLMConfig',
|
|
57
58
|
'VLLM_API_PARAMS',
|
|
59
|
+
'SGLangConfig',
|
|
60
|
+
'SGLANG_API_PARAMS',
|
|
58
61
|
'MistralConfig',
|
|
59
62
|
'MISTRAL_API_PARAMS',
|
|
60
63
|
'RekaConfig',
|
camel/configs/ollama_config.py
CHANGED
|
@@ -13,7 +13,9 @@
|
|
|
13
13
|
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
|
-
from typing import Sequence, Union
|
|
16
|
+
from typing import Sequence, Type, Union
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel
|
|
17
19
|
|
|
18
20
|
from camel.configs.base_config import BaseConfig
|
|
19
21
|
from camel.types import NOT_GIVEN, NotGiven
|
|
@@ -75,7 +77,7 @@ class OllamaConfig(BaseConfig):
|
|
|
75
77
|
stop: Union[str, Sequence[str], NotGiven] = NOT_GIVEN
|
|
76
78
|
max_tokens: Union[int, NotGiven] = NOT_GIVEN
|
|
77
79
|
presence_penalty: float = 0.0
|
|
78
|
-
response_format: Union[dict, NotGiven] = NOT_GIVEN
|
|
80
|
+
response_format: Union[Type[BaseModel], dict, NotGiven] = NOT_GIVEN
|
|
79
81
|
frequency_penalty: float = 0.0
|
|
80
82
|
|
|
81
83
|
|
|
@@ -0,0 +1,71 @@
|
|
|
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 __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Sequence, Union
|
|
17
|
+
|
|
18
|
+
from camel.configs.base_config import BaseConfig
|
|
19
|
+
from camel.types import NOT_GIVEN, NotGiven
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SGLangConfig(BaseConfig):
|
|
23
|
+
r"""Defines the parameters for generating chat completions using the
|
|
24
|
+
OpenAI API.
|
|
25
|
+
|
|
26
|
+
Reference: https://sgl-project.github.io/references/sampling_params.html
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
stop (str or list, optional): Up to :obj:`4` sequences where the API
|
|
30
|
+
will stop generating further tokens. (default: :obj:`None`)
|
|
31
|
+
temperature (float, optional): Sampling temperature to use, between
|
|
32
|
+
:obj:`0` and :obj:`2`. Higher values make the output more random,
|
|
33
|
+
while lower values make it more focused and deterministic.
|
|
34
|
+
(default: :obj:`1.0`)
|
|
35
|
+
top_p (float, optional): An alternative to sampling with temperature,
|
|
36
|
+
called nucleus sampling, where the model considers the results of
|
|
37
|
+
the tokens with top_p probability mass. So :obj:`0.1` means only
|
|
38
|
+
the tokens comprising the top 10% probability mass are considered.
|
|
39
|
+
(default: :obj:`1.0`)
|
|
40
|
+
n (int, optional): How many chat completion choices to generate for
|
|
41
|
+
each input message. (default: :obj:`1`)
|
|
42
|
+
frequency_penalty (float, optional): Number between :obj:`-2.0` and
|
|
43
|
+
:obj:`2.0`. Positive values penalize new tokens based on their
|
|
44
|
+
existing frequency in the text so far, decreasing the model's
|
|
45
|
+
likelihood to repeat the same line verbatim. See more information
|
|
46
|
+
about frequency and presence penalties. (default: :obj:`0.0`)
|
|
47
|
+
presence_penalty (float, optional): Number between :obj:`-2.0` and
|
|
48
|
+
:obj:`2.0`. Positive values penalize new tokens based on whether
|
|
49
|
+
they appear in the text so far, increasing the model's likelihood
|
|
50
|
+
to talk about new topics. See more information about frequency and
|
|
51
|
+
presence penalties. (default: :obj:`0.0`)
|
|
52
|
+
stream (bool, optional): Whether to stream the generated output in
|
|
53
|
+
chunks. If set to `True`, the response will be streamed as it is
|
|
54
|
+
generated. (default: :obj:`False`)
|
|
55
|
+
max_tokens (int, optional): The maximum number of tokens to generate
|
|
56
|
+
in the chat completion. The total length of input tokens and
|
|
57
|
+
generated tokens is limited by the model's context length.
|
|
58
|
+
(default: :obj:`None`)
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
stop: Union[str, Sequence[str], NotGiven] = NOT_GIVEN
|
|
62
|
+
temperature: float = 1.0
|
|
63
|
+
top_p: float = 1.0
|
|
64
|
+
n: int = 1
|
|
65
|
+
frequency_penalty: float = 0.0
|
|
66
|
+
presence_penalty: float = 0.0
|
|
67
|
+
stream: bool = False
|
|
68
|
+
max_tokens: Union[int, NotGiven] = NOT_GIVEN
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
SGLANG_API_PARAMS = {param for param in SGLangConfig.model_fields.keys()}
|
|
@@ -0,0 +1,19 @@
|
|
|
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 .alpaca_collector import AlpacaDataCollector
|
|
16
|
+
from .base import BaseDataCollector
|
|
17
|
+
from .sharegpt_collector import ShareGPTDataCollector
|
|
18
|
+
|
|
19
|
+
__all__ = ["BaseDataCollector", "AlpacaDataCollector", "ShareGPTDataCollector"]
|