Team Ai
Apppublic

LsmyLover/mindsearch_github

sourceHugging Facebsd-3-clauseupdated 2y agoView on Hugging Face
0likes
app.py156 linesDownload Raw Back to root
1 2 3import json4import os5 6import gradio as gr7import requests8from lagent.schema import AgentStatusCode9from class_registry.auto_register import AutoRegister10os.system("python -m mindsearch.app --lang cn --model_format internlm_silicon &")11 12PLANNER_HISTORY = []13SEARCHER_HISTORY = []14 15 16def rst_mem(history_planner: list, history_searcher: list):17    '''18    Reset the chatbot memory.19    '''20    history_planner = []21    history_searcher = []22    if PLANNER_HISTORY:23        PLANNER_HISTORY.clear()24    return history_planner, history_searcher25 26 27def format_response(gr_history, agent_return):28    if agent_return['state'] in [29            AgentStatusCode.STREAM_ING, AgentStatusCode.ANSWER_ING30    ]:31        gr_history[-1][1] = agent_return['response']32    elif agent_return['state'] == AgentStatusCode.PLUGIN_START:33        thought = gr_history[-1][1].split('```')[0]34        if agent_return['response'].startswith('```'):35            gr_history[-1][1] = thought + '\n' + agent_return['response']36    elif agent_return['state'] == AgentStatusCode.PLUGIN_END:37        thought = gr_history[-1][1].split('```')[0]38        if isinstance(agent_return['response'], dict):39            gr_history[-1][40                1] = thought + '\n' + f'```json\n{json.dumps(agent_return["response"], ensure_ascii=False, indent=4)}\n```'  # noqa: E50141    elif agent_return['state'] == AgentStatusCode.PLUGIN_RETURN:42        assert agent_return['inner_steps'][-1]['role'] == 'environment'43        item = agent_return['inner_steps'][-1]44        gr_history.append([45            None,46            f"```json\n{json.dumps(item['content'], ensure_ascii=False, indent=4)}\n```"47        ])48        gr_history.append([None, ''])49    return50 51 52def predict(history_planner, history_searcher):53 54    def streaming(raw_response):55        for chunk in raw_response.iter_lines(chunk_size=8192,56                                             decode_unicode=False,57                                             delimiter=b'\n'):58            if chunk:59                decoded = chunk.decode('utf-8')60                if decoded == '\r':61                    continue62                if decoded[:6] == 'data: ':63                    decoded = decoded[6:]64                elif decoded.startswith(': ping - '):65                    continue66                response = json.loads(decoded)67                yield (response['response'], response['current_node'])68 69    global PLANNER_HISTORY70    PLANNER_HISTORY.append(dict(role='user', content=history_planner[-1][0]))71    new_search_turn = True72 73    url = 'http://localhost:8002/solve'74    headers = {'Content-Type': 'application/json'}75    data = {'inputs': PLANNER_HISTORY}76    raw_response = requests.post(url,77                                 headers=headers,78                                 data=json.dumps(data),79                                 timeout=20,80                                 stream=True)81 82    for resp in streaming(raw_response):83        agent_return, node_name = resp84        if node_name:85            if node_name in ['root', 'response']:86                continue87            agent_return = agent_return['nodes'][node_name]['detail']88            if new_search_turn:89                history_searcher.append([agent_return['content'], ''])90                new_search_turn = False91            format_response(history_searcher, agent_return)92            if agent_return['state'] == AgentStatusCode.END:93                new_search_turn = True94            yield history_planner, history_searcher95        else:96            new_search_turn = True97            format_response(history_planner, agent_return)98            if agent_return['state'] == AgentStatusCode.END:99                PLANNER_HISTORY = agent_return['inner_steps']100            yield history_planner, history_searcher101    return history_planner, history_searcher102 103 104with gr.Blocks() as demo:105    gr.HTML("""<h1 align="center">MindSearch Gradio Demo</h1>""")106    gr.HTML("""<p style="text-align: center; font-family: Arial, sans-serif;">MindSearch is an open-source AI Search Engine Framework with Perplexity.ai Pro performance. You can deploy your own Perplexity.ai-style search engine using either closed-source LLMs (GPT, Claude) or open-source LLMs (InternLM2.5-7b-chat).</p>""")107    gr.HTML("""108    <div style="text-align: center; font-size: 16px;">109        <a href="https://github.com/InternLM/MindSearch" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">  GitHub</a>110        <a href="https://arxiv.org/abs/2407.20183" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">  Arxiv</a>111        <a href="https://huggingface.co/papers/2407.20183" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">  Hugging Face Papers</a>112        <a href="https://huggingface.co/spaces/internlm/MindSearch" style="text-decoration: none; color: #4A90E2;">  Hugging Face Demo</a>113    </div>114    """)115    with gr.Row():116        with gr.Column(scale=10):117            with gr.Row():118                with gr.Column():119                    planner = gr.Chatbot(label='planner',120                                         height=700,121                                         show_label=True,122                                         show_copy_button=True,123                                         bubble_full_width=False,124                                         render_markdown=True)125                with gr.Column():126                    searcher = gr.Chatbot(label='searcher',127                                          height=700,128                                          show_label=True,129                                          show_copy_button=True,130                                          bubble_full_width=False,131                                          render_markdown=True)132            with gr.Row():133                user_input = gr.Textbox(show_label=False,134                                        placeholder='帮我搜索一下 InternLM 开源体系',135                                        lines=5,136                                        container=False)137            with gr.Row():138                with gr.Column(scale=2):139                    submitBtn = gr.Button('Submit')140                with gr.Column(scale=1, min_width=20):141                    emptyBtn = gr.Button('Clear History')142 143    def user(query, history):144        return '', history + [[query, '']]145 146    submitBtn.click(user, [user_input, planner], [user_input, planner],147                    queue=False).then(predict, [planner, searcher],148                                      [planner, searcher])149    emptyBtn.click(rst_mem, [planner, searcher], [planner, searcher],150                   queue=False)151 152demo.queue()153demo.launch(server_name='0.0.0.0',154            server_port=7860,155            inbrowser=True,156            share=True)