-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathall_experiments.py
2144 lines (1881 loc) · 103 KB
/
all_experiments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
1. Test Experiment 1: Evaluate the ability to select the correct API, without assessing parameters.
2. Test Experiment 2: Assess the correct population of primitive data types/enumerations.
3. Test Experiment 3: Evaluate the correctness of system or user inputs.
"""
import json
import os
from collections.abc import Iterable
import random
import time
import re
import openai
import copy
from collections import defaultdict
import logging
import tiktoken
import dashscope
import argparse
import google.generativeai as genai
from generate_shortcut_desc import APIsClass, WFActionsClass, get_identifier2return_value, get_all_shortcuts_paras_that_is_necessary_in_query
from cal_shortcut_len import cal_WFWorkflowActions_len, label_each_WFWorkflowAction_pos_inplace
from all_experiments_prompt import SYSTEM_PROMPT_TEMPLATE, USER_PROMPT_TEMPLATE
SHORTCUT_DATA = os.getenv("SHORTCUT_DATA")
# MODEL_NAME = 'gemini-1.5-pro' # $3.5 / 1M, $10.5 / 1M
# MODEL_NAME = 'qwen2-72b-instruct' # 5 / 1M, 10 / 1M => exchange_rate : 7.1151 => 0.70 / 1M, 1.40 / 1M
# MODEL_NAME = 'deepseek-chat' # $0.14 / 1M, $0.28 / 1M
# MODEL_NAME = 'deepseek-coder' # $0.14 / 1M, $0.28 / 1M
# MODEL_NAME = 'meta-llama/Llama-3-70b-chat-hf' # $1.17 / 1M, $1.17 / 1M
# MODEL_NAME = 'gemini-1.5-flash' # $0.35 / 1M, $1.05 / 1M
# MODEL_NAME = 'qwen2-57b-a14b-instruct' # 3.5 / 1M, 7 / 1M => exchange_rate : 7.1151 => 0.49 / 1M, 0.98 / 1M
# MODEL_NAME = "gpt-3.5-turbo" # $0.50 / 1M, $1.50 / 1M
# MODEL_NAME = "gpt-4o-mini" # $0.15 / 1M, $0.60 / 1M
# MODEL_NAME = 'GLM-4-Air' # 1 / 1M, 1 / 1M => exchange_rate : 7.1151 => 0.14 / 1M, 0.14 / 1M
# https://aimlapi.com/comparisons/llama-3-vs-chatgpt-3-5-comparison
ignore_in_judge_WFWorkflowActionIdentifier_list = [ # Actions not included in the evaluation results
"is.workflow.actions.conditional",
"is.workflow.actions.choosefrommenu",
"is.workflow.actions.repeat.each",
"is.workflow.actions.repeat.count",
"is.workflow.actions.getvariable",
"is.workflow.actions.setvariable",
"is.workflow.actions.appendvariable",
"is.workflow.actions.runworkflow",
"is.workflow.actions.gettext",
"is.workflow.actions.ask"
]
filter_WFWorkflowActionIdentifier_list = [ # Directly excluded: not included in the evaluation results and not used as input for the agent (the agent does not see this comment).
"is.workflow.actions.comment",
"is.workflow.actions.alert"
]
branch_num_2_nlp_desc = { # Map the parameters of `is.workflow.actions.conditional` for model interpretation.
"0": '"less/earlier than"',
"1": '"less than or equal"',
"2": '"greater/later than"',
"3": '"greater than or equal"',
"4": '"is"',
"5": '"is not"',
"8": '"begin with"',
"9": '"end with"',
"99": '"contain"',
"100": '"have value"',
"101": '"do not have any value"',
"999": '"do not contain"',
"1000": '"is after"',
"1001": '"is the most recent"',
"1002": '"is today"',
"1003": '"is between"',
"Contains": '"contains"',
"Equals": '"equals"',
"Is Less Than": '"is less than"',
"Is Greater Than": '"is greater than"'
}
def extract_json(text):
# Match the outermost curly braces and their contents.
pattern = r"\{.*\}"
matches = re.finditer(pattern, text, re.DOTALL)
for match in matches:
try:
# Attempt to parse the matched string as a JSON object.
json_object = json.loads(match.group())
return json.dumps(json_object, indent=2) # Format the output.
except json.JSONDecodeError:
continue
return None
def match_brackets(text):
# Match the outermost curly braces and their contents.
pattern = r"\{.*\}"
matches = re.finditer(pattern, text, re.DOTALL)
for match in matches:
try:
# Try to parse the matched string as a JSON object.
json_object = json.loads(match.group())
return json.dumps(json_object, indent=2) # Format the output.
except json.JSONDecodeError:
continue
return text
class APIBasedAgent:
def __init__(self, all_api_descs_dict):
# Each element is a dictionary: `{'APIName': api_name, 'Description': api_description}`.
self.all_api_descs_dict = all_api_descs_dict
self.all_api_descs_list = [f"{i + 1}. {api_name}. {api_description}" for i,
(api_name, api_description) in enumerate(self.all_api_descs_dict.items())]
self.all_api_descs = "\n".join(self.all_api_descs_list)
self.all_api_names = list(self.all_api_descs_dict.keys())
self.history_actions = []
def set_history_actions(self, history_actions):
self.history_actions = history_actions
self.history_actions = traverse_and_truncate(self.history_actions)
def append_history_actions(self, history_action):
history_action = traverse_and_truncate(self.history_actions)
self.history_actions.append(history_action)
def get_history_action_str(self):
return json.dumps(self.history_actions, indent=2)
def truncate_string(value, max_length=300):
if isinstance(value, str) and len(value) > max_length:
return value[:max_length] + '...'
return value
def traverse_and_truncate(data):
if isinstance(data, dict):
for key, value in data.items():
data[key] = traverse_and_truncate(value)
elif isinstance(data, list):
for i in range(len(data)):
data[i] = traverse_and_truncate(data[i])
else:
data = truncate_string(data)
return data
def get_all_api_info():
"""Retrieve information for all APIs, i.e., a mapping from API names to API descriptions.
"""
# Load all API information from `WFActions.json`.
WFActions_path = os.path.join(SHORTCUT_DATA, "is.workflow.actions",
"WorkflowKit.framework/Versions/A/Resources/WFActions.json")
wf_actions_instance = WFActionsClass(WFActions_path)
my_WFActions_path = os.path.join(
SHORTCUT_DATA, "is.workflow.actions", "my_WFActions.json")
wf_actions_instance.WFActions_dicts.update(
json.load(open(my_WFActions_path, "r")))
all_api2info_WF, all_api2paraname2paratype_WF, all_api2parasummary_WF = wf_actions_instance.all_api2desc(
need_api2paraname2paratype=True, need_api2parasummary=True)
# Load all API information from the app.
# succ_api_json_path = os.path.join(
# SHORTCUT_DATA, "4_success_api_json_filter.json")
# fail_api_json_path = os.path.join(
# SHORTCUT_DATA, "4_fail_api_json_filter.json")
# API_instance = APIsClass(
# succ_api_json_path, fail_api_json_path)
api_json_path = os.path.join(
SHORTCUT_DATA, "4_api_json_filter.json")
API_instance = APIsClass(api_json_path)
all_api2info_from_app, all_api2paraname2paratype_from_app, _ = API_instance.all_api2desc(
need_api2paraname2paratype=True, need_api2parasummary=True)
"""Mapping of all APIs to their information."""
all_api2info = all_api2info_WF.copy()
all_api2info.update(all_api2info_from_app)
"""Mapping of all APIs to parameter names to parameter types (including default values)."""
all_api2paraname2paratype = all_api2paraname2paratype_WF.copy()
all_api2paraname2paratype.update(all_api2paraname2paratype_from_app)
return all_api2info, all_api2paraname2paratype
def sample_more_APIs(all_api2info, number, exclude_APIs=[]):
"""Randomly select `number` APIs from all available APIs.
"""
if number <= 0:
return []
all_APIs = list(all_api2info.keys())
# Compute the difference set.
all_APIs = list(set(all_APIs) - set(exclude_APIs))
sampled_APIs = random.sample(all_APIs, number)
return sampled_APIs
def remove_wf_serialization_types(data):
if isinstance(data, dict):
remove_keys = []
for key, value in data.items():
if key == "WFSerializationType":
remove_keys.append(key)
else:
remove_wf_serialization_types(value)
for key in remove_keys:
del data[key]
elif isinstance(data, list):
for item in data:
remove_wf_serialization_types(item)
def count_and_clean_aggrandizements(data, type_counts=None):
"""Count the distinct values for the key `"Type"` in all dictionaries and the frequency of each value.
After counting, delete dictionaries with keys `WFCoercionVariableAggrandizement`, `WFDateFormatVariableAggrandizement`,
and `WFUnitVariableAggrandizement`. If `Aggrandizements` is empty after these deletions, also remove `Aggrandizements`.
"""
if type_counts is None:
type_counts = defaultdict(int)
if isinstance(data, dict):
keys_to_remove = []
for key, value in data.items():
if key == "Aggrandizements" and isinstance(value, list):
new_list = []
for item in value:
if isinstance(item, dict) and "Type" in item:
type_counts[item["Type"]] += 1
if item["Type"] not in ["WFCoercionVariableAggrandizement", "WFDateFormatVariableAggrandizement", "WFUnitVariableAggrandizement"]:
new_list.append(item)
else:
new_list.append(item)
data[key] = new_list
if not data[key]:
keys_to_remove.append(key)
else:
count_and_clean_aggrandizements(value, type_counts)
for key in keys_to_remove:
del data[key]
elif isinstance(data, list):
for item in data:
count_and_clean_aggrandizements(item, type_counts)
return type_counts
def replace_and_sort_attachments(data):
"""Find all dictionaries where the values include both the keys `string` and `attachmentsByRange`.
Replace all instances of `` in `string` with `${ValueXX}`,
where XX is a sequential number starting from 1.
Then, replace all `attachmentsByRange` keys with `ValueXX`.
Note that you first need to sort `attachmentsByRange` keys numerically based on the number XX1 in keys like `{XX1,XX2}`.
"""
def process_internal(data):
if "string" in data and "attachmentsByRange" in data:
# Replace  with ${ValueXX} in "string"
value_index = 1
data["string"] = re.sub(
r"", lambda _: f"${{Value{value_index}}}", data["string"])
value_index += 1
# Sort attachmentsByRange by the first number in the key
sorted_attachments = sorted(data["attachmentsByRange"].items(
), key=lambda item: int(re.search(r'\{(\d+),', item[0]).group(1)))
# Create a new dictionary for sorted attachments with new keys
new_attachments = {}
for idx, (key, value) in enumerate(sorted_attachments):
new_key = f"Value{idx + 1}"
new_attachments[new_key] = value
data["attachmentsByRange"] = new_attachments
for key, value in data.items():
if isinstance(value, (dict, list)):
replace_and_sort_attachments(value)
if isinstance(data, dict):
process_internal(data)
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
replace_and_sort_attachments(item)
return data
categorie2num_dict = {
"Productivity & Utilities": 0,
"Health & Fitness": 1,
"Entertainment & Media": 2,
"Lifestyle & Social": 3,
"Education & Reference": 4,
"Business & Finance": 5,
"Development & API": 6,
"Home & Smart Devices": 7
}
def evaluate_experiment(shortcuts_list, print_or_not = True):
"""Evaluation of Question 1 focuses solely on whether the correct API was selected, without considering the parameters.
Each element is a dictionary:{
"URL": URL,
"query": log_query,
"api_names": log_api_names,
"api_descs": log_api_descs,
"aseqs": aseqs,
"bseqs": bseqs,
"cur_input_token_count": cur_input_token_count,
"cur_output_token_count": cur_output_token_count,
"cur_input_cost": cur_input_cost,
"cur_output_cost": cur_output_cost,
"cur_total_cost": cur_total_cost
}
"""
if print_or_not:
print("Begin evaluating Experiment 1: focus only on whether the correct API was selected, ignoring the parameters.")
with open(os.path.join(SHORTCUT_DATA, f"generated_success_categories.json"), "r") as f:
generated_success_categories = json.load(f)
aseq_res_list = []
bseq_res_list = []
"""
1. <=1
2. (1, 5]
3. (5, 15]
4. (15, 30]
"""
for cur_shortcut_dict in shortcuts_list:
URL = cur_shortcut_dict["URL"]
aseqs = cur_shortcut_dict["aseqs"] # Actual actions
aseq_len = cal_WFWorkflowActions_len(aseqs, URL)
bseqs = cur_shortcut_dict["bseqs"] # Generated actions, corresponding one-to-one with `aseqs`.
all_api_names = cur_shortcut_dict["api_names"] # All APIs available to the agent
true_api_names = []
for aseq in aseqs:
true_api_names.append(aseq["WFWorkflowActionIdentifier"])
label_each_WFWorkflowAction_pos_inplace(aseqs, URL)
for aseq, bseq in zip(aseqs, bseqs):
WFWorkflowActionIdentifier = aseq["WFWorkflowActionIdentifier"]
if WFWorkflowActionIdentifier in filter_WFWorkflowActionIdentifier_list:
continue
if WFWorkflowActionIdentifier in ignore_in_judge_WFWorkflowActionIdentifier_list:
continue
aseq_res_list.append(
{"URL": URL, "WFWorkflowActionIdentifier": WFWorkflowActionIdentifier, "len_aseq": aseq_len})
if "pos" in aseq:
aseq_res_list[-1]["pos"] = aseq["pos"] # `pos` refers to the position of the current action within the current shortcut.
aseq_res_list[-1]["all_api_names"] = all_api_names
aseq_res_list[-1]["true_api_names"] = true_api_names
if bseq["state"] == "json_error" or ((bseq["state"] == "generated_by_agent" or bseq["state"] == "corrected_by_model") and (isinstance(bseq["aseq"], Iterable) and "WFWorkflowActionIdentifier" not in bseq["aseq"])):
bseq_res_list.append(
{"URL": URL, "WFWorkflowActionIdentifier": None, "len_aseq": aseq_len})
continue
if isinstance(bseq["aseq"], Iterable):
WFWorkflowActionIdentifier_pred = bseq["aseq"]["WFWorkflowActionIdentifier"]
else:
WFWorkflowActionIdentifier_pred = None
bseq_res_list.append(
{"URL": URL, "WFWorkflowActionIdentifier": WFWorkflowActionIdentifier_pred, "len_aseq": aseq_len})
# Calculate the overall accuracy of `aseq_res_list` and `bseq_res_list`, as well as the accuracy within each of the four interval ranges.
correct_num, all_num = 0, 0
correct_num_list = [0, 0, 0, 0]
all_num_list = [0, 0, 0, 0]
categories_correct_num = [0] * len(categorie2num_dict)
categories_all_num = [0] * len(categorie2num_dict)
# The x-axis represents the action's position in the shortcut, while the y-axis represents accuracy. Each model is represented by a separate line.
correct_num_every_len_level2, all_num_every_len_level2 = {}, {}
correct_num_every_len_level3, all_num_every_len_level3 = {}, {}
correct_num_every_len_level4, all_num_every_len_level4 = {}, {}
# The x-axis represents different models, and the y-axis represents accuracy.
# The bar chart displays five intervals for each bar: (0,5], (5,10], (10,15], (15,20], and (20,+),
# indicating the number of APIs available to the agent.
correct_num_api_nums = [0] * 5
all_num_api_nums = [0] * 5
hall_numerator = [0] * 5 # The API selected by the model is not among the APIs available to the agent.
percentage_numerator = [0] * 5 # The location of the APIs favored by the model.
percentage_denominator = [0] * 5 # The positions of APIs preferred by the model.
for aseq_dict, bseq_dict in zip(aseq_res_list, bseq_res_list):
URL = aseq_dict["URL"]
if aseq_dict["WFWorkflowActionIdentifier"] == bseq_dict["WFWorkflowActionIdentifier"]:
correct_num += 1
if aseq_dict["len_aseq"] <= 1:
correct_num_list[0] += 1
elif 1 < aseq_dict["len_aseq"] <= 5:
correct_num_list[1] += 1
if 'pos' in aseq_dict:
correct_num_every_len_level2[aseq_dict["pos"]] = correct_num_every_len_level2.get(aseq_dict["pos"], 0) + 1
elif 5 < aseq_dict["len_aseq"] <= 15:
correct_num_list[2] += 1
if 'pos' in aseq_dict:
correct_num_every_len_level3[aseq_dict["pos"]] = correct_num_every_len_level3.get(aseq_dict["pos"], 0) + 1
elif 15 < aseq_dict["len_aseq"] <= 30:
correct_num_list[3] += 1
if 'pos' in aseq_dict:
correct_num_every_len_level4[aseq_dict["pos"]] = correct_num_every_len_level4.get(aseq_dict["pos"], 0) + 1
if len(aseq_dict["all_api_names"]) <= 5:
correct_num_api_nums[0] += 1
elif 5 < len(aseq_dict["all_api_names"]) <= 10:
correct_num_api_nums[1] += 1
elif 10 < len(aseq_dict["all_api_names"]) <= 15:
correct_num_api_nums[2] += 1
elif 15 < len(aseq_dict["all_api_names"]) <= 20:
correct_num_api_nums[3] += 1
else:
correct_num_api_nums[4] += 1
if URL in generated_success_categories:
category = generated_success_categories[URL]['category']
if category in categorie2num_dict:
categories_correct_num[categorie2num_dict[category]] += 1
else:
if len(aseq_dict["all_api_names"]) <= 5:
if bseq_dict["WFWorkflowActionIdentifier"] not in aseq_dict["all_api_names"]:
hall_numerator[0] += 1
else:
chose_pos = aseq_dict["all_api_names"].index(bseq_dict["WFWorkflowActionIdentifier"])
percentage_numerator[0] += chose_pos / len(aseq_dict["all_api_names"])
percentage_denominator[0] += 1
elif 5 < len(aseq_dict["all_api_names"]) <= 10:
if bseq_dict["WFWorkflowActionIdentifier"] not in aseq_dict["all_api_names"]:
hall_numerator[1] += 1
else:
chose_pos = aseq_dict["all_api_names"].index(bseq_dict["WFWorkflowActionIdentifier"])
percentage_numerator[1] += chose_pos / len(aseq_dict["all_api_names"])
percentage_denominator[1] += 1
elif 10 < len(aseq_dict["all_api_names"]) <= 15:
if bseq_dict["WFWorkflowActionIdentifier"] not in aseq_dict["all_api_names"]:
hall_numerator[2] += 1
else:
chose_pos = aseq_dict["all_api_names"].index(bseq_dict["WFWorkflowActionIdentifier"])
percentage_numerator[2] += chose_pos / len(aseq_dict["all_api_names"])
percentage_denominator[2] += 1
elif 15 < len(aseq_dict["all_api_names"]) <= 20:
if bseq_dict["WFWorkflowActionIdentifier"] not in aseq_dict["all_api_names"]:
hall_numerator[3] += 1
else:
chose_pos = aseq_dict["all_api_names"].index(bseq_dict["WFWorkflowActionIdentifier"])
percentage_numerator[3] += chose_pos / len(aseq_dict["all_api_names"])
percentage_denominator[3] += 1
else:
if bseq_dict["WFWorkflowActionIdentifier"] not in aseq_dict["all_api_names"]:
hall_numerator[4] += 1
else:
chose_pos = aseq_dict["all_api_names"].index(bseq_dict["WFWorkflowActionIdentifier"])
percentage_numerator[4] += chose_pos / len(aseq_dict["all_api_names"])
percentage_denominator[4] += 1
if aseq_dict["len_aseq"] <= 1:
all_num_list[0] += 1
elif 1 < aseq_dict["len_aseq"] <= 5:
all_num_list[1] += 1
if 'pos' in aseq_dict:
all_num_every_len_level2[aseq_dict["pos"]] = all_num_every_len_level2.get(aseq_dict["pos"], 0) + 1
elif 5 < aseq_dict["len_aseq"] <= 15:
all_num_list[2] += 1
if 'pos' in aseq_dict:
all_num_every_len_level3[aseq_dict["pos"]] = all_num_every_len_level3.get(aseq_dict["pos"], 0) + 1
elif 15 < aseq_dict["len_aseq"] <= 30:
all_num_list[3] += 1
if 'pos' in aseq_dict:
all_num_every_len_level4[aseq_dict["pos"]] = all_num_every_len_level4.get(aseq_dict["pos"], 0) + 1
if len(aseq_dict["all_api_names"]) <= 5:
all_num_api_nums[0] += 1
elif 5 < len(aseq_dict["all_api_names"]) <= 10:
all_num_api_nums[1] += 1
elif 10 < len(aseq_dict["all_api_names"]) <= 15:
all_num_api_nums[2] += 1
elif 15 < len(aseq_dict["all_api_names"]) <= 20:
all_num_api_nums[3] += 1
else:
all_num_api_nums[4] += 1
all_num += 1
if URL in generated_success_categories:
category = generated_success_categories[URL]['category']
if category in categorie2num_dict:
categories_all_num[categorie2num_dict[category]] += 1
if print_or_not:
accuracy = correct_num / all_num
print(f"Overall accuracy: {correct_num} / {all_num} = {accuracy * 100:.2f}")
for i, correct_num in enumerate(correct_num_list):
print(f"Length within the interval{i + 1}的准确率:{correct_num} / {all_num_list[i]} = {correct_num / all_num_list[i] * 100:.2f}")
return correct_num, all_num, correct_num_list, all_num_list, categories_correct_num, categories_all_num, \
correct_num_every_len_level2, all_num_every_len_level2, \
correct_num_every_len_level3, all_num_every_len_level3, \
correct_num_every_len_level4, all_num_every_len_level4, \
correct_num_api_nums, all_num_api_nums, \
hall_numerator, percentage_numerator, percentage_denominator
def judge_if_equal(value1, value2):
"""Determine if two numbers are equal."""
if isinstance(value1, bool):
value1 = int(value1)
if isinstance(value2, bool):
value2 = int(value2)
# Only integer, float, and string types remain.
# If one number is a float, attempt to convert the other number to a float for comparison.
if isinstance(value1, float) or isinstance(value2, float):
try:
value1 = float(value1)
value2 = float(value2)
except:
return False
# Only integer, float, and string types remain.
# If one number is an integer, attempt to convert the other number to an integer for comparison. If the conversion fails, convert both numbers to strings and compare them.
if isinstance(value1, int) or isinstance(value2, int):
try:
value1 = int(value1)
value2 = int(value2)
except:
value1 = str(value1)
value2 = str(value2)
return value1 == value2
def evaluate_experiment2_basic_para(
shortcuts_list,
all_shortcuts_paras_that_is_necessary_in_query,
check_intersection_of_query_and_para_necessary,
print_or_not = True,
):
"""Evaluation of Question 2: Verify if the basic parameters are correctly populated.
Each element of `shortcuts_list` is a dictionary: {
"URL": URL,
"query": log_query,
"api_names": log_api_names,
"api_descs": log_api_descs,
"aseqs": aseqs,
"bseqs": bseqs,
"cur_input_token_count": cur_input_token_count,
"cur_output_token_count": cur_output_token_count,
"cur_input_cost": cur_input_cost,
"cur_output_cost": cur_output_cost,
"cur_total_cost": cur_total_cost
}
"""
all_shortcuts_paras_that_is_necessary_in_query
""""https://www.icloud.com/shortcuts/e6fa8dd9e012484bb85c9967f0b83f02": {
"1": {
"WFURLActionURL": "https://experience.regmovies.com/unlimited"
}
},
"""
check_intersection_of_query_and_para_necessary
"""
"https://www.icloud.com/shortcuts/87cd41f5c4694a248fab11085214d04e": {
"query": "I would like to rename the icon of an app using the App Store search term '提供的输入'. Please use 'App更改图标名称(重写版)V1.0 by SKY 修复:无法制作多个图标,优化用户ti yan' as the text, and prompt me with the message '输入要更改名称图标的app' to input the app name. After selecting the app from the list, continue by prompting me with '选择选择一个app' to choose the proper app from the App Store. After that, set the id and continue the process, making sure to ask me for the description file name with the prompt '请输入描述文件的名称:', the app name with the prompt '请输入App的名称:', and the description file remark with the prompt '描述文件备注'. Also, base64 encode the selected photos every 76 characters, get a UID from 'https://1024tools.com/uuid', and ensure you set the name of the final file as 'Label.mobileconfig'. Finally, open the generated URL.",
"api_desc": "is.workflow.actions.base64encode(WFEncodeMode: Enum = \"Encode\", WFBase64LineBreakMode: Enum = \"Every 76 Characters\", WFInput: WFVariablePickerParameter(Object)) -> Base64 Encoded: (WFStringContentItem(Object) or public.data(Object))\nParameters:\n WFEncodeMode: Mode. The value of this Enum must be one of the following values (The text in parentheses describes the value): \"Encode\", \"Decode\".\n WFBase64LineBreakMode: Line Breaks. The value of this Enum must be one of the following values (The text in parentheses describes the value): \"None\", \"Every 64 Characters\", \"Every 76 Characters\". This value depends on the value of WFEncodeMode. This parameter is only valid when the value of \"WFEncodeMode\" is \"Encode\".\n WFInput: Input.\nReturn Value:\n Base64 Encoded: \nDescription:\n Base64 Encode: Encodes or decodes text or files using Base64 encoding.\nParameterSummary: ${WFEncodeMode} ${WFInput} with base64\n",
"necessary_paras": {
"29": {
"WFHTTPBodyType": "Form",
"WFHTTPMethod": "POST"
},
"34": {
"WFBase64LineBreakMode": "Every 76 Characters"
}
},
"significant_paras": {
"29": {
"WFHTTPBodyType": {
"WFHTTPBodyType": "Essential parameter",
"reason": "The user explicitly mentioned the need to prompt for the description file name, app name, and description file remark, which indicates the necessity of setting the HTTP body type as 'Form' to handle form values."
},
"WFHTTPMethod": {
"WFHTTPMethod": "Essential parameter",
"reason": "The user specified the usage of the App Store search term, which involves selecting and downloading content, implying the need for an HTTP method like 'POST' to interact with the server."
}
},
"34": {
"WFBase64LineBreakMode": {
"WFBase64LineBreakMode": "Essential parameter",
"reason": "The WFBase64LineBreakMode parameter is explicitly mentioned in the user query as part of the required actions."
}
}
}
"""
"""Correct only if both the API prediction and parameter population are accurate."""
if print_or_not:
print("Begin evaluating Experiment 2: focus solely on whether the basic parameters are correctly populated.")
aseq_res_list = []
bseq_res_list = []
for cur_shortcut_dict in shortcuts_list:
URL = cur_shortcut_dict["URL"]
aseqs = cur_shortcut_dict["aseqs"]
aseq_len = cal_WFWorkflowActions_len(aseqs, URL)
bseqs = cur_shortcut_dict["bseqs"]
for pos, (aseq, bseq) in enumerate(zip(aseqs, bseqs)): # Ensure that `pos` corresponds to the position in the original shortcut.
WFWorkflowActionIdentifier = aseq["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters = aseq["WFWorkflowActionParameters"]
if WFWorkflowActionIdentifier in filter_WFWorkflowActionIdentifier_list:
continue
if WFWorkflowActionIdentifier in ignore_in_judge_WFWorkflowActionIdentifier_list:
continue
aseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": WFWorkflowActionIdentifier,
"WFWorkflowActionParameters": WFWorkflowActionParameters,
"len_aseq": aseq_len
})
if bseq["state"] == "json_error":
bseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
continue
elif (bseq["state"] == "generated_by_agent" or bseq["state"] == "corrected_by_model") and (isinstance(bseq["aseq"], Iterable) and ("WFWorkflowActionIdentifier" not in bseq["aseq"] or "WFWorkflowActionParameters" not in bseq["aseq"])):
if "WFWorkflowActionIdentifier" not in bseq["aseq"] and "WFWorkflowActionParameters" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
elif "WFWorkflowActionIdentifier" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": bseq["aseq"]["WFWorkflowActionParameters"],
"len_aseq": aseq_len
})
elif "WFWorkflowActionParameters" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": bseq["aseq"]["WFWorkflowActionIdentifier"],
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
continue
if isinstance(bseq["aseq"], Iterable):
WFWorkflowActionIdentifier_pred = bseq["aseq"]["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters_pred = bseq["aseq"]["WFWorkflowActionParameters"]
else:
WFWorkflowActionIdentifier_pred = None
WFWorkflowActionParameters_pred = None
bseq_res_list.append({
"URL": URL,
"pos": pos,
"WFWorkflowActionIdentifier": WFWorkflowActionIdentifier_pred,
"WFWorkflowActionParameters": WFWorkflowActionParameters_pred,
"len_aseq": aseq_len
})
# Calculate the overall basic parameter accuracy for `aseq_res_list` and `bseq_res_list`, as well as the accuracy within each of the four interval ranges.
# The denominator for this calculation is the count of all `significant_paras` with type "Essential parameter" in `check_intersection_of_query_and_para_necessary`.
para_correct_num, para_all_num = 0, 0
para_correct_num_list = [0, 0, 0, 0]
para_all_num_list = [0, 0, 0, 0]
for aseq_dict, bseq_dict in zip(aseq_res_list, bseq_res_list):
URL = aseq_dict["URL"]
pos = aseq_dict["pos"]
len_aseq = aseq_dict["len_aseq"]
WFWorkflowActionIdentifier = aseq_dict["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters = aseq_dict["WFWorkflowActionParameters"]
WFWorkflowActionIdentifier_pred = bseq_dict["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters_pred = bseq_dict["WFWorkflowActionParameters"]
if WFWorkflowActionIdentifier == WFWorkflowActionIdentifier_pred: # Calculate accuracy based only on the correct parameter population for predictions.
for para_name, para_value in WFWorkflowActionParameters.items(): # Iterate through all parameters of the current action.
if URL in check_intersection_of_query_and_para_necessary and str(pos) in check_intersection_of_query_and_para_necessary[URL]["significant_paras"]:
necessary_paras_dict = check_intersection_of_query_and_para_necessary[URL]["significant_paras"][str(
pos)]
# Only parameters marked as "Essential parameter" are considered correct.
if para_name in necessary_paras_dict and necessary_paras_dict[para_name][para_name] == "Essential parameter":
para_all_num += 1
if len_aseq <= 1:
para_all_num_list[0] += 1
elif 1 < len_aseq <= 5:
para_all_num_list[1] += 1
elif 5 < len_aseq <= 15:
para_all_num_list[2] += 1
elif 15 < len_aseq <= 30:
para_all_num_list[3] += 1
if WFWorkflowActionParameters_pred == None:
continue
if para_name in WFWorkflowActionParameters_pred and judge_if_equal(para_value, WFWorkflowActionParameters_pred[para_name]):
para_correct_num += 1
if len_aseq <= 1:
para_correct_num_list[0] += 1
elif 1 < len_aseq <= 5:
para_correct_num_list[1] += 1
elif 5 < len_aseq <= 15:
para_correct_num_list[2] += 1
elif 15 < len_aseq <= 30:
para_correct_num_list[3] += 1
if print_or_not:
accuracy = para_correct_num / para_all_num
print(f"Overall basic parameter accuracy: {para_correct_num} / {para_all_num} = {accuracy * 100:.2f}")
for i, correct_num in enumerate(para_correct_num_list):
if para_all_num_list[i] != 0:
print(f"Basic parameter accuracy for lengths within interval {i + 1}: {correct_num} / {
para_all_num_list[i]} = {correct_num / para_all_num_list[i] * 100:.2f}")
else:
print(f"Basic parameter accuracy for lengths within interval {i + 1}: Denominator value is 0.")
return para_correct_num, para_all_num, para_correct_num_list, para_all_num_list
def is_return_value_type(value):
"""Determine if a number is in the form of a return value or a system input, i.e., if the value is a dictionary."""
if not isinstance(value, dict):
return 0
if "Value" not in value:
return 0
Value = value["Value"]
if isinstance(Value, dict):
if "Type" in Value and Value["Type"] == "ActionOutput":
return 1
if "Type" in Value and Value["Type"] in ["ExtensionInput"]:
return 2
elif "Type" in Value and Value["Type"] in ["CurrentDate"]:
return 3
elif "Type" in Value and Value["Type"] in ["Clipboard"]:
return 4
elif "Type" in Value and Value["Type"] in ["DeviceDetails"]:
return 5
elif "Type" in Value and Value["Type"] in ["Ask"]:
return 6
return 0
def judge_if_return_value_equal(value1, value2):
"""Determine if two return values are equal."""
# If the data types are different, return `False` immediately.
if not isinstance(value1, dict) or not isinstance(value2, dict):
return False, 'format_error'
if "Value" not in value1 or "Value" not in value2:
return False, 'format_error'
Value1 = value1["Value"]
Value2 = value2["Value"]
if not isinstance(Value1, dict) or not isinstance(Value2, dict):
return False, 'format_error'
if "Type" in Value1 and "Type" in Value2 and Value1["Type"] == Value2["Type"]:
if Value1["Type"] == "ActionOutput":
UUID_Value1, UUID_Value2 = None, None
OutputName_Value1, OutputName_Value2 = None, None
if "OutputUUID" in Value1:
UUID_Value1 = Value1["OutputUUID"]
if "OutputUUID" in Value2:
UUID_Value2 = Value2["OutputUUID"]
if "OutputName" in Value1:
OutputName_Value1 = Value1["OutputName"]
if "OutputName" in Value2:
OutputName_Value2 = Value2["OutputName"]
if UUID_Value1 and UUID_Value2 and OutputName_Value1 and OutputName_Value2:
if UUID_Value1 == UUID_Value2 or OutputName_Value1 == OutputName_Value2:
return True, None
else:
return False, 'value_error' # The provided value is incorrect.
elif UUID_Value1 and UUID_Value2:
if UUID_Value1 == UUID_Value2:
return True, None
else:
return False, 'value_error' # The provided value is incorrect.
elif OutputName_Value1 and OutputName_Value2:
if OutputName_Value1 == OutputName_Value2:
return True, None
else:
return False, 'value_error' # The provided value is incorrect.
return False, 'value_error' # No value provided.
if Value1["Type"] in ["ExtensionInput", "CurrentDate", "Clipboard", "DeviceDetails", "Ask"]:
return True, None
else:
return False, 'format_error'
return False, 'format_error'
def cal_return_para_pos(shortcuts_list):
"""When an action uses the output of a previous action, I want to know the position of the referenced action.
"""
para_pos = {}
for cur_shortcut_dict in shortcuts_list:
URL = cur_shortcut_dict["URL"]
aseqs = cur_shortcut_dict["aseqs"]
for aseq in aseqs:
WFWorkflowActionIdentifier = aseq["WFWorkflowActionIdentifier"]
if WFWorkflowActionIdentifier in filter_WFWorkflowActionIdentifier_list:
continue
if WFWorkflowActionIdentifier in ignore_in_judge_WFWorkflowActionIdentifier_list:
continue
WFWorkflowActionParameters = aseq["WFWorkflowActionParameters"]
for para_name, para_value in WFWorkflowActionParameters.items():
pass
def evaluate_experiment2_return_para(
shortcuts_list, print_or_not = True):
"""Evaluation of Question 2: Check if the basic parameters are correctly populated.
Each element of `shortcuts_list` is a dictionary: {
"URL": URL,
"query": log_query,
"api_names": log_api_names,
"api_descs": log_api_descs,
"aseqs": aseqs,
"bseqs": bseqs,
"cur_input_token_count": cur_input_token_count,
"cur_output_token_count": cur_output_token_count,
"cur_input_cost": cur_input_cost,
"cur_output_cost": cur_output_cost,
"cur_total_cost": cur_total_cost
}
"""
aseq_res_list = []
bseq_res_list = []
for cur_shortcut_dict in shortcuts_list:
URL = cur_shortcut_dict["URL"]
aseqs = cur_shortcut_dict["aseqs"]
aseq_len = cal_WFWorkflowActions_len(aseqs, URL)
bseqs = cur_shortcut_dict["bseqs"]
for pos, (aseq, bseq) in enumerate(zip(aseqs, bseqs)):
WFWorkflowActionIdentifier = aseq["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters = aseq["WFWorkflowActionParameters"]
if WFWorkflowActionIdentifier in filter_WFWorkflowActionIdentifier_list:
continue
if WFWorkflowActionIdentifier in ignore_in_judge_WFWorkflowActionIdentifier_list:
continue
aseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": WFWorkflowActionIdentifier,
"WFWorkflowActionParameters": WFWorkflowActionParameters,
"len_aseq": aseq_len
})
if bseq["state"] == "json_error":
bseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
continue
elif (bseq["state"] == "generated_by_agent" or bseq["state"] == "corrected_by_model") and (isinstance(bseq["aseq"], Iterable) and ("WFWorkflowActionIdentifier" not in bseq["aseq"] or "WFWorkflowActionParameters" not in bseq["aseq"])):
if "WFWorkflowActionIdentifier" not in bseq["aseq"] and "WFWorkflowActionParameters" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
elif "WFWorkflowActionIdentifier" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": None,
"WFWorkflowActionParameters": bseq["aseq"]["WFWorkflowActionParameters"],
"len_aseq": aseq_len
})
elif "WFWorkflowActionParameters" not in bseq["aseq"]:
bseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": bseq["aseq"]["WFWorkflowActionIdentifier"],
"WFWorkflowActionParameters": None,
"len_aseq": aseq_len
})
continue
if isinstance(bseq["aseq"], Iterable):
WFWorkflowActionIdentifier_pred = bseq["aseq"]["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters_pred = bseq["aseq"]["WFWorkflowActionParameters"]
else:
WFWorkflowActionIdentifier_pred = None
WFWorkflowActionParameters_pred = None
bseq_res_list.append({
"URL": URL,
"WFWorkflowActionIdentifier": WFWorkflowActionIdentifier_pred,
"WFWorkflowActionParameters": WFWorkflowActionParameters_pred,
"len_aseq": aseq_len
})
# Calculate the overall accuracy of return value parameter population for `aseq_res_list` and `bseq_res_list`, as well as the accuracy within each of the four interval ranges.
return_para_correct_num, return_para_all_num = 0, 0
return_para_correct_num_list = [0, 0, 0, 0]
return_para_all_num_list = [0, 0, 0, 0]
return_para_nopred_num_list = [0, 0, 0, 0] # Number of parameters with no predictions.
return_para_formaterror_num_list = [0, 0, 0, 0] # Parameters with the correct names but incorrect types or formats.
return_para_chooseerror_num_list = [0, 0, 0, 0] # Parameters with the correct names but incorrect selected values.
for aseq_dict, bseq_dict in zip(aseq_res_list, bseq_res_list):
URL = aseq_dict["URL"]
len_aseq = aseq_dict["len_aseq"]
WFWorkflowActionIdentifier = aseq_dict["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters = aseq_dict["WFWorkflowActionParameters"]
WFWorkflowActionIdentifier_pred = bseq_dict["WFWorkflowActionIdentifier"]
WFWorkflowActionParameters_pred = bseq_dict["WFWorkflowActionParameters"]
if WFWorkflowActionIdentifier == WFWorkflowActionIdentifier_pred:
"""If the parameter was not predicted, it counts as incorrect. If it was predicted but incorrect, it also counts as incorrect."""
for para_name, para_value in WFWorkflowActionParameters.items():
if is_return_value_type(para_value) == 1:
return_para_all_num += 1
if len_aseq <= 1:
return_para_all_num_list[0] += 1
elif 1 < len_aseq <= 5:
return_para_all_num_list[1] += 1
elif 5 < len_aseq <= 15:
return_para_all_num_list[2] += 1
elif 15 < len_aseq <= 30:
return_para_all_num_list[3] += 1
if WFWorkflowActionParameters_pred == None or para_name not in WFWorkflowActionParameters_pred:
if len_aseq <= 1:
return_para_nopred_num_list[0] += 1
elif 1 < len_aseq <= 5:
return_para_nopred_num_list[1] += 1
elif 5 < len_aseq <= 15:
return_para_nopred_num_list[2] += 1
elif 15 < len_aseq <= 30:
return_para_nopred_num_list[3] += 1
continue
equal_or_not, error_reason = judge_if_return_value_equal(para_value, WFWorkflowActionParameters_pred[para_name])
if equal_or_not:
return_para_correct_num += 1
if len_aseq <= 1:
return_para_correct_num_list[0] += 1
elif 1 < len_aseq <= 5:
return_para_correct_num_list[1] += 1
elif 5 < len_aseq <= 15:
return_para_correct_num_list[2] += 1
elif 15 < len_aseq <= 30:
return_para_correct_num_list[3] += 1
else:
if error_reason == 'format_error':
if len_aseq <= 1:
return_para_formaterror_num_list[0] += 1
elif 1 < len_aseq <= 5:
return_para_formaterror_num_list[1] += 1
elif 5 < len_aseq <= 15:
return_para_formaterror_num_list[2] += 1
elif 15 < len_aseq <= 30:
return_para_formaterror_num_list[3] += 1
elif error_reason == 'value_error':
if len_aseq <= 1:
return_para_chooseerror_num_list[0] += 1
elif 1 < len_aseq <= 5:
return_para_chooseerror_num_list[1] += 1
elif 5 < len_aseq <= 15:
return_para_chooseerror_num_list[2] += 1
elif 15 < len_aseq <= 30:
return_para_chooseerror_num_list[3] += 1