camel-ai 0.2.15a0__py3-none-any.whl → 0.2.17__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 (95) hide show
  1. camel/__init__.py +1 -1
  2. camel/agents/chat_agent.py +18 -4
  3. camel/agents/multi_hop_generator_agent.py +85 -0
  4. camel/agents/programmed_agent_instruction.py +148 -0
  5. camel/benchmarks/__init__.py +13 -1
  6. camel/benchmarks/apibank.py +565 -0
  7. camel/benchmarks/apibench.py +500 -0
  8. camel/benchmarks/gaia.py +4 -4
  9. camel/benchmarks/nexus.py +518 -0
  10. camel/benchmarks/ragbench.py +333 -0
  11. camel/bots/__init__.py +1 -1
  12. camel/bots/discord/__init__.py +26 -0
  13. camel/bots/discord/discord_app.py +384 -0
  14. camel/bots/discord/discord_installation.py +64 -0
  15. camel/bots/discord/discord_store.py +160 -0
  16. camel/configs/__init__.py +3 -0
  17. camel/configs/anthropic_config.py +17 -15
  18. camel/configs/internlm_config.py +60 -0
  19. camel/data_collector/base.py +5 -5
  20. camel/data_collector/sharegpt_collector.py +2 -2
  21. camel/datagen/__init__.py +6 -2
  22. camel/datagen/{o1datagen.py → cotdatagen.py} +19 -6
  23. camel/datagen/self_instruct/__init__.py +36 -0
  24. camel/datagen/self_instruct/filter/__init__.py +34 -0
  25. camel/datagen/self_instruct/filter/filter_function.py +216 -0
  26. camel/datagen/self_instruct/filter/filter_registry.py +56 -0
  27. camel/datagen/self_instruct/filter/instruction_filter.py +81 -0
  28. camel/datagen/self_instruct/self_instruct.py +393 -0
  29. camel/datagen/self_instruct/templates.py +382 -0
  30. camel/datahubs/huggingface.py +12 -2
  31. camel/datahubs/models.py +2 -3
  32. camel/embeddings/mistral_embedding.py +5 -1
  33. camel/embeddings/openai_compatible_embedding.py +6 -1
  34. camel/embeddings/openai_embedding.py +5 -1
  35. camel/interpreters/e2b_interpreter.py +5 -1
  36. camel/loaders/__init__.py +2 -0
  37. camel/loaders/apify_reader.py +5 -1
  38. camel/loaders/chunkr_reader.py +5 -1
  39. camel/loaders/firecrawl_reader.py +0 -30
  40. camel/loaders/panda_reader.py +337 -0
  41. camel/logger.py +11 -5
  42. camel/messages/__init__.py +10 -4
  43. camel/messages/conversion/conversation_models.py +5 -0
  44. camel/messages/func_message.py +30 -22
  45. camel/models/__init__.py +2 -0
  46. camel/models/anthropic_model.py +6 -23
  47. camel/models/azure_openai_model.py +1 -2
  48. camel/models/cohere_model.py +13 -1
  49. camel/models/deepseek_model.py +5 -1
  50. camel/models/gemini_model.py +15 -2
  51. camel/models/groq_model.py +5 -1
  52. camel/models/internlm_model.py +143 -0
  53. camel/models/mistral_model.py +19 -8
  54. camel/models/model_factory.py +3 -0
  55. camel/models/nemotron_model.py +5 -1
  56. camel/models/nvidia_model.py +5 -1
  57. camel/models/openai_model.py +5 -1
  58. camel/models/qwen_model.py +5 -1
  59. camel/models/reka_model.py +5 -1
  60. camel/models/reward/__init__.py +2 -0
  61. camel/models/reward/nemotron_model.py +5 -1
  62. camel/models/reward/skywork_model.py +88 -0
  63. camel/models/samba_model.py +5 -1
  64. camel/models/togetherai_model.py +5 -1
  65. camel/models/yi_model.py +5 -1
  66. camel/models/zhipuai_model.py +5 -1
  67. camel/schemas/openai_converter.py +5 -1
  68. camel/storages/graph_storages/nebula_graph.py +89 -20
  69. camel/storages/graph_storages/neo4j_graph.py +138 -0
  70. camel/synthetic_datagen/source2synth/data_processor.py +373 -0
  71. camel/synthetic_datagen/source2synth/models.py +68 -0
  72. camel/synthetic_datagen/source2synth/user_data_processor_config.py +73 -0
  73. camel/toolkits/__init__.py +4 -0
  74. camel/toolkits/arxiv_toolkit.py +20 -3
  75. camel/toolkits/dappier_toolkit.py +196 -0
  76. camel/toolkits/function_tool.py +61 -61
  77. camel/toolkits/google_scholar_toolkit.py +9 -0
  78. camel/toolkits/meshy_toolkit.py +5 -1
  79. camel/toolkits/notion_toolkit.py +1 -1
  80. camel/toolkits/openbb_toolkit.py +869 -0
  81. camel/toolkits/search_toolkit.py +91 -5
  82. camel/toolkits/stripe_toolkit.py +5 -1
  83. camel/toolkits/twitter_toolkit.py +24 -16
  84. camel/types/__init__.py +4 -2
  85. camel/types/enums.py +34 -1
  86. camel/types/openai_types.py +6 -4
  87. camel/types/unified_model_type.py +5 -0
  88. camel/utils/__init__.py +2 -0
  89. camel/utils/commons.py +104 -19
  90. camel/utils/token_counting.py +3 -3
  91. {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.17.dist-info}/METADATA +160 -177
  92. {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.17.dist-info}/RECORD +94 -69
  93. {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.17.dist-info}/WHEEL +1 -1
  94. camel/bots/discord_app.py +0 -138
  95. {camel_ai-0.2.15a0.dist-info → camel_ai-0.2.17.dist-info}/LICENSE +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