camel-ai 0.2.15a0__py3-none-any.whl → 0.2.16__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/benchmarks/__init__.py +11 -1
- camel/benchmarks/apibank.py +560 -0
- camel/benchmarks/apibench.py +496 -0
- camel/benchmarks/gaia.py +2 -2
- camel/benchmarks/nexus.py +518 -0
- camel/datagen/__init__.py +6 -2
- camel/datagen/{o1datagen.py → cotdatagen.py} +19 -6
- camel/datagen/self_instruct/__init__.py +36 -0
- camel/datagen/self_instruct/filter/__init__.py +34 -0
- camel/datagen/self_instruct/filter/filter_function.py +216 -0
- camel/datagen/self_instruct/filter/filter_registry.py +56 -0
- camel/datagen/self_instruct/filter/instruction_filter.py +81 -0
- camel/datagen/self_instruct/self_instruct.py +393 -0
- camel/datagen/self_instruct/templates.py +384 -0
- camel/datahubs/huggingface.py +12 -2
- camel/datahubs/models.py +2 -3
- camel/embeddings/mistral_embedding.py +5 -1
- camel/embeddings/openai_compatible_embedding.py +6 -1
- camel/embeddings/openai_embedding.py +5 -1
- camel/interpreters/e2b_interpreter.py +5 -1
- camel/loaders/apify_reader.py +5 -1
- camel/loaders/chunkr_reader.py +5 -1
- camel/loaders/firecrawl_reader.py +0 -30
- camel/logger.py +11 -5
- camel/models/anthropic_model.py +5 -1
- camel/models/azure_openai_model.py +1 -2
- camel/models/cohere_model.py +5 -1
- camel/models/deepseek_model.py +5 -1
- camel/models/gemini_model.py +5 -1
- camel/models/groq_model.py +5 -1
- camel/models/mistral_model.py +5 -1
- camel/models/nemotron_model.py +5 -1
- camel/models/nvidia_model.py +5 -1
- camel/models/openai_model.py +5 -1
- camel/models/qwen_model.py +5 -1
- camel/models/reka_model.py +5 -1
- camel/models/reward/nemotron_model.py +5 -1
- camel/models/samba_model.py +5 -1
- camel/models/togetherai_model.py +5 -1
- camel/models/yi_model.py +5 -1
- camel/models/zhipuai_model.py +5 -1
- camel/schemas/openai_converter.py +5 -1
- camel/storages/graph_storages/nebula_graph.py +89 -20
- camel/storages/graph_storages/neo4j_graph.py +138 -0
- camel/toolkits/__init__.py +4 -0
- camel/toolkits/arxiv_toolkit.py +20 -3
- camel/toolkits/dappier_toolkit.py +196 -0
- camel/toolkits/function_tool.py +61 -61
- camel/toolkits/meshy_toolkit.py +5 -1
- camel/toolkits/notion_toolkit.py +1 -1
- camel/toolkits/openbb_toolkit.py +869 -0
- camel/toolkits/search_toolkit.py +91 -5
- camel/toolkits/stripe_toolkit.py +5 -1
- camel/toolkits/twitter_toolkit.py +24 -16
- camel/utils/__init__.py +2 -0
- camel/utils/commons.py +104 -19
- {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.16.dist-info}/METADATA +16 -4
- {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.16.dist-info}/RECORD +61 -49
- {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.16.dist-info}/LICENSE +0 -0
- {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.16.dist-info}/WHEEL +0 -0
|
@@ -0,0 +1,518 @@
|
|
|
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 ast
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import random
|
|
20
|
+
import textwrap
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Dict, List, Literal, Optional, Tuple, Union
|
|
24
|
+
|
|
25
|
+
import pandas as pd
|
|
26
|
+
from datasets import load_dataset
|
|
27
|
+
from tqdm import tqdm
|
|
28
|
+
|
|
29
|
+
from camel.agents import ChatAgent
|
|
30
|
+
from camel.benchmarks.base import BaseBenchmark
|
|
31
|
+
from camel.messages import BaseMessage
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Define the data class
|
|
37
|
+
@dataclass
|
|
38
|
+
class NexusSample:
|
|
39
|
+
r"""Nexus benchmark dataset sample."""
|
|
40
|
+
|
|
41
|
+
input: str
|
|
42
|
+
output: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class NexusTool:
|
|
47
|
+
r"""Nexus benchmark tool"""
|
|
48
|
+
|
|
49
|
+
function_calls: str
|
|
50
|
+
descriptions: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
dataset_mapping = {
|
|
54
|
+
"NVDLibrary": "Nexusflow/NVDLibraryBenchmark",
|
|
55
|
+
"VirusTotal": "Nexusflow/VirusTotalBenchmark",
|
|
56
|
+
"PlacesAPI": "Nexusflow/PlacesAPIBenchmark",
|
|
57
|
+
"ClimateAPI": "Nexusflow/ClimateAPIBenchmark",
|
|
58
|
+
"OTX": "Nexusflow/OTXAPIBenchmark",
|
|
59
|
+
"VirusTotal-NestedCalls": "Nexusflow/vt_multiapi",
|
|
60
|
+
"VirusTotal-ParallelCalls": "Nexusflow/vt_multiapi",
|
|
61
|
+
"NVDLibrary-NestedCalls": "Nexusflow/CVECPEAPIBenchmark",
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
TOOL_CALLING_PROMPT = """
|
|
65
|
+
You are given multiple functions and a user query.
|
|
66
|
+
|
|
67
|
+
Please proceed with generating a function call for the function \
|
|
68
|
+
with the proper arguments that best answers the given prompt.
|
|
69
|
+
|
|
70
|
+
Respond with nothing but the function call ONLY, such that I can \
|
|
71
|
+
directly execute your function call without any post processing \
|
|
72
|
+
necessary from my end. Do not use variables.
|
|
73
|
+
If there are more than two function calls, separate them with a semicolon (;).
|
|
74
|
+
|
|
75
|
+
{tools}
|
|
76
|
+
|
|
77
|
+
Question: {input}
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class NexusBenchmark(BaseBenchmark):
|
|
82
|
+
r"""Nexus Function Calling Benchmark adapted from `NexusRaven V2
|
|
83
|
+
Function Calling Benchmark`
|
|
84
|
+
<https://huggingface.co/collections/Nexusflow/nexusraven-v2-function-calling-benchmark-657a597fb84dbe7a09ebfc3e>.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
data_dir (str): The directory to save the data.
|
|
88
|
+
save_to (str): The file to save the results.
|
|
89
|
+
processes (int, optional): The number of processes to use.
|
|
90
|
+
(default: :obj:`1`)
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
def __init__(
|
|
94
|
+
self,
|
|
95
|
+
data_dir: str,
|
|
96
|
+
save_to: str,
|
|
97
|
+
processes: int = 1,
|
|
98
|
+
):
|
|
99
|
+
r"""Initialize the Nexus Function Calling benchmark.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
data_dir (str): The directory to save the data.
|
|
103
|
+
save_to (str): The file to save the results.
|
|
104
|
+
processes (int, optional): The number of processes to use for
|
|
105
|
+
parallel processing. (default: :obj:`1`)
|
|
106
|
+
"""
|
|
107
|
+
super().__init__("nexus", data_dir, save_to, processes)
|
|
108
|
+
self._data: List[NexusSample] = [] # type: ignore[assignment]
|
|
109
|
+
|
|
110
|
+
def download(self):
|
|
111
|
+
r"""Download the Nexus Functional Calling Benchmark dataset."""
|
|
112
|
+
from huggingface_hub import snapshot_download
|
|
113
|
+
|
|
114
|
+
for dataset_name, repo_id in dataset_mapping.items():
|
|
115
|
+
local_dir = self.data_dir / dataset_name
|
|
116
|
+
snapshot_download(
|
|
117
|
+
repo_id=repo_id,
|
|
118
|
+
repo_type="dataset",
|
|
119
|
+
local_dir=local_dir,
|
|
120
|
+
local_dir_use_symlinks=True,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
def load(self, dataset_name: str, force_download: bool = False): # type: ignore[override]
|
|
124
|
+
r"""Load the Nexus Benchmark dataset.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
dataset_name (str): Name of the specific dataset to be loaded.
|
|
128
|
+
force_download (bool): Whether to force download the data.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def _load_csv_data(dataset_dir: Path) -> List:
|
|
132
|
+
r"""Load datasets from CSV files."""
|
|
133
|
+
dataset = []
|
|
134
|
+
for file_name in os.listdir(dataset_dir):
|
|
135
|
+
file_path = dataset_dir / file_name
|
|
136
|
+
if file_name.endswith(".csv"):
|
|
137
|
+
data = pd.read_csv(file_path)
|
|
138
|
+
for _, sample in data.iterrows():
|
|
139
|
+
dataset.append(
|
|
140
|
+
NexusSample(
|
|
141
|
+
sample["Input"], "".join(sample["Output"])
|
|
142
|
+
)
|
|
143
|
+
)
|
|
144
|
+
continue
|
|
145
|
+
|
|
146
|
+
logger.warning(f"Skipping unsupported file: {file_name}")
|
|
147
|
+
return dataset
|
|
148
|
+
|
|
149
|
+
def _load_parquet_data(data_dir: Path, dataset_name: str) -> List:
|
|
150
|
+
r"""Load datasets from Parquet files."""
|
|
151
|
+
dataset = []
|
|
152
|
+
if not data_dir.exists():
|
|
153
|
+
raise FileNotFoundError(
|
|
154
|
+
f"Data directory '{data_dir}' does not exist."
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
for file_name in os.listdir(data_dir):
|
|
158
|
+
file_path = data_dir / file_name
|
|
159
|
+
if file_name.endswith(".parquet"):
|
|
160
|
+
data = pd.read_parquet(file_path)
|
|
161
|
+
dataset.extend(_process_parquet_data(data, dataset_name))
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
logger.warning(f"Skipping unsupported file: {file_name}")
|
|
165
|
+
|
|
166
|
+
return dataset
|
|
167
|
+
|
|
168
|
+
def _process_parquet_data(
|
|
169
|
+
data: pd.DataFrame, dataset_name: str
|
|
170
|
+
) -> List:
|
|
171
|
+
r"""Process data from Parquet files based on dataset name."""
|
|
172
|
+
dataset: List = []
|
|
173
|
+
dataset_handlers = {
|
|
174
|
+
"NVDLibrary": _process_nvdlibrary,
|
|
175
|
+
"VirusTotal": _process_simple,
|
|
176
|
+
"PlacesAPI": _process_simple,
|
|
177
|
+
"ClimateAPI": _process_simple,
|
|
178
|
+
"OTX": _process_simple,
|
|
179
|
+
"VirusTotal-NestedCalls": _process_nested_calls,
|
|
180
|
+
"VirusTotal-ParallelCalls": _process_parallel_calls,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
if dataset_name not in dataset_handlers:
|
|
184
|
+
logger.warning(
|
|
185
|
+
f"No specific handler for dataset: {dataset_name}"
|
|
186
|
+
)
|
|
187
|
+
return dataset
|
|
188
|
+
|
|
189
|
+
handler = dataset_handlers[dataset_name]
|
|
190
|
+
for _, sample in data.iterrows():
|
|
191
|
+
processed_sample = handler(sample)
|
|
192
|
+
if processed_sample:
|
|
193
|
+
dataset.append(processed_sample)
|
|
194
|
+
return dataset
|
|
195
|
+
|
|
196
|
+
def _process_nvdlibrary(sample) -> NexusSample:
|
|
197
|
+
r"""Process samples for the NVDLibrary dataset."""
|
|
198
|
+
return NexusSample(
|
|
199
|
+
sample["Input"], sample["Output"].replace("r = nvdlib.", "")
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
def _process_simple(sample) -> NexusSample:
|
|
203
|
+
r"""Process samples for simple datasets (e.g., VirusTotal)."""
|
|
204
|
+
return NexusSample(sample["Input"], sample["Output"])
|
|
205
|
+
|
|
206
|
+
def _process_nested_calls(sample) -> Union[NexusSample, None]:
|
|
207
|
+
r"""Process samples for VirusTotal-NestedCalls dataset."""
|
|
208
|
+
if len(sample["fncall"]) == 1:
|
|
209
|
+
return NexusSample(
|
|
210
|
+
sample["generated_question"], "".join(sample["fncall"])
|
|
211
|
+
)
|
|
212
|
+
return None
|
|
213
|
+
|
|
214
|
+
def _process_parallel_calls(sample) -> Union[NexusSample, None]:
|
|
215
|
+
r"""Process samples for VirusTotal-ParallelCalls dataset."""
|
|
216
|
+
if len(sample["fncall"]) > 1:
|
|
217
|
+
return NexusSample(
|
|
218
|
+
sample["generated_question"], "; ".join(sample["fncall"])
|
|
219
|
+
)
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
if force_download:
|
|
223
|
+
logger.info("Force downloading data.")
|
|
224
|
+
self.download()
|
|
225
|
+
|
|
226
|
+
# Validate dataset name
|
|
227
|
+
if dataset_name not in dataset_mapping:
|
|
228
|
+
available_datasets = list(dataset_mapping.keys())
|
|
229
|
+
raise ValueError(
|
|
230
|
+
f"Dataset '{dataset_name}' is not recognized. "
|
|
231
|
+
f"Available datasets: {available_datasets}"
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
# Get the dataset directory
|
|
235
|
+
dataset_dir = self.data_dir / dataset_name
|
|
236
|
+
if not dataset_dir.exists():
|
|
237
|
+
raise FileNotFoundError(
|
|
238
|
+
f"The dataset directory for '{dataset_name}' \
|
|
239
|
+
does not exist at {dataset_dir}. "
|
|
240
|
+
"Please download it first."
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
# Load the dataset
|
|
244
|
+
if dataset_name == "NVDLibrary-NestedCalls":
|
|
245
|
+
self._data = _load_csv_data(dataset_dir)
|
|
246
|
+
else:
|
|
247
|
+
self._data = _load_parquet_data(dataset_dir / "data", dataset_name)
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def train(self):
|
|
251
|
+
r"""Get the training set."""
|
|
252
|
+
raise NotImplementedError(
|
|
253
|
+
"Nexus Functional Calling has only a single 'train' set."
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
def run( # type: ignore[override, return]
|
|
257
|
+
self,
|
|
258
|
+
agent: ChatAgent,
|
|
259
|
+
task: Literal[
|
|
260
|
+
"NVDLibrary",
|
|
261
|
+
"VirusTotal",
|
|
262
|
+
"OTX",
|
|
263
|
+
"PlacesAPI",
|
|
264
|
+
"ClimateAPI",
|
|
265
|
+
"VirusTotal-ParallelCalls",
|
|
266
|
+
"VirusTotal-NestedCalls",
|
|
267
|
+
"NVDLibrary-NestedCalls",
|
|
268
|
+
],
|
|
269
|
+
randomize: bool = False,
|
|
270
|
+
subset: Optional[int] = None,
|
|
271
|
+
) -> Dict[str, Any]:
|
|
272
|
+
r"""Run the benchmark.
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
agent (ChatAgent): The agent to run the benchmark.
|
|
276
|
+
task (Literal["NVDLibrary", "VirusTotal", "OTX",
|
|
277
|
+
"PlacesAPI", "ClimateAPI", "VirusTotal-ParallelCalls",
|
|
278
|
+
"VirusTotal-NestedCalls",
|
|
279
|
+
"NVDLibrary-NestedCalls"]): The task to run the benchmark.
|
|
280
|
+
randomize (bool, optional): Whether to randomize the data.
|
|
281
|
+
(default: :obj:`False`)
|
|
282
|
+
subset (Optional[int], optional): The subset of data to run.
|
|
283
|
+
(default: :obj:`None`)
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
Dict[str, Any]: The results of the benchmark.
|
|
287
|
+
"""
|
|
288
|
+
|
|
289
|
+
if task not in dataset_mapping:
|
|
290
|
+
raise ValueError(f"Invalid value for dataset: {task}.")
|
|
291
|
+
|
|
292
|
+
logger.info(f"Running Nexus Function Calling benchmark on {task}.")
|
|
293
|
+
self.load(task)
|
|
294
|
+
datas = self._data
|
|
295
|
+
|
|
296
|
+
# Shuffle and subset data if necessary
|
|
297
|
+
if randomize:
|
|
298
|
+
random.shuffle(datas)
|
|
299
|
+
if subset:
|
|
300
|
+
datas = datas[:subset]
|
|
301
|
+
|
|
302
|
+
logger.info(f"Number of tasks: {len(datas)}")
|
|
303
|
+
|
|
304
|
+
# Initialize results storage
|
|
305
|
+
self._results = []
|
|
306
|
+
|
|
307
|
+
# Process samples
|
|
308
|
+
tools = construct_tool_descriptions(task)
|
|
309
|
+
with open(self.save_to, "w") as f:
|
|
310
|
+
for sample in tqdm(datas, desc="Running"):
|
|
311
|
+
prompt = construct_prompt(input=sample.input, tools=tools)
|
|
312
|
+
msg = BaseMessage.make_user_message(
|
|
313
|
+
role_name="User", content=prompt
|
|
314
|
+
)
|
|
315
|
+
ground_truth_call = sample.output
|
|
316
|
+
try:
|
|
317
|
+
# Generate response
|
|
318
|
+
response = agent.step(msg)
|
|
319
|
+
agent_call = response.msgs[0].content
|
|
320
|
+
|
|
321
|
+
# Evaluate response
|
|
322
|
+
if agent_call:
|
|
323
|
+
result = compare_function_calls(
|
|
324
|
+
agent_call=agent_call,
|
|
325
|
+
ground_truth_call=ground_truth_call,
|
|
326
|
+
)
|
|
327
|
+
self._results.append(
|
|
328
|
+
{
|
|
329
|
+
"input": sample.input,
|
|
330
|
+
"agent_call": agent_call,
|
|
331
|
+
"ground_truth_call": ground_truth_call,
|
|
332
|
+
"result": result,
|
|
333
|
+
"error": None,
|
|
334
|
+
}
|
|
335
|
+
)
|
|
336
|
+
except Exception as e:
|
|
337
|
+
logger.warning(f"Error in processing task: {sample.input}")
|
|
338
|
+
self._results.append(
|
|
339
|
+
{
|
|
340
|
+
"input": sample.input,
|
|
341
|
+
"agent_call": None,
|
|
342
|
+
"ground_truth_call": ground_truth_call,
|
|
343
|
+
"result": 0,
|
|
344
|
+
"error": str(e),
|
|
345
|
+
}
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
agent.reset()
|
|
349
|
+
|
|
350
|
+
f.write(json.dumps(self._results[-1], indent=2) + "\n")
|
|
351
|
+
f.flush()
|
|
352
|
+
|
|
353
|
+
total = len(self._results)
|
|
354
|
+
correct = sum(r["result"] for r in self._results)
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
"total": total,
|
|
358
|
+
"correct": correct,
|
|
359
|
+
"accuracy": correct / total,
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
# Utility functions
|
|
364
|
+
def construct_tool_descriptions(dataset_name: str) -> str:
|
|
365
|
+
r"""Construct tool descriptions from function definitions and
|
|
366
|
+
descriptions."""
|
|
367
|
+
tool_dataset_mapping = {
|
|
368
|
+
"NVDLibrary": "CVECPE",
|
|
369
|
+
"VirusTotal": "VirusTotal",
|
|
370
|
+
"PlacesAPI": "Places",
|
|
371
|
+
"ClimateAPI": "Climate",
|
|
372
|
+
"OTX": "OTX",
|
|
373
|
+
"VirusTotal-NestedCalls": "VT_Multi (Nested)",
|
|
374
|
+
"VirusTotal-ParallelCalls": "VT_Multi (Parallel)",
|
|
375
|
+
"NVDLibrary-NestedCalls": "CVECPE_Multi (Nested)",
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
if dataset_name not in tool_dataset_mapping:
|
|
379
|
+
raise ValueError(
|
|
380
|
+
f"Dataset '{dataset_name}' is not recognized. "
|
|
381
|
+
f"Available datasets: {list(dataset_mapping.keys())}"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# Load the dataset based on the dataset name
|
|
385
|
+
dataset = load_dataset(
|
|
386
|
+
"Nexusflow/Function_Call_Definitions",
|
|
387
|
+
name=tool_dataset_mapping[dataset_name],
|
|
388
|
+
)["train"]
|
|
389
|
+
|
|
390
|
+
# Construct tool descriptions
|
|
391
|
+
tools = [
|
|
392
|
+
NexusTool(tool["function_calls"], tool["descriptions"])
|
|
393
|
+
for tool in dataset
|
|
394
|
+
]
|
|
395
|
+
|
|
396
|
+
# Generate the tool prompt
|
|
397
|
+
tool_prompt = "".join(
|
|
398
|
+
f"Function:\ndef {tool.function_calls}:\n"
|
|
399
|
+
+ "\"\"\"\n"
|
|
400
|
+
+ f"{tool.descriptions}\n"
|
|
401
|
+
+ "\"\"\"\n"
|
|
402
|
+
for tool in tools
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
return tool_prompt
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def construct_prompt(input: str, tools: str) -> str:
|
|
409
|
+
r"Construct prompt from tools and input."
|
|
410
|
+
return TOOL_CALLING_PROMPT.format(tools=tools, input=input)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
# Functions for function call evaluation
|
|
414
|
+
def parse_function_call(
|
|
415
|
+
call: str,
|
|
416
|
+
) -> Tuple[Optional[str], Optional[List[Any]], Optional[Dict[str, Any]]]:
|
|
417
|
+
r"""Parse a function call string to extract the function name,
|
|
418
|
+
positional arguments, and keyword arguments, including
|
|
419
|
+
nested function calls.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
call (str): A string in the format `func(arg1, arg2, kwarg=value)`.
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
tuple: (function_name (str), positional_args (list),
|
|
426
|
+
keyword_args (dict)) or (None, None, None).
|
|
427
|
+
"""
|
|
428
|
+
|
|
429
|
+
def preprocess_input(call: str) -> str:
|
|
430
|
+
r"""Remove formatting like code blocks and whitespace."""
|
|
431
|
+
if call.strip().startswith("```python"):
|
|
432
|
+
call = call.strip().removeprefix("```python").removesuffix("```")
|
|
433
|
+
return textwrap.dedent(call).strip()
|
|
434
|
+
|
|
435
|
+
def evaluate_arg(arg):
|
|
436
|
+
r"""Recursively evaluate arguments, including nested calls."""
|
|
437
|
+
if isinstance(arg, ast.Call):
|
|
438
|
+
# Recursively parse nested calls
|
|
439
|
+
func_name, args, kwargs = parse_function_call(ast.unparse(arg))
|
|
440
|
+
return func_name, args, kwargs
|
|
441
|
+
elif isinstance(
|
|
442
|
+
arg, ast.Constant
|
|
443
|
+
): # Handle literals like numbers, strings, etc.
|
|
444
|
+
return arg.value
|
|
445
|
+
elif isinstance(arg, ast.List): # Handle list literals
|
|
446
|
+
return [evaluate_arg(el) for el in arg.elts]
|
|
447
|
+
elif isinstance(arg, ast.Dict): # Handle dictionary literals
|
|
448
|
+
return {
|
|
449
|
+
evaluate_arg(k): evaluate_arg(v)
|
|
450
|
+
for k, v in zip(arg.keys, arg.values)
|
|
451
|
+
}
|
|
452
|
+
elif isinstance(arg, ast.Tuple): # Handle tuple literals
|
|
453
|
+
return tuple(evaluate_arg(el) for el in arg.elts)
|
|
454
|
+
else:
|
|
455
|
+
return ast.literal_eval(arg) # Safely evaluate other types
|
|
456
|
+
|
|
457
|
+
call = preprocess_input(call)
|
|
458
|
+
parsed_calls = []
|
|
459
|
+
|
|
460
|
+
try:
|
|
461
|
+
# Parse the string into an AST
|
|
462
|
+
parsed_calls = call.split(";")
|
|
463
|
+
for single_call in parsed_calls:
|
|
464
|
+
tree = ast.parse(single_call, mode='eval')
|
|
465
|
+
|
|
466
|
+
# Ensure it's a function call
|
|
467
|
+
if isinstance(tree.body, ast.Call):
|
|
468
|
+
# Extract function name
|
|
469
|
+
if isinstance(
|
|
470
|
+
tree.body.func, ast.Name
|
|
471
|
+
): # Simple function call
|
|
472
|
+
func_name = tree.body.func.id
|
|
473
|
+
elif isinstance(
|
|
474
|
+
tree.body.func, ast.Attribute
|
|
475
|
+
): # Attribute function call
|
|
476
|
+
func_name = (
|
|
477
|
+
f"{tree.body.func.value.id}.{tree.body.func.attr}" # type: ignore[attr-defined]
|
|
478
|
+
)
|
|
479
|
+
else:
|
|
480
|
+
raise ValueError(f"Unsupported function call: {call}")
|
|
481
|
+
|
|
482
|
+
# Extract positional arguments
|
|
483
|
+
args = [evaluate_arg(arg) for arg in tree.body.args]
|
|
484
|
+
|
|
485
|
+
# Extract keyword arguments
|
|
486
|
+
kwargs: Dict[str, Any] = {
|
|
487
|
+
kw.arg: evaluate_arg(kw.value)
|
|
488
|
+
for kw in tree.body.keywords
|
|
489
|
+
if kw.arg is not None
|
|
490
|
+
}
|
|
491
|
+
logger.info("Valid call.")
|
|
492
|
+
return func_name, args, kwargs
|
|
493
|
+
else:
|
|
494
|
+
raise ValueError(f"Not a valid function call: {call}")
|
|
495
|
+
except Exception as e:
|
|
496
|
+
logger.info(f"Error parsing call: {call}, {e}")
|
|
497
|
+
return None, None, None
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def compare_function_calls(agent_call: str, ground_truth_call: str) -> bool:
|
|
501
|
+
r"""Compare the function name and arguments of
|
|
502
|
+
agent_call and ground_truth_call.
|
|
503
|
+
Args:
|
|
504
|
+
agent_call (str): Function call by agent.
|
|
505
|
+
ground_truth_call (str): Ground truth function call.
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
- `True` if the function names and arguments match.
|
|
509
|
+
- `False` otherwise.
|
|
510
|
+
"""
|
|
511
|
+
# Parse both calls
|
|
512
|
+
agent_parsed = parse_function_call(agent_call)
|
|
513
|
+
gt_parsed = parse_function_call(ground_truth_call)
|
|
514
|
+
|
|
515
|
+
if agent_parsed and gt_parsed:
|
|
516
|
+
return agent_parsed == gt_parsed
|
|
517
|
+
else:
|
|
518
|
+
return False
|
camel/datagen/__init__.py
CHANGED
|
@@ -12,6 +12,10 @@
|
|
|
12
12
|
# limitations under the License.
|
|
13
13
|
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
|
|
14
14
|
|
|
15
|
-
from .
|
|
15
|
+
from .cotdatagen import CoTDataGenerator
|
|
16
|
+
from .self_instruct import SelfInstructPipeline
|
|
16
17
|
|
|
17
|
-
__all__ = [
|
|
18
|
+
__all__ = [
|
|
19
|
+
"CoTDataGenerator",
|
|
20
|
+
"SelfInstructPipeline",
|
|
21
|
+
]
|
|
@@ -22,7 +22,7 @@ from camel.agents import ChatAgent
|
|
|
22
22
|
from camel.logger import get_logger
|
|
23
23
|
|
|
24
24
|
# Get a logger for this module
|
|
25
|
-
logger = get_logger('
|
|
25
|
+
logger = get_logger('CoTDataGenerator')
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
class AgentResponse(BaseModel):
|
|
@@ -60,11 +60,17 @@ class VerificationResponse(BaseModel):
|
|
|
60
60
|
)
|
|
61
61
|
|
|
62
62
|
|
|
63
|
-
class
|
|
63
|
+
class CoTDataGenerator:
|
|
64
64
|
r"""Class for generating and managing data through chat agent interactions.
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
|
|
66
|
+
This module implements a sophisticated Chain of Thought data generation
|
|
67
|
+
system that combines several key algorithms to produce high-quality
|
|
68
|
+
reasoning paths. Methods implemented:
|
|
69
|
+
|
|
70
|
+
1. Monte Carlo Tree Search (MCTS)
|
|
71
|
+
2. Binary Search Error Detection
|
|
72
|
+
3. Dual-Agent Verification System
|
|
73
|
+
4. Solution Tree Management
|
|
68
74
|
|
|
69
75
|
Args:
|
|
70
76
|
chat_agent (Optional[ChatAgent]): Optional single agent
|
|
@@ -89,7 +95,7 @@ class O1DataGenerator:
|
|
|
89
95
|
golden_answers: Dict[str, str],
|
|
90
96
|
search_limit: int = 100,
|
|
91
97
|
):
|
|
92
|
-
r"""Initialize the
|
|
98
|
+
r"""Initialize the CoTDataGenerator.
|
|
93
99
|
|
|
94
100
|
This constructor supports both single-agent and dual-agent modes:
|
|
95
101
|
1. Single-agent mode (legacy): Pass a single chat_agent that will be
|
|
@@ -131,7 +137,7 @@ class O1DataGenerator:
|
|
|
131
137
|
self.search_limit = search_limit
|
|
132
138
|
self.solution_tree: Dict[str, Dict[str, Union[str, int]]] = {}
|
|
133
139
|
logger.info(
|
|
134
|
-
"
|
|
140
|
+
"CoTDataGenerator initialized with search_limit=%d", search_limit
|
|
135
141
|
)
|
|
136
142
|
|
|
137
143
|
def get_answer(self, question: str, context: str = "") -> str:
|
|
@@ -203,6 +209,13 @@ class O1DataGenerator:
|
|
|
203
209
|
) -> float:
|
|
204
210
|
r"""Perform Monte Carlo Tree Search to find the best solution.
|
|
205
211
|
|
|
212
|
+
Process:
|
|
213
|
+
a. Selection: Choose promising partial solutions based on previous
|
|
214
|
+
scores
|
|
215
|
+
b. Expansion: Generate new solution steps using the generator agent
|
|
216
|
+
c. Simulation: Evaluate solution quality using similarity scores
|
|
217
|
+
d. Backpropagation: Update solution tree with new findings
|
|
218
|
+
|
|
206
219
|
Args:
|
|
207
220
|
question (str): The question to solve.
|
|
208
221
|
partial_solution (str): The current partial solution.
|
|
@@ -0,0 +1,36 @@
|
|
|
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 .filter import (
|
|
15
|
+
FILTER_REGISTRY,
|
|
16
|
+
FilterFunction,
|
|
17
|
+
InstructionFilter,
|
|
18
|
+
KeywordFilter,
|
|
19
|
+
LengthFilter,
|
|
20
|
+
NonEnglishFilter,
|
|
21
|
+
PunctuationFilter,
|
|
22
|
+
RougeSimilarityFilter,
|
|
23
|
+
)
|
|
24
|
+
from .self_instruct import SelfInstructPipeline
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
'SelfInstructPipeline',
|
|
28
|
+
'InstructionFilter',
|
|
29
|
+
'NonEnglishFilter',
|
|
30
|
+
'PunctuationFilter',
|
|
31
|
+
'RougeSimilarityFilter',
|
|
32
|
+
'FilterFunction',
|
|
33
|
+
'KeywordFilter',
|
|
34
|
+
'LengthFilter',
|
|
35
|
+
'FILTER_REGISTRY',
|
|
36
|
+
]
|
|
@@ -0,0 +1,34 @@
|
|
|
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 .filter_function import (
|
|
15
|
+
FilterFunction,
|
|
16
|
+
KeywordFilter,
|
|
17
|
+
LengthFilter,
|
|
18
|
+
NonEnglishFilter,
|
|
19
|
+
PunctuationFilter,
|
|
20
|
+
RougeSimilarityFilter,
|
|
21
|
+
)
|
|
22
|
+
from .filter_registry import FILTER_REGISTRY
|
|
23
|
+
from .instruction_filter import InstructionFilter
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"LengthFilter",
|
|
27
|
+
"NonEnglishFilter",
|
|
28
|
+
"PunctuationFilter",
|
|
29
|
+
"RougeSimilarityFilter",
|
|
30
|
+
"FilterFunction",
|
|
31
|
+
"KeywordFilter",
|
|
32
|
+
"InstructionFilter",
|
|
33
|
+
"FILTER_REGISTRY",
|
|
34
|
+
]
|