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
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
#!/usr/bin/env python

# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import collections
import copy
import functools
import inspect
import json
import operator
import reprlib
import textwrap
import time
import traceback

import gradio as gr

import erniebot as eb

CUSTOM_FUNC_NAME = "custom_function"
MAX_CONTEXT_LINES_TO_SHOW = 10


def parse_setup_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--port", type=int, default=8073)
    args = parser.parse_args()
    return args


def create_ui_and_launch(args):
    with gr.Blocks(
        title="ERNIE Bot SDK Function Calling Demo", theme=gr.themes.Soft(spacing_size="sm", text_size="md")
    ) as blocks:
        gr.Markdown("# ERNIE Bot SDK函数调用功能演示")
        create_components(functions=get_predefined_functions())

    blocks.queue(api_open=False, concurrency_count=8).launch(server_name="0.0.0.0", server_port=args.port)


def create_components(functions):
    func_name_list = list(map(operator.attrgetter("name"), functions))
    name2function = collections.OrderedDict(zip(func_name_list, functions))
    default_state = {"name2function": name2function, "context": []}
    default_api_type = "qianfan"
    default_model = "ernie-bot"

    state = gr.State(value=default_state)
    auth_state = gr.State(
        value={
            "api_type": default_api_type,
            "ak": "",
            "sk": "",
            "access_token": "",
        }
    )

    with gr.Row():
        with gr.Column(scale=4):
            with gr.Row():
                with gr.Column(scale=1):
                    with gr.Accordion(label="基础配置", open=True):
                        with gr.Group():
                            api_type = gr.Dropdown(
                                label="API Type",
                                info="提供对话能力的后端平台",
                                value=default_api_type,
                                choices=["qianfan", "aistudio"],
                            )
                            access_key = gr.Textbox(
                                label="AK",
                                info="用于访问后端平台的API key或access key ID",
                                type="password",
                                visible=(default_api_type == "qianfan"),
                            )
                            secret_key = gr.Textbox(
                                label="SK",
                                info="用于访问后端平台的secret key或secret access key",
                                type="password",
                                visible=(default_api_type == "qianfan"),
                            )
                            access_token = gr.Textbox(
                                label="Access Token", info="用于访问后端平台的access token", type="password"
                            )
                            ernie_model = gr.Dropdown(
                                label="Model", info="模型类型", value=default_model, choices=["ernie-bot"]
                            )
                    with gr.Accordion(label="高级配置", open=False):
                        with gr.Group():
                            top_p = gr.Slider(
                                label="Top-p",
                                info="控制采样范围,该参数越小生成结果越稳定",
                                value=0.7,
                                minimum=0,
                                maximum=1,
                                step=0.05,
                            )
                            temperature = gr.Slider(
                                label="Temperature",
                                info="控制采样随机性,该参数越小生成结果越稳定",
                                value=0.95,
                                minimum=0.05,
                                maximum=1,
                                step=0.05,
                            )

                with gr.Column(scale=3):
                    context_chatbot = gr.Chatbot(
                        label="对话历史",
                        latex_delimiters=[
                            {"left": "$$", "right": "$$", "display": True},
                            {"left": "$", "right": "$", "display": False},
                        ],
                        bubble_full_width=False,
                    )
                    input_text = gr.Textbox(label="消息内容", value="请问12和16的“魔法运算”结果是多少?", placeholder="请输入...")
                    with gr.Row():
                        send_text_btn = gr.Button("发送消息")
                        regen_btn = gr.Button("重新生成")
                    with gr.Row():
                        recall_btn = gr.Button("撤回消息")
                        clear_btn = gr.Button("重置对话")

            func_call_accord = gr.Accordion(label="函数调用", open=False)
            with func_call_accord:
                chosen_func_names = gr.CheckboxGroup(
                    label="备选函数", value=func_name_list, choices=func_name_list + [CUSTOM_FUNC_NAME]
                )

                with gr.Row():
                    with gr.Tabs():
                        for function in functions:
                            create_function_tab(function)
                        with gr.Tab(label="自定义函数"):
                            custom_func_code = gr.Code(
                                label="定义",
                                value=get_custom_func_def_template(),
                                language="python",
                                interactive=True,
                            )
                            update_func_desc_btn = gr.Button("更新描述")
                            custom_func_desc = JSONCode(
                                label="描述",
                                value=to_pretty_json(get_custom_func_desc_template(), from_json=False),
                                interactive=True,
                            )

                    with gr.Column(scale=1):
                        func_name = gr.Textbox(label="函数名称")
                        func_in_params = JSONCode(label="请求参数")
                        func_out_params = JSONCode(label="响应参数", interactive=False)
                        with gr.Row():
                            call_func_btn = gr.Button("调用函数")
                            send_res_btn = gr.Button("发送调用结果")
                        reset_func_btn = gr.Button("重置函数调用信息")

        with gr.Accordion(label="原始对话上下文信息", open=False):
            raw_context_json = gr.JSON(label=f"最近{MAX_CONTEXT_LINES_TO_SHOW}条消息", scale=1)

    api_type.change(
        update_api_type,
        inputs=[
            auth_state,
            api_type,
        ],
        outputs=[
            auth_state,
            access_key,
            secret_key,
        ],
    ).success(
        reset_conversation,
        inputs=state,
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
        ],
    )
    access_key.change(
        make_state_updater(key="ak", strip=True),
        inputs=[
            auth_state,
            access_key,
        ],
        outputs=auth_state,
    )
    secret_key.change(
        make_state_updater(key="sk", strip=True),
        inputs=[
            auth_state,
            secret_key,
        ],
        outputs=auth_state,
    )
    access_token.change(
        make_state_updater(key="access_token", strip=True),
        inputs=[
            auth_state,
            access_token,
        ],
        outputs=auth_state,
    )

    disable_chat_input_args = {
        "fn": lambda: replicate_gradio_update(6, interactive=False),
        "inputs": None,
        "outputs": [
            input_text,
            clear_btn,
            recall_btn,
            regen_btn,
            send_text_btn,
            send_res_btn,
        ],
        "show_progress": False,
        "queue": False,
    }
    enable_chat_input_args = {
        "fn": lambda: replicate_gradio_update(6, interactive=True),
        "inputs": None,
        "outputs": [
            input_text,
            clear_btn,
            recall_btn,
            regen_btn,
            send_text_btn,
            send_res_btn,
        ],
        "show_progress": False,
        "queue": False,
    }
    input_text.submit(**disable_chat_input_args).then(
        generate_response_for_text,
        inputs=[
            state,
            chosen_func_names,
            auth_state,
            ernie_model,
            input_text,
            top_p,
            temperature,
        ],
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
            func_call_accord,
        ],
        show_progress=False,
    ).then(**enable_chat_input_args)
    send_text_btn.click(**disable_chat_input_args).then(
        generate_response_for_text,
        inputs=[
            state,
            chosen_func_names,
            auth_state,
            ernie_model,
            input_text,
            top_p,
            temperature,
        ],
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
            func_call_accord,
        ],
        show_progress=False,
    ).then(**enable_chat_input_args)
    regen_btn.click(**disable_chat_input_args).then(
        lambda history: (history and history[:-1], gr.update(interactive=False)),
        inputs=context_chatbot,
        outputs=[
            context_chatbot,
            regen_btn,
        ],
        show_progress=False,
        queue=False,
    ).then(
        regenerate_response,
        inputs=[
            state,
            chosen_func_names,
            auth_state,
            ernie_model,
            top_p,
            temperature,
        ],
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
            func_call_accord,
        ],
        show_progress=False,
    ).then(
        **enable_chat_input_args
    )
    recall_btn.click(**disable_chat_input_args).then(
        recall_message,
        inputs=state,
        outputs=[state, context_chatbot, raw_context_json],
        show_progress=False,
    ).then(**enable_chat_input_args)
    clear_btn.click(**disable_chat_input_args).then(
        reset_conversation,
        inputs=state,
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
        ],
    ).then(**enable_chat_input_args)

    chosen_func_names.select(
        try_update_candidates,
        inputs=[
            state,
            chosen_func_names,
            custom_func_code,
            custom_func_desc,
        ],
        outputs=[
            state,
            chosen_func_names,
        ],
        show_progress=False,
    )

    custom_func_code.change(
        remove_old_custom_function,
        inputs=[
            state,
            chosen_func_names,
        ],
        outputs=[
            state,
            chosen_func_names,
        ],
        show_progress=False,
    )
    custom_func_desc.change(
        remove_old_custom_function,
        inputs=[
            state,
            chosen_func_names,
        ],
        outputs=[
            state,
            chosen_func_names,
        ],
        show_progress=False,
    )
    update_func_desc_btn.click(
        update_custom_func_desc,
        inputs=[
            custom_func_code,
            custom_func_desc,
        ],
        outputs=custom_func_desc,
        show_progress=False,
    )

    call_func_btn.click(
        lambda: gr.update(interactive=False),
        outputs=call_func_btn,
        show_progress=False,
        queue=False,
    ).then(
        call_function,
        inputs=[
            state,
            chosen_func_names,
            func_name,
            func_in_params,
        ],
        outputs=func_out_params,
        show_progress=False,
    ).then(
        lambda: gr.update(interactive=True),
        outputs=call_func_btn,
        show_progress=False,
        queue=False,
    )
    send_res_btn.click(**disable_chat_input_args).then(
        generate_response_for_function,
        inputs=[
            state,
            chosen_func_names,
            auth_state,
            ernie_model,
            func_name,
            func_out_params,
            top_p,
            temperature,
        ],
        outputs=[
            state,
            context_chatbot,
            input_text,
            raw_context_json,
            func_name,
            func_in_params,
            func_out_params,
        ],
        show_progress=False,
    ).then(**enable_chat_input_args)
    reset_func_btn.click(
        lambda: (None, None, None),
        outputs=[
            func_name,
            func_in_params,
            func_out_params,
        ],
    )


def create_function_tab(function):
    with gr.Tab(label=function.name):
        with gr.Column():
            gr.Code(label="定义", value=get_source_code(function.func), language="python", interactive=False)
            JSONCode(label="描述", value=to_pretty_json(function.desc, from_json=False), interactive=False)


def make_state_updater(key, *, strip=False):
    def _update_state(state, val):
        if strip:
            val = val.strip()
        state[key] = val
        return state

    return _update_state


def update_api_type(auth_state, api_type):
    auth_state["api_type"] = api_type
    if api_type == "qianfan":
        return auth_state, gr.update(visible=True), gr.update(visible=True)
    elif api_type == "aistudio":
        return auth_state, gr.update(visible=False), gr.update(visible=False)


def generate_response_for_function(
    state,
    candidates,
    auth_config,
    ernie_model,
    func_name,
    func_res,
    top_p,
    temperature,
):
    if text_is_empty(func_name):
        raise gr.Error("函数名称不能为空")
    if func_res is None:
        raise gr.Error("无法获取函数响应参数,请调用函数")
    message = {"role": "function", "name": func_name, "content": to_compact_json(func_res, from_json=True)}
    yield from generate_response(
        state=state,
        candidates=candidates,
        auth_config=auth_config,
        ernie_model=ernie_model,
        message=message,
        top_p=top_p,
        temperature=temperature,
    )


def generate_response_for_text(
    state,
    candidates,
    auth_config,
    ernie_model,
    content,
    top_p,
    temperature,
):
    if text_is_empty(content):
        raise gr.Error("消息内容不能为空")
    content = content.strip().replace("<br>", "")
    message = {"role": "user", "content": content}
    yield from generate_response(
        state=state,
        candidates=candidates,
        auth_config=auth_config,
        ernie_model=ernie_model,
        message=message,
        top_p=top_p,
        temperature=temperature,
    )


def recall_message(state):
    context = state["context"]
    if len(context) < 2:
        raise gr.Error("请至少进行一轮对话")
    context = context[:-2]
    history = extract_history(context)
    state["context"] = context
    return state, history, context[-MAX_CONTEXT_LINES_TO_SHOW:]


def regenerate_response(
    state,
    candidates,
    auth_config,
    ernie_model,
    top_p,
    temperature,
):
    context = state["context"]
    if len(context) < 2:
        raise gr.Error("请至少进行一轮对话")
    context.pop()
    user_message = context.pop()
    yield from generate_response(
        state=state,
        candidates=candidates,
        auth_config=auth_config,
        ernie_model=ernie_model,
        message=user_message,
        top_p=top_p,
        temperature=temperature,
    )


def reset_conversation(state):
    state["context"].clear()
    return state, None, None, None, None, None, None


def generate_response(
    state,
    candidates,
    auth_config,
    ernie_model,
    message,
    top_p,
    temperature,
):
    context = copy.copy(state["context"])
    context.append(message)
    name2function = state["name2function"]
    functions = [name2function[name].desc for name in candidates]
    params = {
        "model": ernie_model,
        "messages": context,
        "top_p": top_p,
        "temperature": temperature,
        "functions": functions,
    }

    try:
        resp_stream = create_chat_completion(
            _config_={k: v for k, v in auth_config.items() if v},
            **params,
            stream=True,
        )
    except eb.errors.TokenUpdateFailedError as e:
        raise gr.Error("鉴权参数无效,请重新填写") from e
    except eb.errors.EBError as e:
        raise gr.Error(f"请求失败。错误信息如下:{str(e)}") from e

    context.append({"role": "assistant", "content": None})
    history = None
    for resp in resp_stream:
        if hasattr(resp, "function_call"):
            function_call = resp.function_call
            func_name = function_call["name"]
            try:
                func_args = to_pretty_json(function_call["arguments"], from_json=True)
            except gr.Error:
                # This is most likely because the model is returning incorrectly
                # formatted JSON. In this case we use the raw string.
                func_args = function_call["arguments"]
            context[-1]["function_call"] = function_call
            assert history is None
            history = extract_history(context)
            state["context"] = context
            yield (
                state,
                history,
                None,
                context[-MAX_CONTEXT_LINES_TO_SHOW:],
                func_name,
                func_args,
                None,
                gr.update(open=True),
            )
            break
        else:
            if history is None:
                history = extract_history(context)
            if context[-1]["content"] is None:
                context[-1]["content"] = ""
            old_content = context[-1]["content"]
            delta = resp.result
            context[-1]["content"] += delta
            for content in stream_output_smoother(
                old_content,
                delta,
            ):
                history[-1][1] = content
                yield (
                    state,
                    history,
                    None,
                    *replicate_gradio_update(5),
                )
            assert history[-1][1] == context[-1]["content"]
    else:
        state["context"] = context
        yield (
            state,
            history,
            None,
            context[-MAX_CONTEXT_LINES_TO_SHOW:],
            *replicate_gradio_update(4),
        )


def extract_history(context):
    history = []
    for round_idx in range(0, len(context), 2):
        user_message = context[round_idx]
        pair = []
        if user_message["role"] == "function":
            function_call_result = to_pretty_json(user_message["content"], from_json=True)
            pair.append(
                f"**【函数调用】** 我调用了函数`{user_message['name']}`,函数的返回结果如下:\n\n```\n{function_call_result}\n```"
            )
        elif user_message["role"] == "user":
            pair.append(user_message["content"])
        else:
            raise gr.Error("消息中的`role`不正确")

        try:
            assistant_message = context[round_idx + 1]
        except IndexError:
            pair.append(None)
        else:
            if "function_call" in assistant_message:
                function_call = assistant_message["function_call"]
                function_call_response = to_pretty_json(function_call["arguments"], from_json=True)
                pair.append(
                    (
                        f"**【函数调用】** {function_call['thoughts']}\n\n"
                        f"我建议调用函数`{function_call['name']}`,传入如下参数:\n\n```\n{function_call_response}\n```"
                    )
                )
            else:
                pair.append(assistant_message["content"])

        assert len(pair) == 2
        history.append(pair)
    return history


def stream_output_smoother(old_content, delta, *, delay=0.03):
    content = old_content
    yield content
    for char in delta:
        content += char
        yield content
        time.sleep(delay)


def try_update_candidates(state, candidates, custom_func_code, custom_func_desc_str):
    if CUSTOM_FUNC_NAME in candidates:
        try:
            custom_function = make_custom_function(custom_func_code, custom_func_desc_str)
        except Exception as e:
            handle_exception(e, f"自定义函数的定义或描述中存在错误,无法将其添加为候选函数。错误信息如下:{str(e)}", raise_=False)
            candidates.remove(CUSTOM_FUNC_NAME)
        else:
            state["name2function"][CUSTOM_FUNC_NAME] = custom_function
    return state, candidates


def remove_old_custom_function(state, candidates):
    state["name2function"].pop(CUSTOM_FUNC_NAME, None)
    if CUSTOM_FUNC_NAME in candidates:
        candidates.remove(CUSTOM_FUNC_NAME)
    return state, candidates


def update_custom_func_desc(custom_func_code, custom_func_desc_str):
    try:
        func = code_to_function(custom_func_code, CUSTOM_FUNC_NAME)
        sig = inspect.signature(func)
        custom_func_desc = json_to_obj(custom_func_desc_str)
        new_params_desc = get_custom_func_desc_template()["parameters"]
        for param in sig.parameters.values():
            name = param.name
            if name in custom_func_desc["parameters"]["properties"]:
                param_desc = custom_func_desc["parameters"]["properties"][name]
            else:
                param_desc = {}
            if param.kind in (param.POSITIONAL_ONLY, param.VAR_POSITIONAL, param.VAR_KEYWORD):
                raise gr.Error("函数中不可包含positional-only、var-positional或var-keyword参数")
            if param.default is not param.empty:
                param_desc["default"] = param.default
            else:
                if "default" in param_desc:
                    del param_desc["default"]
            if param.kind == param.POSITIONAL_OR_KEYWORD and param.default is param.empty:
                if "required" not in new_params_desc:
                    new_params_desc["required"] = []
                new_params_desc["required"].append(name)
            new_params_desc["properties"][name] = param_desc
        custom_func_desc["parameters"] = new_params_desc
    except Exception as e:
        raise gr.Error(f"更新函数描述失败,错误信息如下:{str(e)}") from e
    else:
        return to_pretty_json(custom_func_desc)


def make_custom_function(code, desc_str):
    func = code_to_function(code, CUSTOM_FUNC_NAME)
    if func.__name__ != CUSTOM_FUNC_NAME:
        raise gr.Error(f"在自定义函数的定义中,必须将函数名称设置为{repr(CUSTOM_FUNC_NAME)}")
    desc = json_to_obj(desc_str)
    if desc["name"] != CUSTOM_FUNC_NAME:
        raise gr.Error(f"在自定义函数的描述中,必须将函数名称设置为{repr(CUSTOM_FUNC_NAME)}")
    return make_function(func, desc, name=CUSTOM_FUNC_NAME)


def call_function(state, candidates, func_name, func_args):
    name2function = state["name2function"]
    if text_is_empty(func_name):
        raise gr.Error("函数名称不能为空")
    if func_name not in name2function:
        raise gr.Error(f"函数`{func_name}`不存在")
    if func_name not in candidates:
        raise gr.Error(f"函数`{func_name}`不是候选函数")
    func = name2function[func_name].func
    if text_is_empty(func_args):
        func_args = "{}"
    func_args = json_to_obj(func_args)
    if not isinstance(func_args, dict):
        raise gr.Error(f"无法将{reprlib.repr(func_args)}解析为字典")
    try:
        res = func(**func_args)
    except Exception as e:
        raise gr.Error(f"函数{func_name}调用失败,错误信息如下:{str(e)}") from e
    return to_pretty_json(res, from_json=False)


JSONCode = functools.partial(gr.Code, language="json")

Function = collections.namedtuple("Function", ["name", "func", "desc"])


def get_custom_func_def_template():
    indent = 2
    return f"def {CUSTOM_FUNC_NAME}():\n{' '*indent}# Write your code here"


def get_custom_func_desc_template():
    return {
        "name": CUSTOM_FUNC_NAME,
        "description": "",
        "parameters": {
            "type": "object",
            "properties": {},
        },
        "responses": {
            "type": "object",
            "properties": {},
        },
    }


def get_predefined_functions():
    functions = []

    def magic_op(a, b):
        return {"result": a * b + (a - b)}

    magic_op_desc = {
        "name": "magic_op",
        "description": "计算输入数字经过“魔法运算”得到的结果",
        "parameters": {
            "type": "object",
            "properties": {
                "a": {
                    "type": "integer",
                },
                "b": {
                    "type": "integer",
                },
            },
            "required": [
                "a",
                "b",
            ],
        },
        "responses": {
            "type": "object",
            "properties": {
                "result": {
                    "type": "integer",
                    "description": "“魔法运算”结果",
                },
            },
        },
    }

    functions.append(make_function(magic_op, magic_op_desc))

    def get_contact_info(name, field=None):
        info_dict = {
            "李小明": {
                "age": 31,
                "email": "[email protected]",
            },
            "王刚": {
                "age": 28,
                "email": "[email protected]",
            },
            "张一一": {
                "age": 26,
                "email": "[email protected]",
            },
        }
        info = info_dict[name]
        if field is not None:
            return {"name": name, field: info[field]}
        else:
            return {"name": name, **info}

    get_contact_info_desc = {
        "name": "get_contact_info",
        "description": "获取联系人的个人信息",
        "parameters": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "联系人姓名",
                },
                "field": {
                    "type": "string",
                    "description": "想要获取的字段名称,如果不指定则返回所有字段",
                    "enum": [
                        "age",
                        "email",
                    ],
                },
            },
            "required": [
                "name",
            ],
        },
        "responses": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "姓名",
                },
                "age": {
                    "type": "integer",
                    "description": "年龄",
                    "minimum": 0,
                },
                "email": {
                    "type": "string",
                    "description": "电子邮箱地址",
                    "format": "email",
                },
            },
            "required": [
                "name",
            ],
        },
    }

    functions.append(make_function(get_contact_info, get_contact_info_desc))

    return functions


def code_to_function(code, func_name):
    code = compile(code, "<string>", "exec")
    co_names = code.co_names
    if len(co_names) != 1 or co_names[0] != func_name:
        raise gr.Error(f"只允许定义一个函数,函数名为{repr(func_name)}")
    locals_ = {}
    exec(code, {"__builtins__": {}}, locals_)
    func = locals_[func_name]
    return func


def get_source_code(func):
    code = inspect.getsource(func)
    return textwrap.dedent(code)


def make_function(func, desc, *, name=None):
    if name is None:
        name = func.__name__
    return Function(name=name, func=func, desc=desc)


def create_chat_completion(*args, **kwargs):
    response = eb.ChatCompletion.create(*args, **kwargs)
    return response


def json_to_obj(str_):
    try:
        return json.loads(str_)
    except (TypeError, json.JSONDecodeError) as e:
        raise gr.Error(f"无法以JSON格式解码{reprlib.repr(str_)}") from e


def obj_to_json(obj, **kwargs):
    try:
        return json.dumps(obj, ensure_ascii=False, **kwargs)
    except TypeError as e:
        raise gr.Error(f"无法将{reprlib.repr(obj)}编码为JSON") from e


def to_compact_json(obj, *, from_json=False):
    if from_json:
        obj = json_to_obj(obj)
    return obj_to_json(obj, sort_keys=False, separators=(",", ":"))


def to_pretty_json(obj, *, from_json=False):
    if from_json:
        obj = json_to_obj(obj)
    return obj_to_json(obj, sort_keys=False, indent=2)


def handle_exception(exception, message, *, raise_=False):
    if raise_:
        raise gr.Error(message) from exception
    else:
        traceback.print_exception(type(exception), exception, exception.__traceback__)
        gr.Warning(message)


def replicate_gradio_update(count, /, **kwargs):
    return tuple(gr.update(**kwargs) for _ in range(count))


def text_is_empty(text):
    return text is None or text.strip() == ""


if __name__ == "__main__":
    args = parse_setup_args()
    create_ui_and_launch(args)