您的当前位置:首页进阶岛-第6关-【MindSearch 快速部署】

进阶岛-第6关-【MindSearch 快速部署】

2024-06-03 来源:乌哈旅游
  • 任务详情

1.基础任务

  • 按照教程,将 MindSearch 部署到 HuggingFace 并美化 Gradio 的界面,并提供截图和 Hugging Face 的Space的链接。

2.任务步骤

2.1 环境搭建

  • 打开,创建自己的Codespaces
  • 新建一个目录"mindsearch"用于存放 MindSearch 的相关代码
  • 在终端中 clone 关于"mindsearch"的代码
mkdir -p /workspaces/mindsearch
cd /workspaces/mindsearch
git clone https://github.com/InternLM/MindSearch.git
cd MindSearch && git checkout b832275 && cd ..

  • 接下来,我们创建一个 conda 环境来安装相关依赖。
  • github上就是快
# 创建环境
conda create -n mindsearch python=3.10 -y
  • 这里出现了一个BUG,需要输入命令
conda init
  • 然后重新启动终端
cd /workspaces/mindsearch
# 激活环境
conda activate mindsearch
# 安装依赖
pip install -r /workspaces/mindsearch/MindSearch/requirements.txt

2.2 获取硅基流动 API Key

  • 注册硅基流动的账号:
  • 创建新 API 密钥:

2.3 启动 MindSearch

2.3.1 启动后端

  • 直接执行下面的代码来启动 MindSearch 的后端。
export SILICON_API_KEY=第二步中复制的密钥
  • 然后,执行代码:
conda activate mindsearch
cd /workspaces/mindsearch/MindSearch
python -m mindsearch.app --lang cn --model_format internlm_silicon --search_engine DuckDuckGoSearch
  • 注意:出现如下报错ImportError: cannot import name ‘AutoRegister’ from ‘class_registry’ (/opt/conda/envs/mindsearch/lib/python3.10/site-packages/class_registry/init.py),解决方法,再执行上面的代码:
pip install --upgrade class_registry

2.3.2 启动前端

  • 打开新终端运行如下命令来启动 MindSearch 的前端。
conda activate mindsearch
cd /workspaces/mindsearch/MindSearch
python frontend/mindsearch_gradio.py

  • 我们在第一个终端还可以看到如下内容:
  • 我还尝试问了一个他没有的"你知道佳缘科技股份有限公司吗"

2.4. 部署到 HuggingFace Space

  • 首先打开,点击"Spaces"
  • 然后点击"Create new Space"
  • 然后进入创建界面
  • space name 写入自己想写的名字
  • license不填
  • 然后在下面的Select the Space SD选择"Gradio"
  • Choose a Gradio template:“Blank”
  • Space hardware:“CPU basic·2vCPU·16 GB·FREE”
  • 然后点击"Create Space"
  • 进入下一个界面,点击"Settings"
  • 选择 New secrets,name 一栏输入 SILICON_API_KEY,value 一栏输入你的 API Key 的内容。
  • New secrets在网页中间下面一点.
  • 最后,我们先新建一个目录,准备提交到 HuggingFace Space 的全部文件。
# 创建新目录
mkdir -p /workspaces/mindsearch/mindsearch_deploy
# 准备复制文件
cd /workspaces/mindsearch
cp -r /workspaces/mindsearch/MindSearch/mindsearch /workspaces/mindsearch/mindsearch_deploy
cp /workspaces/mindsearch/MindSearch/requirements.txt /workspaces/mindsearch/mindsearch_deploy
# 创建 app.py 作为程序入口
touch /workspaces/mindsearch/mindsearch_deploy/app.py
  • 用vim打开app.py文件
cd mindsearch_deploy/
vim app.py
  • 然后复制以下代码
import json
import os

import gradio as gr
import requests
from lagent.schema import AgentStatusCode

os.system("python -m mindsearch.app --lang cn --model_format internlm_silicon &")

PLANNER_HISTORY = []
SEARCHER_HISTORY = []


def rst_mem(history_planner: list, history_searcher: list):
    '''
    Reset the chatbot memory.
    '''
    history_planner = []
    history_searcher = []
    if PLANNER_HISTORY:
        PLANNER_HISTORY.clear()
    return history_planner, history_searcher


def format_response(gr_history, agent_return):
    if agent_return['state'] in [
            AgentStatusCode.STREAM_ING, AgentStatusCode.ANSWER_ING
    ]:
        gr_history[-1][1] = agent_return['response']
    elif agent_return['state'] == AgentStatusCode.PLUGIN_START:
        thought = gr_history[-1][1].split('```')[0]
        if agent_return['response'].startswith('```'):
            gr_history[-1][1] = thought + '\n' + agent_return['response']
    elif agent_return['state'] == AgentStatusCode.PLUGIN_END:
        thought = gr_history[-1][1].split('```')[0]
        if isinstance(agent_return['response'], dict):
            gr_history[-1][
                1] = thought + '\n' + f'```json\n{json.dumps(agent_return["response"], ensure_ascii=False, indent=4)}\n```'  # noqa: E501
    elif agent_return['state'] == AgentStatusCode.PLUGIN_RETURN:
        assert agent_return['inner_steps'][-1]['role'] == 'environment'
        item = agent_return['inner_steps'][-1]
        gr_history.append([
            None,
            f"```json\n{json.dumps(item['content'], ensure_ascii=False, indent=4)}\n```"
        ])
        gr_history.append([None, ''])
    return


def predict(history_planner, history_searcher):

    def streaming(raw_response):
        for chunk in raw_response.iter_lines(chunk_size=8192,
                                             decode_unicode=False,
                                             delimiter=b'\n'):
            if chunk:
                decoded = chunk.decode('utf-8')
                if decoded == '\r':
                    continue
                if decoded[:6] == 'data: ':
                    decoded = decoded[6:]
                elif decoded.startswith(': ping - '):
                    continue
                response = json.loads(decoded)
                yield (response['response'], response['current_node'])

    global PLANNER_HISTORY
    PLANNER_HISTORY.append(dict(role='user', content=history_planner[-1][0]))
    new_search_turn = True

    url = 'http://localhost:8002/solve'
    headers = {'Content-Type': 'application/json'}
    data = {'inputs': PLANNER_HISTORY}
    raw_response = requests.post(url,
                                 headers=headers,
                                 data=json.dumps(data),
                                 timeout=20,
                                 stream=True)

    for resp in streaming(raw_response):
        agent_return, node_name = resp
        if node_name:
            if node_name in ['root', 'response']:
                continue
            agent_return = agent_return['nodes'][node_name]['detail']
            if new_search_turn:
                history_searcher.append([agent_return['content'], ''])
                new_search_turn = False
            format_response(history_searcher, agent_return)
            if agent_return['state'] == AgentStatusCode.END:
                new_search_turn = True
            yield history_planner, history_searcher
        else:
            new_search_turn = True
            format_response(history_planner, agent_return)
            if agent_return['state'] == AgentStatusCode.END:
                PLANNER_HISTORY = agent_return['inner_steps']
            yield history_planner, history_searcher
    return history_planner, history_searcher


with gr.Blocks() as demo:
    gr.HTML("""<h1 align="center">MindSearch Gradio Demo</h1>""")
    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>""")
    gr.HTML("""
    <div style="text-align: center; font-size: 16px;">
        <a href="https://github.com/InternLM/MindSearch" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">🔗 GitHub</a>
        <a href="https://arxiv.org/abs/2407.20183" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">📄 Arxiv</a>
        <a href="https://huggingface.co/papers/2407.20183" style="margin-right: 15px; text-decoration: none; color: #4A90E2;">📚 Hugging Face Papers</a>
        <a href="https://huggingface.co/spaces/internlm/MindSearch" style="text-decoration: none; color: #4A90E2;">🤗 Hugging Face Demo</a>
    </div>
    """)
    with gr.Row():
        with gr.Column(scale=10):
            with gr.Row():
                with gr.Column():
                    planner = gr.Chatbot(label='planner',
                                         height=700,
                                         show_label=True,
                                         show_copy_button=True,
                                         bubble_full_width=False,
                                         render_markdown=True)
                with gr.Column():
                    searcher = gr.Chatbot(label='searcher',
                                          height=700,
                                          show_label=True,
                                          show_copy_button=True,
                                          bubble_full_width=False,
                                          render_markdown=True)
            with gr.Row():
                user_input = gr.Textbox(show_label=False,
                                        placeholder='帮我搜索一下 InternLM 开源体系',
                                        lines=5,
                                        container=False)
            with gr.Row():
                with gr.Column(scale=2):
                    submitBtn = gr.Button('Submit')
                with gr.Column(scale=1, min_width=20):
                    emptyBtn = gr.Button('Clear History')

    def user(query, history):
        return '', history + [[query, '']]

    submitBtn.click(user, [user_input, planner], [user_input, planner],
                    queue=False).then(predict, [planner, searcher],
                                      [planner, searcher])
    emptyBtn.click(rst_mem, [planner, searcher], [planner, searcher],
                   queue=False)

demo.queue()
demo.launch(server_name='0.0.0.0',
            server_port=7860,
            inbrowser=True,
            share=True)
  • 然后按下":wq"进行保存
  • 在最后,将 /root/mindsearch/mindsearch_deploy 目录下的文件(使用 git)提交到 HuggingFace Space 即可完成部署了。将代码提交到huggingface space的流程如下:
  • 首先创建一个有写权限的token。
  • 然后
  • 然后从huggingface把空的代码仓库clone到codespace。
cd /workspaces/codespaces-blank
git clone https://huggingface.co/spaces/<你的名字>/<仓库名称>
# 把token挂到仓库上,让自己有写权限
git remote set-url space https://<你的名字>:<上面创建的token>@huggingface.co/spaces/<你的名字>/<仓库名称>

  • ** 注意,提交到huggingface也会出现一个错误**:
  • ImportError: cannot import name ‘AutoRegister’ from ‘class_registry’ (/opt/conda/envs/mindsearch/lib/python3.10/site-packages/class_registry/init.py)
  • 我这里直接把requirements.txt文件修改一下就可以了,把"class_registry"加到最后,再启动
duckduckgo_search==5.3.1b1
einops
fastapi
git+https://github.com/InternLM/lagent.git
gradio
janus
lmdeploy
pyvis
sse-starlette
termcolor
transformers==4.41.0
uvicorn
class_registry
  • 最终启动如下
  • hf地址:

因篇幅问题不能全部显示,请点此查看更多更全内容