书生.浦江大模型实战训练营——(十四)MindSearch 快速部署

news2024/9/22 17:33:40

最近在学习书生.浦江大模型实战训练营,所有课程都免费,以关卡的形式学习,也比较有意思,提供免费的算力实战,真的很不错(无广)!欢迎大家一起学习,打开LLM探索大门:邀请连接,PS,邀请有算力哈哈
在这里插入图片描述

文章目录

  • 一、创建开发机 & 环境配置
  • 二、获取硅基流动 API Key
  • 三、启动 MindSearch
  • 四、部署到 HuggingFace Space

一、创建开发机 & 环境配置

打开codespace主页,选择blank template。
在这里插入图片描述
新建一个目录用于存放 MindSearch 的相关代码,并把 MindSearch 仓库 clone 下来。在终端中运行下面的命令:

mkdir -p /workspaces/mindsearch
cd /workspaces/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 /workspaces/mindsearch/MindSearch/requirements.txt

二、获取硅基流动 API Key

首先,我们打开https://account.siliconflow.cn/login 来注册硅基流动的账号。在完成注册后,打开 https://cloud.siliconflow.cn/account/ak 来准备 API Key。首先创建新 API 密钥,然后点击密钥进行复制,以备后续使用。
在这里插入图片描述

三、启动 MindSearch

可以直接执行下面的代码来启动 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

打开新终端运行如下命令来启动 MindSearch 的前端:

conda activate mindsearch
cd /workspaces/mindsearch/MindSearch
python frontend/mindsearch_gradio.py

可以看到github自动为这两个进程做端口转发。
在这里插入图片描述
在弹出的弹窗中打开窗口,即可体验。
在这里插入图片描述

四、部署到 HuggingFace Space

首先打开 https://huggingface.co/spaces ,并点击 Create new Space,如下图所示。

在这里插入图片描述

在输入 Space name 并选择 License 后,选择配置如下所示:
在这里插入图片描述

入 Settings,配置硅基流动的 API Key。如下图所示:
在这里插入图片描述
选择 New secrets,name 一栏输入 SILICON_API_KEY,value 一栏输入你的 API Key 的内容,点击save保存。
最后,新建一个目录,准备提交到 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;">🔗 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)

最后,将 /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/<你的名字>/<仓库名称>

在这里插入图片描述
现在codespace就是本地仓库,huggingface space是远程仓库,接下来使用方法就和常规的git一样了。

cd <仓库名称>
# 把刚才准备的文件都copy进来
cp /workspaces/mindsearch/mindsearch_deploy/* .

这是最终目录:
在这里插入图片描述
最后把代码提交到huggingface space会自动启动项目:

git add .
git commit -m "update"
git push

支持在线访问:MindSearch Gradio Demo,下面进行测试:
在这里插入图片描述
至此,MindSearch 快速部署完成!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2078789.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

达梦数据库兼容Quartz定时框架

1、背景 近期项目中需要使用达梦数据库&#xff0c;现将mysql数据库切换为达梦数据库&#xff0c;其中兼容Quartz定时框架报错如下&#xff1a; 2、解决方案 2.1 起初配置完&#xff1a;达梦数据库驱动直接启动项目直接报错&#xff0c; 后面在yml中配置数据库表名前缀&…

rac集群二几点重启ora.gipcd不能正常启动

集群起来后gipcd服务不能正常启动 检查gipcd日志&#xff1a; 2024-08-26 00:29:50.745: [GIPCXCPT][2] gipcPostF [gipcd_ExitCB : gipcd.c : 431]: EXCEPTION[ ret gipcretInvalidObject (3) ] failed to post obj 0000000000000000, flags 0x0 2024-08-26 00:29:50.745: […

企业培训APP开发指南:基于在线教育系统源码的实践

当下&#xff0c;基于在线教育系统源码开发企业培训APP成为了许多企业提高员工技能、优化培训流程的首选方案。 一、为什么选择基于在线教育系统源码开发企业培训APP&#xff1f; 1.定制化需求&#xff1a;每个企业的培训需求和目标都不尽相同&#xff0c;基于现有的在线教育…

一键安装最流畅的Win7系统家庭版!附详细安装教程

今日系统之家小编给大家带来运作最流畅的Win7系统家庭版&#xff0c;该版本系统经过精心优化&#xff0c;系统资源占用更少&#xff0c;运作变得更流畅。系统支持不同的安装方式&#xff0c;推荐用户使用硬盘一键安装方式&#xff0c;安装起来更简单&#xff0c;非常适合新手用…

汇川技术|Inoproshop软件菜单[工具、窗口、帮助]

哈喽&#xff0c;你好啊&#xff0c;我是雷工&#xff01; 其实对软件的学习就是看帮助加应用&#xff0c;根据帮助了解都有哪些功能&#xff0c;然后在应用中熟悉这些功能&#xff0c;随着应用的熟练&#xff0c;逐步总结出提升效率的技巧方法&#xff0c;从而逐步达到精通的…

探索 Go 语言中的数组和切片:深入理解顺序集合

在 Go 语言的丰富数据类型中&#xff0c;数组和切片是处理有序数据集合的强大工具&#xff0c;它们允许开发者以连续的内存块来存储和管理相同类型的多个元素。无论是在处理大量数据时的性能优化&#xff0c;还是在实现算法时对数据结构的需求&#xff0c;数组和切片都扮演着至…

无线领夹麦克风六大行业趋势揭秘:洞察市场风向谨防踩坑!

​近年来&#xff0c;无线领夹麦克风受到很多直播达人、视频创作者的推荐与青睐&#xff0c;作为一款实用便捷的音频设备&#xff0c;各个创作领域都广泛应用。如今无线领夹麦克风市场产品多样且品质各异&#xff0c;有些产品采用劣质材料&#xff0c;甚至存在信号不稳定等问题…

IP代理怎么测试网速:全面指南

在互联网时代&#xff0c;代理IP已经成为了很多人上网的重要工具。不管你是为了保护隐私&#xff0c;还是为了提高访问速度&#xff0c;代理IP都能提供很大的帮助。那么&#xff0c;如何测试代理IP的网速呢&#xff1f;今天我们就来聊聊这个话题。 什么是代理IP&#xff1f; 代…

SQL进阶技巧:如何按任意时段分析时间区间问题? | 分区间讨论【左、中、右】

目录 0 场景描述 1 数据准备 2 问题分析 方法1:分情况讨论,找出重叠区间 方法2:暴力美学法。按区间展开成日期明细表 3 拓展案例 4小结 0 场景描述 现有用户还款计划表 user_repayment ,该表内的一条数据,表示用户在指定日期区间内 [date_start, date_end] ,每天…

从零部件到汽车,Fortinet如何守护车主安全出行每一步

随着汽车产业蓬勃发展&#xff0c; 网络安全威胁也正在“紧盯”汽车全产业链。从制造、销售直至最终使用阶段&#xff0c;均面临着网络安全威胁的挑战&#xff1a;制造环节的软件与生产环境漏洞隐患、销售过程中数据泄露风险&#xff0c;以及使用阶段车载系统脆弱性和用户安全意…

自由能在哪些领域可以大放异彩? ——自由能的多领域应用探索

自由能在哪些领域可以大放异彩&#xff1f; ——自由能的多领域应用探索 【表格】自由能的应用领域 序号应用领域具体描述涉及公式/概念备注1化学领域描述化学反应的自发性&#xff0c;判断反应是否可能进行 Δ G Δ H − T Δ S \Delta G \Delta H - T\Delta S ΔGΔH−T…

#网络编程 笔记

认识网络 网络发展史 ARPnetA--->Internet--->移动互联网--->物联网 TCP 用来检测网络传输中差错的传输控制协议 UDP 用户数据报协议&#xff0c;专门负责对不同网络进行互联的互联网协议 局域网 实现小范围短距离网络通信 广域网 现大范围长距离网络通信…

最佳实践 | SaleSmartly用HelpLook搭建知识库,客服效率提升,服务好全球数万客户

SaleSmartly&#xff0c;作为全渠道私域沟通工具的佼佼者&#xff0c;使用HelpLook开启了全新智能客服服务新体验。通过使用HelpLook搭建了AI知识库和博客中心&#xff0c;SaleSmartly不仅大幅提升了客服效率&#xff0c;还成功优化了品牌形象&#xff0c;服务覆盖全球数万客户…

Onnx使用预训练的 ResNet18 模型对输入图像进行分类,并将分类结果显示在图像上

目录 一、整体功能概述 二、函数分析 2.1 resnet() 函数&#xff1a; 2.2 pre_process(img_path) 函数&#xff1a; 2.3 loadOnnx(img_path) 函数&#xff1a; 三、代码执行流程 一、整体功能概述 这段代码实现了一个图像分类系统&#xff0c;使用预训练的 ResNet18 模型对…

error C2375: “WSAAsyncGetHostByName”: 重定义;不同的链接

error C2375: “WSAAsyncGetHostByName”: 重定义;不同的链接 win11 vs2015 背景:当项目中使用到了开源库,开源库使用WinSock2.h,同时windows项目又有包含Windows.h, 编译时常常会出现一堆编译错误,方法重定义等等。 问题原因: 默认windows.h头文件会包含winsock.h //…

【Linux】快速入门(第一篇)

1. Linux简介 1.操作系统概念 Linux 也是众多操作系统之一&#xff0c;要想知道 Linux 是什么&#xff0c;首先得说一说什么是操作系统。 计算机是一台机器&#xff0c;它按照用户的要求接收信息、存储数据、处理数据&#xff0c;然后再将处理结果输出&#xff08;文字、图片…

.ipynb文件:交互式 Jupyter Notebook

Python 接口文件&#xff08;带有扩展名的文件.pyi&#xff09;&#xff0c;或称为 Python 存根文件&#xff0c;在使用类型提示增强 Python 代码方面发挥着至关重要的作用。 当你遇到名称以 .ipynb、.pyi、.pyc 等结尾的 Python 文件时&#xff0c;你是否会感到困惑&#xff…

Adobe ME软件安装win/mac下载与使用教程

目录 一、Adobe ME软件介绍 1.1 软件概述 1.2 主要功能 1.3 软件优势 二、系统要求 2.1 Windows系统要求 2.2 macOS系统要求 三、安装步骤 3.1 Windows系统安装 3.2 macOS系统安装 四、使用教程 4.1 基本界面介绍 4.2 视频编码与转码 4.3 音频和字幕处理 4.4 高…

快来领取迅雷加速器7天会员,让你的《黑神话·悟空》更新速度嗖嗖嗖!⚡️

嘿&#xff0c;各位《黑神话悟空》的小伙伴们&#xff01;&#x1f606; 最近大家肯定都在Steam上体验这款国产3A大作吧&#xff1f;游戏的画质、玩法是不是让你眼前一亮&#xff1f;&#x1f60d; 但是&#xff01;&#x1f62b; 大家有没有发现&#xff0c;游戏加载和更新时…

谷歌的有害链接是什么?

有害链接&#xff0c;顾名思义&#xff0c;是指那些可能对你网站的Google排名产生负面影响的链接&#xff0c;但&#xff0c;真的存在会对网站造成坏影响的链接吗&#xff1f; 所谓的有害链接&#xff0c;更多是现在很多seo工具所定义出来的&#xff0c;事实上&#xff0c;自从…