【书生浦语实战】MindSearch 部署到HuggingFace Space

news/2024/10/11 20:13:42/

结果速览

欢迎来玩:https://huggingface.co/spaces/LLyn/mindsearch_exercise
在这里插入图片描述

配置开发环境

使用github codespace

第一次使用github的codespace~本质上跟在intern studio一样,但是页面是vscode效果(intern studio是linux cli窗口),浏览器会自动在新的页面打开一个web版的vscode,比起用ssh访问intern studio的优势是部署服务后不需要设置本地ssh和远程再链接啦

步骤:左侧导航栏选择 Codespace、选择Blank 空白模版, Use this template进入IDE
在这里插入图片描述

安装环境

mkdir -p /workspaces/mindsearch
cd /workspaces/mindsearch
git clone https://github.com/InternLM/MindSearch.git
cd MindSearch && git checkout b832275 && cd ..# 创建环境
conda create -n mindsearch python=3.10 -y
# 激活环境
conda activate mindsearch
# 安装依赖
pip install -r /workspaces/mindsearch/MindSearch/requirements.txt

除了requirements.txt里面的依赖包,还要安装class_registry、(不然运行lagent会报错、我之前是直接去修改了源码导入,但现在部署到hf了只能装包解决了)

pip install class_registry

获取硅基流动 API Key

因为要使用硅基流动的 API Key,所以接下来便是注册并获取 API Key 了。

首先,我们打开 https://account.siliconflow.cn/login 来注册硅基流动的账号(如果注册过,则直接登录即可)。

在完成注册后,打开 https://cloud.siliconflow.cn/account/ak 来准备 API Key。首先创建新 API 密钥,然后点击密钥进行复制,以备后续使用。

调试前后端

再github space先运行一下代码看下效果

export SILICON_API_KEY=第二步中复制的密钥
conda activate mindsearch
cd /workspaces/mindsearch/MindSearch
python -m mindsearch.app --lang cn --model_format internlm_silicon --search_engine DuckDuckGoSearchconda activate mindsearch
cd /workspaces/mindsearch/MindSearch
python frontend/mindsearch_gradio.py

效果如下:
在这里插入图片描述

部署到 HuggingFace Space

配置sillionflow的key

再hugging face创建好的space中 setting里面找到如下模块,配置好SILICON_API_KEY
在这里插入图片描述
(看图上两条key就知道小白踩过雷…)

记得secret的变量名称要叫SILICON_API_KEY,不要改成别的(除非mindset.agent.models里面定义好了其他环境变量key的名称!,下图是SILICON_API_KEY引用来源)
在这里插入图片描述

编写app.py

# 创建新目录
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

本人稍微调整了一下gradio页面布局,把输入框放到结果框前面了

import json
import osimport gradio as gr
import requests
from lagent.schema import AgentStatusCodeos.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_searcherdef 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: E501elif 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, ''])returndef 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':continueif decoded[:6] == 'data: ':decoded = decoded[6:]elif decoded.startswith(': ping - '):continueresponse = json.loads(decoded)yield (response['response'], response['current_node'])global PLANNER_HISTORYPLANNER_HISTORY.append(dict(role='user', content=history_planner[-1][0]))new_search_turn = Trueurl = '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 = respif node_name:if node_name in ['root', 'response']:continueagent_return = agent_return['nodes'][node_name]['detail']if new_search_turn:history_searcher.append([agent_return['content'], ''])new_search_turn = Falseformat_response(history_searcher, agent_return)if agent_return['state'] == AgentStatusCode.END:new_search_turn = Trueyield history_planner, history_searcherelse:new_search_turn = Trueformat_response(history_planner, agent_return)if agent_return['state'] == AgentStatusCode.END:PLANNER_HISTORY = agent_return['inner_steps']yield history_planner, history_searcherreturn history_planner, history_searcherwith 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():user_input = gr.Textbox(show_label=False,placeholder='介绍一下Mindseach',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')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)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)

提交到 HF space

首先创建一个有写权限的token

记得要选permissions=write!
在这里插入图片描述

然后拷贝代码:

教程里面给的git remote set-url稍微有点错,应该是 git remote set-url ;remote-name是远程仓的名称、或者用origin(教程给的“space”会报错找不到指定的仓!)

cd /workspaces/codespaces-blank
git clone https://huggingface.co/spaces/<你的名字>/<仓库名称>
# 把token挂到仓库上,让自己有写权限
git remote set-url origin https://<你的名字>:<上面创建的token>@huggingface.co/spaces/<你的名字>/<仓库名称>## my case
git clone  https://huggingface.co/spaces/LLyn/mindsearch_exercise
git remote set-url origin https://LLyn:hf_token@huggingface.co/spaces/LLyn/mindsearch_exercise

然后把代码搬运到建好的仓里面(这里教程又错了,最后一期写的有点潦草啊喂…难道老师故意的???cp要加上-r不然文件夹拷贝不过来)


cd /workspaces/codespaces-blank/mindsearch_exercise
cp -r /workspaces/mindsearch/mindsearch_deploy/* .

注意mindsearch文件夹其实是Mindsearch项目中的一个子文件夹,文件夹完整内容如下:

(base) @lynnelian ➜ /workspaces/codespaces-blank/mindsearch_exercise (main) $ tree
.
├── README.md
├── app.py
├── mindsearch
│   ├── __pycache__
│   │   ├── app.cpython-310.pyc
│   │   └── app.cpython-312.pyc
│   ├── agent
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-310.pyc
│   │   │   ├── mindsearch_agent.cpython-310.pyc
│   │   │   ├── mindsearch_prompt.cpython-310.pyc
│   │   │   └── models.cpython-310.pyc
│   │   ├── mindsearch_agent.py
│   │   ├── mindsearch_prompt.py
│   │   └── models.py
│   ├── app.py
│   └── terminal.py
└── requirements.txt4 directories, 15 files

然后git提交

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

Hugging Face Space效果验证

进入https://huggingface.co/spaces/LLyn/mindsearch_exercise
输入测试query,成功!
在这里插入图片描述


http://www.ppmy.cn/news/1537612.html

相关文章

【PostgreSQL】PG数据库表“膨胀”粗浅学习

文章目录 1 为什么需要关注表膨胀&#xff1f;2 如何确定是否发生了表膨胀&#xff1f;2.1 通过查询表的死亡元组占比情况来判断膨胀率2.1.1 指定数据库和表名2.1.2 查询数据库里面所有表的膨胀情况 3 膨胀的原理3.1 什么是膨胀&#xff1f;膨胀率&#xff1f;3.2 哪些数据库元…

Spring Cache 的说明及常用注解

一.介绍 Spring Cache是Spring Framework中的一个模块&#xff0c;用于简化和统一缓存的使用。它提供了一种将缓存逻辑与应用程序业务逻辑分离的方式&#xff0c;使得我们可以更方便地使用缓存来提高应用程序的性能。 二.主要特性 注解支持&#xff1a;Spring Cache提供了一组…

通过onnxruntime进行模型部署过程中的问题

​ 1. onnxruntime包下载 从https://github.com/microsoft/onnxruntime/releases/下载解压到E:/code/package/onnruntime 2. opencv_c下载https://github.com/opencv/opencv/releases/tag/4.8.1 3.测试opencv代码&#xff1a;总结&#xff1a;添加include目录&#xff0c;添…

Leetcode 买卖股票的最佳时机

这段代码的目的是解决“买卖股票的最佳时机”这个问题&#xff0c;即在给定的股票价格数组中&#xff0c;找到一次买入和卖出所能获得的最大利润。 算法思想&#xff1a; 定义两个变量&#xff1a; minPrice: 这个变量用于记录迄今为止遇到的最小股票价格&#xff08;买入价格…

Stable Diffusion绘画 | 签名、字体、Logo设计

第1步&#xff0c;使用 PS&#xff08;小白推荐使用 可画&#xff09;准备一个 512*768 的签名、字体、Logo图片&#xff1a; 第2步&#xff0c;来到模型网站&#xff0c;搜索&#x1f50d;关键词“电商”&#xff0c;找到一款喜欢的 LoRA&#xff1a; 第3步&#xff0c;选择一…

学习JavaScript的真假值然后理解!!运算符的使用

真值&#xff08;truthy&#xff09;和假值&#xff08;falsy&#xff09; 在 JavaScript 中&#xff0c;有一些值总是被认为是假值&#xff08;falsy&#xff09;&#xff0c;其他的都被认为是真值&#xff08;truthy&#xff09;。以下是常见的假值&#xff1a; false0&…

线性代数书中求解齐次线性方程组、非齐次线性方程组方法的特点和缺陷(附实例讲解)

目录 一、克拉默法则 1. 方法概述 2. 例16(1) P45 3. 特点 (1) 只适用于系数矩阵是方阵 (2) 只适用于行列式非零 (3) 只适用于唯一解的情况 (4) 只适用于非齐次线性方程组 二、逆矩阵 1. 方法概述 2. 例16(2) P45 3. 特点 (1) 只适用于系数矩阵必须是方阵且可逆 …

Docker容器简介及部署方法

1.1 Docker简介 Docker之父Solomon Hykes&#xff1a;Docker就好比传统的货运集装箱 2008 年LXC(LinuX Contiainer)发布&#xff0c;但是没有行业标准&#xff0c;兼容性非常差 docker2013年首次发布&#xff0c;由Docker, Inc开发 1.1.1什么是Docker Docker是管理容器的引…