首页 > 其他分享 >【书生·浦语实战营】进阶岛第6关:MindSearch CPU-only 版部署

【书生·浦语实战营】进阶岛第6关:MindSearch CPU-only 版部署

时间:2024-08-25 10:25:14浏览次数:8  
标签:MindSearch 进阶 return gr agent only mindsearch 浦语 history

文章目录

任务目标

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

学习内容

1. 创建开发机 & 环境配置

由于是 CPU-only,所以选择 10% A100 开发机即可,镜像方面选择 cuda-12.2。
或者采用github codespace选择blank template
在这里插入图片描述

然后我们新建一个目录用于存放 MindSearch 的相关代码,并把 MindSearch 仓库 clone 下来。

mkdir -p /root/mindsearch
cd /root/mindsearch
git clone https://github.com/InternLM/MindSearch.git
cd MindSearch && git checkout b832275 && cd ..

接下来,我们创建一个 conda 环境来安装相关依赖。

# 创建环境
conda create -n mindsearch python=3.10 -y
# 激活环境
conda activate mindsearch
# 安装依赖
pip install -r /root/mindsearch/MindSearch/requirements.txt

[CondaError:Run conda init’before’conda activate’]报错解决

如使用github codespace上一步可能会出现以下错误:
在这里插入图片描述
输入conda init并不能解决问题,可以输入 source activate应用conda环境:
在这里插入图片描述
之后即可正常激活conda环境。

[ERROR:Could not open requirements file:[Errno 13]Permission denied:'/root/mindsearch/Mindsearch/requirements.txt]报错解决

在这里插入图片描述
这是因为使用codespces时路径不对,命令修改为pip install -r /workspaces/mindsearch/MindSearch/requirements.txt即可

2. 获取硅基流动 API Key

因为要使用硅基流动的 API Key,所以接下来便是注册并获取 API Key 了。
首先,我们打开 https://account.siliconflow.cn/login 来注册硅基流动的账号(如果注册过,则直接登录即可)。
在完成注册后,打开 https://cloud.siliconflow.cn/account/ak 来准备 API Key。首先创建新 API 密钥,然后点击密钥进行复制,以备后续使用。
3. 启动 MindSearch

  • 启动后端
    由于硅基流动 API 的相关配置已经集成在了 MindSearch 中,所以我们可以直接执行下面的代码来启动 MindSearch 的后端。
export SILICON_API_KEY=第二步中复制的密钥
conda activate mindsearch
# 如果使用codespaces就是:
# cd /workspaces/mindsearch/MindSearch
cd /root/mindsearch/MindSearch
python -m mindsearch.app --lang cn --model_format internlm_silicon --search_engine DuckDuckGoSearch

在这里插入图片描述
在这里插入图片描述

  • 启动前端
    在后端启动完成后,我们打开新终端运行如下命令来启动 MindSearch 的前端。
conda activate mindsearch
# 如果采用codespaces就是:
# cd /workspaces/mindsearch/MindSearch
cd /root/mindsearch/MindSearch
python frontend/mindsearch_gradio.py

在这里插入图片描述

最后,我们把 8002 端口和 7882 端口都映射到本地。可以在本地的 powershell 中执行如下代码:

ssh -CNg -L 8002:127.0.0.1:8002 -L 7882:127.0.0.1:7882 [email protected] -p <你的 SSH 端口号>

然后,我们在本地浏览器中打开 localhost:7882 即可体验啦。
如果遇到了 timeout 的问题,可以按照 文档 换用 Bing 的搜索接口。
在这里插入图片描述

部署planner部分结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

部署searcher部分结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4. 部署到 HuggingFace Space

最后,我们来将 MindSearch 部署到 HuggingFace Space。
我们首先打开 https://huggingface.co/spaces ,并点击 Create new Space,如下图所示。
在这里插入图片描述
在输入 Space name 并选择 License 后,选择配置如下所示。
在这里插入图片描述
然后,我们进入 Settings,配置硅基流动的 API Key。如下图所示。
在这里插入图片描述
往下翻,选择 New secrets,name 一栏输入 SILICON_API_KEY,value 一栏输入你的 API Key 的内容。
在这里插入图片描述
在这里插入图片描述
最后回到codespaces,我们先新建一个目录,准备提交到 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

其中,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;">

标签:MindSearch,进阶,return,gr,agent,only,mindsearch,浦语,history
From: https://blog.csdn.net/qq_43959624/article/details/141437817

相关文章

  • 浦语Camp3:入门3-Git基础
    任务等级任务内容必做任务破冰,提交一份自我介绍必做任务创建并提交一个项目1.破冰,提交一份自我介绍因此使用gitconfig--global命令来设置用户名和用户邮件执行:gitconfig--globaluser.name"YourName"#真实信息脱敏处理gitconfig--globaluser.email"your......
  • 浦语Camp3:入门2-Python基础
    任务类型任务内容闯关任务python实现wordcount闯关任务Vscode连接InternStudiodebug笔记1.python实现wordcount请实现一个wordcount函数,统计英文字符串中每个单词出现的次数。返回一个字典,key为单词,value为对应单词出现的次数text="""Gotthispandaplushtoyformyd......
  • 浦语Camp3:入门1-Linux基础
    任务等级任务内容闯关任务完成SSH连接与端口映射并运行hello_world.py可选任务1将Linux基础命令在开发机上完成一遍可选任务2使用VSCODE远程连接开发机并创建一个conda环境可选任务3创建并运行test.sh文件1.完成SSH连接与端口映射并运行hello_world.py新建hello_world.p......
  • 【Spring Boot进阶】掌握Spring Boot框架核心注解:从入门到精通(实战指南)
    文章目录SpringBoot注解大全:深入理解与实践引言第一部分:基础知识1.SpringBoot和Java注解简介2.SpringBoot项目搭建第二部分:核心注解详解3.@SpringBootApplication4.@Component,@Service,@Repository,@Controller,@RestController5.@Autowired6.@Bean7......
  • 【Spring进阶】掌握Spring MVC框架核心注解:从基础到实战应用(实战指南)
    文章目录SpringMVC常用注解详解及实践引言第一部分:SpringMVC基础回顾第1章:SpringMVC概述第2章:MVC模式与SpringMVC第3章:快速上手SpringMVC第二部分:核心控制器注解第4章:@Controller第5章:@RestController第6章:@RequestMapping第三部分:请求处理注解第7章:@RequestParam......
  • 【AI绘画】StableDiffusion保姆级入门到进阶教程
    大家好,我是设计师子衿。最近子衿在刷抖音时候,发现现在很多账号都在用AI人物进行直播和带货,不知各位有没有留意到,很多小伙伴在看到时跑来问过,关于现在那些AI主播之类都是什么工具做的,其实这类大部分都是这款软件StableDiffusion做的,你只需要描述一段文字,它就能帮你生成一张......
  • (保姆级)自学网络安全超详细学习路线,从青铜到王者的进阶之路_网络安全工程师自学
    算上从学校开始学习,已经在网安这条路上走了10年了,无论是以前在学校做安全研究,还是毕业后在百度、360从事内核安全产品和二进制漏洞攻防对抗,我都深知学习方法的重要性。没有一条好的学习路径和好的学习方法,往往只会事倍功半。回头看来自己踩过不少坑,走过不少冤枉路,希望我的......
  • Java基础学习篇:switch条件语句进阶(最详细版)
    ......
  • 【Python进阶】Python中的函数式编程元素:map、filter和reduce的妙用
    1、函数式编程概览1.1函数式编程起源与发展函数式编程这一概念可以追溯到20世纪30年代的λ演算理论,这一时期数学家们开始探讨如何通过纯粹的函数运算来构建计算模型。随着时间的推移,函数式编程逐渐发展成为一种重要的编程范式,并在Lisp、Scheme、Haskell等语言中得到了充......
  • SPONGE进阶教程:MetaDynamics的简单用例
    前序课程1前序课程2场景简述蛋白与配体对接后,采用通常的分子动力学模拟,通常会采样得到势阱附近的大量结构(如下图左L-P),即蛋白-配体结合构象的平均系综。如果想要探究蛋白-配体解离过程,需要克服一个解离能垒,去到L-P*,甚至更远的L+P解离状态。这时候静候模拟体系自然地运动过去是不......