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,565 @@
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 sys
21
+ from pathlib import Path
22
+ from typing import Any, Dict, List, Literal, Optional
23
+
24
+ import numpy as np
25
+ from rouge import Rouge
26
+ from tqdm import tqdm
27
+
28
+ from camel.agents import ChatAgent
29
+ from camel.benchmarks.base import BaseBenchmark
30
+ from camel.messages import BaseMessage
31
+ from camel.utils import download_github_subdirectory
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ # Add current folder to sys.path to enable relative import
36
+ current_folder = os.getcwd()
37
+ if current_folder not in sys.path:
38
+ sys.path.append(current_folder)
39
+
40
+
41
+ def process_messages(
42
+ chat_history: List[Dict[str, Any]],
43
+ prompt: str,
44
+ ) -> List[Dict[str, str]]:
45
+ """
46
+ Processes chat history into a structured format for further use.
47
+
48
+ Args:
49
+ chat_history (List[Dict[str, Any]):
50
+ A list of dictionaries representing the chat history.
51
+ prompt (str): A propmt to be set as the system message.
52
+
53
+ Returns:
54
+ List[Dict[str, str]]: A list of dictionaries representing
55
+ the processed messages, where each dictionary has:
56
+ - 'role': The role of the message ('system', 'user', or 'assistant').
57
+ - 'content': The content of the message, including formatted
58
+ API responses when applicable.
59
+ """
60
+ messages = [{'role': 'system', 'content': prompt}]
61
+ for item in chat_history:
62
+ role_map = {'User': 'user', 'AI': 'assistant', 'API': 'system'}
63
+ chat_role = role_map.get(
64
+ item['role'], 'unknown'
65
+ ) # default role to 'unknown'
66
+ if item['role'] == 'API':
67
+ chat_content = '[{}({})] Response: {}'.format(
68
+ item['api_name'],
69
+ ', '.join(
70
+ [
71
+ '{}=\'{}\''.format(k, v)
72
+ for k, v in item['param_dict'].items()
73
+ ]
74
+ ),
75
+ str(item['result']['output']),
76
+ )
77
+ else:
78
+ chat_content = item['text']
79
+ messages.append({'role': chat_role, 'content': chat_content})
80
+ return messages
81
+
82
+
83
+ class APIBankBenchmark(BaseBenchmark):
84
+ r"""API-Bank Benchmark adapted from `API-Bank:
85
+ A Comprehensive Benchmark for Tool-Augmented LLMs`
86
+ <https://github.com/AlibabaResearch/DAMO-ConvAI/tree/main/api-bank>.
87
+
88
+ Args:
89
+ save_to (str): The file to save the results.
90
+ processes (int, optional): The number of processes to use.
91
+ (default: :obj:`1`)
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ save_to: str,
97
+ processes: int = 1,
98
+ ):
99
+ r"""Initialize the APIBank benchmark.
100
+
101
+ Args:
102
+ save_to (str): The file to save the results.
103
+ processes (int, optional): The number of processes to use for
104
+ parallel processing. (default: :obj:`1`)
105
+ """
106
+ # Predefine data_dir for better import management
107
+ super().__init__("apibank", "api_bank", save_to, processes)
108
+ self._data: Dict[str, List[APIBankSample]] = dict() # type: ignore[assignment]
109
+
110
+ def download(self):
111
+ r"""Download APIBank dataset and code from Github."""
112
+
113
+ repo = "AlibabaResearch/DAMO-ConvAI"
114
+ subdir = "api-bank"
115
+ data_dir = self.data_dir
116
+
117
+ download_github_subdirectory(repo, subdir, data_dir)
118
+
119
+ sys.path.insert(0, self.data_dir)
120
+ logger.info("Download completed.")
121
+
122
+ def load(self, level: str, force_download: bool = False): # type: ignore[override]
123
+ r"""Load the APIBank Benchmark dataset.
124
+
125
+ Args:
126
+ level (str): Level to run benchmark on.
127
+ force_download (bool, optional): Whether to
128
+ force download the data.
129
+ """
130
+ if force_download:
131
+ logger.info("Force downloading data.")
132
+ self.download()
133
+
134
+ if level == "level-1":
135
+ file_path = Path("api_bank/lv1-lv2-samples/level-1-given-desc")
136
+ elif level == 'level-2':
137
+ file_path = Path("api_bank/lv1-lv2-samples/level-2-toolsearcher")
138
+ jsonl_files = [
139
+ f for f in os.listdir(file_path) if f.endswith('.jsonl')
140
+ ]
141
+ for file in tqdm(jsonl_files, desc="Processing files"):
142
+ history = []
143
+ with open(file_path / file, 'r') as f:
144
+ for line in f:
145
+ history.append(json.loads(line))
146
+ samples = APIBankSample.from_chat_history(history)
147
+ self._data[file.rsplit('.', 1)[0]] = samples
148
+
149
+ # Change import to relative import in the downloaded python files
150
+ def process_files(folder_path, replacements):
151
+ r"""Replace absolute imports in downloaded files with
152
+ relative import."""
153
+ for file in os.listdir(folder_path):
154
+ if file.endswith(".py"):
155
+ file_path = os.path.join(folder_path, file)
156
+ try:
157
+ with open(file_path, "r", encoding="utf-8") as file:
158
+ content = file.read()
159
+
160
+ original_content = content
161
+
162
+ for pattern, replacement in replacements:
163
+ content = re.sub(pattern, replacement, content)
164
+
165
+ if content != original_content:
166
+ with open(
167
+ file_path, "w", encoding="utf-8"
168
+ ) as file:
169
+ file.write(content)
170
+ logger.info(f"Updated file: {file_path}")
171
+
172
+ except Exception as e:
173
+ logger.info(f"Error processing file {file_path}: {e}")
174
+
175
+ api_bank_folder = "api_bank"
176
+ apis_folder = os.path.join(api_bank_folder, "apis")
177
+
178
+ apis_replacements = [
179
+ (r"from apis.api", "from .api"),
180
+ (r"from apis import", "from .api import"),
181
+ ]
182
+
183
+ api_bank_replacements = [
184
+ (r"from apis", "from .apis"),
185
+ (r"from api_call_extraction", "from .api_call_extraction"),
186
+ (r"f'{basename}", r"f'api_bank.{basename}"),
187
+ ]
188
+
189
+ process_files(apis_folder, apis_replacements)
190
+ process_files(api_bank_folder, api_bank_replacements)
191
+
192
+ def run( # type: ignore[override, return]
193
+ self,
194
+ agent: ChatAgent,
195
+ level: Literal["level-1", "level-2"],
196
+ api_test_enabled=True,
197
+ randomize: bool = False,
198
+ subset: Optional[int] = None,
199
+ ) -> Dict[str, Any]:
200
+ r"""Run the benchmark.
201
+
202
+ Args:
203
+ agent (ChatAgent): The agent to run the
204
+ benchmark.
205
+ level (Literal['level-1', 'level-2']):
206
+ The level to run the benchmark on.
207
+ randomize (bool, optional): Whether to
208
+ randomize the data.
209
+ api_test_enabled (bool): Whether to test
210
+ API calling (`True`) or response (`False`)
211
+ (default: :obj:`False`)
212
+ subset (Optional[int], optional):
213
+ The subset of data to run.
214
+ (default: :obj:`None`)
215
+
216
+ Returns:
217
+ Dict[str, Any]: The results of the benchmark.
218
+ """
219
+ logger.info(f"Running APIBench benchmark on {level}.")
220
+ self.load(level)
221
+ datas = self._data
222
+
223
+ # Shuffle and subset data if necessary
224
+ if randomize:
225
+ randomized_items = list(datas.items())
226
+ random.shuffle(randomized_items)
227
+ datas = dict(randomized_items)
228
+ if subset:
229
+ datas = dict(list(datas.items())[:subset])
230
+
231
+ logger.info(f"Number of tasks: {len(datas)}")
232
+
233
+ # Initialize results storage
234
+ self._results = []
235
+
236
+ # The following code are adapted from the evaluator
237
+ # from the original repo:
238
+ tool_search_enabled = level == "level-2"
239
+ dialog_test_enabled = not api_test_enabled
240
+ total_api_calls, correct_api_calls, rougel_scores = 0, 0, []
241
+
242
+ with open(self.save_to, "w") as f:
243
+ for test in tqdm(datas, desc="Running"):
244
+ samples = self._data[test]
245
+ evaluator = Evaluator(samples) # type: ignore[arg-type]
246
+
247
+ for sample_id in evaluator.get_all_sample_ids():
248
+ # Process sample and generate response
249
+ sample = evaluator.dataset[sample_id]
250
+
251
+ if (
252
+ sample.ground_truth['role'] == 'API'
253
+ and api_test_enabled
254
+ ):
255
+ if tool_search_enabled:
256
+ _, chat_history = evaluator.get_model_input(
257
+ sample_id
258
+ )
259
+ api_descriptions = evaluator.get_api_description(
260
+ 'ToolSearcher'
261
+ )
262
+ else:
263
+ api_descriptions, chat_history = (
264
+ evaluator.get_model_input(sample_id)
265
+ )
266
+ messages = process_messages(
267
+ chat_history, API_CALL_PROMPT + api_descriptions
268
+ )
269
+ model_output = agent_call(messages, agent)
270
+ api_call = get_api_call(model_output)
271
+
272
+ # Evaluate API call
273
+ if api_call:
274
+ try:
275
+ correct, model_output_result = (
276
+ evaluator.evaluate(sample_id, api_call)
277
+ )
278
+ except AssertionError as e:
279
+ if 'The API name is not correct.' not in str(
280
+ e
281
+ ):
282
+ raise e
283
+ logging.info('AssertionError: {}'.format(e))
284
+ correct = False
285
+ else:
286
+ model_output_result = 'No API call found'
287
+ correct = False
288
+ if correct:
289
+ correct_api_calls += 1
290
+ logging.info(
291
+ 'Correct API call: {} Ground truth: {}'.format(
292
+ api_call, sample.ground_truth
293
+ )
294
+ )
295
+ else:
296
+ logging.info(
297
+ 'Incorrect model output: {} Result: {} \
298
+ Ground truth: {} File: {} Sample ID: {} \
299
+ Messages: {}'.format(
300
+ model_output.replace('\n', ' '),
301
+ model_output_result,
302
+ sample.ground_truth,
303
+ test,
304
+ sample_id,
305
+ messages[1:],
306
+ )
307
+ )
308
+ total_api_calls += 1
309
+ self._results.append(
310
+ {
311
+ 'Role': 'API',
312
+ 'Model_output': model_output,
313
+ 'Model_output_result': model_output_result,
314
+ 'Ground_truth': sample.ground_truth,
315
+ 'Test': test,
316
+ 'Correct': correct,
317
+ }
318
+ )
319
+ f.write(json.dumps(self._results[-1], indent=2) + "\n")
320
+
321
+ elif (
322
+ sample.ground_truth['role'] == 'AI'
323
+ and dialog_test_enabled
324
+ ):
325
+ # Process sample and generate response
326
+ api_descriptions, chat_history = (
327
+ evaluator.get_model_input(sample_id)
328
+ )
329
+
330
+ messages = process_messages(
331
+ chat_history, RESPONSE_PROMPT + api_descriptions
332
+ )
333
+ model_output = agent_call(messages, agent)
334
+
335
+ # Evaluate model response
336
+ if model_output:
337
+ score = evaluator.evaluate(sample_id, model_output)
338
+ else:
339
+ score = 0
340
+ rougel_scores.append(score)
341
+ if score < 0.2:
342
+ logging.info(
343
+ 'Low score: {} Score: {} Ground truth: {} \
344
+ Test: {} Sample ID: {} \
345
+ Messages: {}'.format(
346
+ model_output.replace('\n', ' '),
347
+ score,
348
+ sample.ground_truth,
349
+ test,
350
+ sample_id,
351
+ messages[1:],
352
+ )
353
+ )
354
+
355
+ self._results.append(
356
+ {
357
+ 'Role': 'AI',
358
+ 'Model_output': model_output,
359
+ 'Score': score,
360
+ 'Ground_truth': sample.ground_truth,
361
+ 'Test': test,
362
+ }
363
+ )
364
+ f.write(json.dumps(self._results[-1], indent=2) + "\n")
365
+
366
+ f.flush()
367
+
368
+ if api_test_enabled:
369
+ return {
370
+ 'total': total_api_calls,
371
+ 'correct': correct_api_calls,
372
+ "accuracy": correct_api_calls / total_api_calls
373
+ if total_api_calls
374
+ else 0,
375
+ }
376
+ elif dialog_test_enabled:
377
+ return {'Dialog_score': np.mean(rougel_scores)}
378
+
379
+
380
+ # The following code are migrated from the original repo:
381
+ # https://github.com/AlibabaResearch/DAMO-ConvAI/tree/main/api-bank
382
+ def agent_call(messages: List[Dict], agent: ChatAgent):
383
+ r"""Add messages to agent memory and get response."""
384
+ for i, msg in enumerate(messages):
385
+ if msg['role'] == 'user':
386
+ message = BaseMessage.make_user_message(
387
+ role_name="CAMEL User", content=msg['content']
388
+ )
389
+ elif msg['role'] == 'assistant':
390
+ message = BaseMessage.make_assistant_message(
391
+ role_name="CAMEL Assistant", content=msg['content']
392
+ )
393
+ elif msg['role'] == 'system':
394
+ message = BaseMessage.make_assistant_message(
395
+ role_name="System", content=msg['content']
396
+ )
397
+ else:
398
+ raise ValueError(f"Unrecognized role: {msg['role']}")
399
+
400
+ if i == len(messages) - 1:
401
+ break
402
+ agent.record_message(message)
403
+
404
+ response = agent.step(message)
405
+ model_output = response.msgs[0].content
406
+ agent.reset()
407
+ return model_output
408
+
409
+
410
+ def calculate_rouge_l_score(reference, hypothesis):
411
+ r"""Calculate rouge l score between hypothesis and reference."""
412
+ rouge = Rouge()
413
+ scores = rouge.get_scores(hypothesis, reference)
414
+ rouge_l_score = scores[0]['rouge-l']['f']
415
+ return rouge_l_score
416
+
417
+
418
+ def get_api_call(model_output):
419
+ r"""Parse api call from model output."""
420
+ api_call_pattern = r"\[(\w+)\((.*)\)\]"
421
+ api_call_pattern = re.compile(api_call_pattern)
422
+ match = api_call_pattern.search(model_output)
423
+ if match:
424
+ return match.group(0)
425
+ else:
426
+ return None
427
+
428
+
429
+ class APIBankSample:
430
+ r"""APIBank sample used to load the datasets."""
431
+
432
+ def __init__(self, chat_history, apis, ground_truth):
433
+ self.chat_history = chat_history
434
+ self.apis = apis
435
+ self.ground_truth = ground_truth
436
+
437
+ def __repr__(self):
438
+ return 'Sample(chat_history={}, apis={}, ground_truth={})'.format(
439
+ self.chat_history, self.apis, self.ground_truth
440
+ )
441
+
442
+ @classmethod
443
+ def from_chat_history(cls, chat_history):
444
+ apis = set()
445
+ api_positions = []
446
+ for i, item in enumerate(chat_history):
447
+ if item['role'] == 'API':
448
+ apis.add(item['api_name'])
449
+ api_positions.append(i)
450
+
451
+ samples = []
452
+ for i in api_positions:
453
+ sample = cls(chat_history[:i], apis, chat_history[i])
454
+ samples.append(sample)
455
+ sample = cls(chat_history[: i + 1], apis, chat_history[i + 1])
456
+ samples.append(sample)
457
+
458
+ return samples
459
+
460
+
461
+ class Evaluator:
462
+ r"""Evaluator for APIBank benchmark."""
463
+
464
+ def __init__(self, samples: List[APIBankSample]):
465
+ # Place holder for import as the import
466
+ # only works after the files have been downloaded
467
+ try:
468
+ from api_bank.tool_manager import ( # type: ignore[import-not-found]
469
+ ToolManager,
470
+ )
471
+ except Exception as e:
472
+ logger.info(f"{e}, Module will be imported after download.")
473
+ self.dataset = samples
474
+ self.sample_ids = list(range(len(self.dataset)))
475
+ os.chdir("api_bank")
476
+ self.tool_manager = ToolManager("apis")
477
+ os.chdir("..")
478
+
479
+ def get_all_sample_ids(self):
480
+ return self.sample_ids
481
+
482
+ def get_api_description(self, api_name):
483
+ return self.tool_manager.get_api_description(api_name)
484
+
485
+ def get_model_input(self, sample_id: int):
486
+ sample = self.dataset[sample_id]
487
+ apis = sample.apis
488
+ chat_history = sample.chat_history
489
+ api_descriptions = []
490
+ for api_name in apis:
491
+ api_descriptions.append(
492
+ self.tool_manager.get_api_description(api_name)
493
+ )
494
+ api_description = '\n'.join(api_descriptions)
495
+ return api_description, chat_history
496
+
497
+ def evaluate(self, sample_id, model_output):
498
+ try:
499
+ from api_bank.api_call_extraction import ( # type: ignore[import-not-found]
500
+ parse_api_call,
501
+ )
502
+ except Exception as e:
503
+ logger.info(f"{e}, Module will be imported after download.")
504
+ sample = self.dataset[sample_id]
505
+ ground_truth = sample.ground_truth
506
+ if ground_truth['role'] == 'API':
507
+ api_name, param_dict = parse_api_call(model_output)
508
+ if api_name != ground_truth['api_name']:
509
+ return False, 'API Name Mismatch: {} vs {}'.format(
510
+ api_name, ground_truth['api_name']
511
+ )
512
+ try:
513
+ result = self.tool_manager.api_call(api_name, **param_dict)
514
+ except Exception as e:
515
+ return False, str(e)
516
+ api = self.tool_manager.init_tool(api_name)
517
+ try:
518
+ correct = api.check_api_call_correctness(
519
+ result, ground_truth['result']
520
+ )
521
+ except KeyError:
522
+ correct = False
523
+ result = 'KeyError' + str(result)
524
+ return correct, result
525
+ elif ground_truth['role'] == 'AI':
526
+ score = calculate_rouge_l_score(ground_truth['text'], model_output)
527
+ return round(score, 4)
528
+
529
+
530
+ API_CALL_PROMPT = '''
531
+ Based on the given API description and the existing \
532
+ conversation history 1..t, please generate the API request \
533
+ that the AI should call in step t+1 and output it in the \
534
+ format of [ApiName(key1='value1', key2='value2', ...)], \
535
+ replace the ApiName with the actual API name, and \
536
+ replace the key and value with the actual parameters. \
537
+ Your output should start with a square bracket "[" \
538
+ and end with a square bracket "]". Do not output any \
539
+ other explanation or prompt or the result of the API call in your output.
540
+ This year is 2023.
541
+ Input:
542
+ User: [User's utterence]
543
+ AI: [AI's utterence]
544
+
545
+ Expected output:
546
+ [ApiName(key1='value1', key2='value2', ...)]
547
+
548
+ API descriptions:
549
+ '''
550
+
551
+ RESPONSE_PROMPT = '''
552
+ Based on the given API description and the existing \
553
+ conversation history 1..t, please generate the next \
554
+ dialog that the AI should response after the API call t.
555
+ This year is 2023.
556
+ Input:
557
+ User: [User's utterence]
558
+ AI: [AI's utterence]
559
+ [ApiName(key1='value1', key2='value2', …)]
560
+
561
+ Expected output:
562
+ AI: [AI's utterence]
563
+
564
+ API descriptions:
565
+ '''