当前位置: 首页 > news >正文

28网站怎么做代理西安百度关键词优化排名

28网站怎么做代理,西安百度关键词优化排名,做同城购物网站赚钱吗,做网站设计管理的专业Streamlit是一个开源的Python库,利用Streamlit可以快速构建机器学习应用的用户界面。 本文主要探讨如何使用Streamlit构建大模型外部知识检索的AI问答可视化界面。 我们先构建了外部知识检索接口,然后让大模型根据检索返回的结果作为上下文来回答问题。…

Streamlit是一个开源的Python库,利用Streamlit可以快速构建机器学习应用的用户界面。

本文主要探讨如何使用Streamlit构建大模型+外部知识检索的AI问答可视化界面。

我们先构建了外部知识检索接口,然后让大模型根据检索返回的结果作为上下文来回答问题。

Streamlit-使用说明

下面简单介绍下Streamlit的安装和一些用到的组件。

  1. Streamlit安装
pip install streamlit
  1. Streamlit启动
streamlit run xxx.py --server.port 8888

说明:

  • 如果不指定端口,默认使用8501,如果启动多个streamlit,端口依次升序,8502,8503,…。
  • 设置server.port可指定端口。
  • streamlit启动后将会给出两个链接,Local URL和Network URL。
  1. 相关组件
import streamlit as st
  • st.header

streamlit.header(body)

body:字符串,要显示的文本。

  • st.markdown

st.markdown(body, unsafe_allow_html=False)

body:要显示的markdown文本,字符串。

unsafe_allow_html: 是否允许出现html标签,布尔值,默认:false,表示所有的html标签都将转义。 注意,这是一个临时特性,在将来可能取消。

  • st.write

st.write(*args, **kwargs)

*args:一个或多个要显示的对象参数。

unsafe_allow_html :是否允许不安全的HTML标签,布尔类型,默认值:false。

  • st.button

st.button(label, key=None)

label:按钮标题字符串。

key:按钮组件的键,可选。如果未设置的话,streamlit将自动生成一个唯一键。

  • st.radio

st.radio(label, options, index=0, format_func=<class 'str'>, key=None)

label:单选框文本,字符串。

options:选项列表,可以是以下类型:
list
tuple
numpy.ndarray
pandas.Series

index:选中项的序号,整数。

format_func:选项文本的显示格式化函数。

key:组件ID,当未设置时,streamlit会自动生成。

  • st.sidebar

st.slider(label, min_value=None, max_value=None, value=None, step=None, format=None, key=None)

label:说明文本,字符串。

min_value:允许的最小值,默认值:0或0.0。

max_value:允许的最大值,默认值:0或0.0。

value:当前值,默认值为min_value。

step:步长,默认值为1或0.01。

format:数字显示格式字符串

key:组件ID。

  • st.empty

st.empty()

填充占位符。

  • st.columns

插入并排排列的容器。

st.columns(spec, *, gap="small")

spec: 控制要插入的列数和宽度。

gap: 列之间的间隙大小。

AI问答可视化代码

这里只涉及到构建AI问答界面的代码,不涉及到外部知识检索。

  1. 导入packages
import streamlit as st
import requests
import json
import sys,osimport torch
import torch.nn as nn
from dataclasses import dataclass, asdict
from typing import List, Optional, Callable
import copy
import warnings
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.generation.utils import GenerationConfig
from peft import PeftModel
from chatglm.modeling_chatglm import ChatGLMForConditionalGeneration
  1. 外部知识检索
def get_reference(user_query,use_top_k=True,top_k=10,use_similar_score=True,threshold=0.7):"""外部知识检索的方式,使用top_k或者similar_score控制检索返回值。"""# 设置检索接口SERVICE_ADD = ''ref_list = []user_query = user_query.strip()input_data = {}if use_top_k:input_data['query'] = user_queryinput_data['topk'] = top_kresult = requests.post(SERVICE_ADD, json=input_data)res_json = json.loads(result.text)for i in range(len(res_json['answer'])):ref = res_json['answer'][i]ref_list.append(ref)elif use_similar_score:input_data['query'] = user_queryinput_data['topk'] = top_kresult = requests.post(SERVICE_ADD, json=input_data)res_json = json.loads(result.text)for i in range(len(res_json['answer'])):maxscore = res_json['answer'][i]['prob']if maxscore > threshold:  ref = res_json['answer'][i]ref_list.append(ref)return ref_list
  1. 参数设置
# 设置清除按钮
def on_btn_click():del st.session_state.messages# 设置参数
def set_config():# 设置基本参数base_config = {"model_name":"","use_ref":"","use_topk":"","top_k":"","use_similar_score":"","max_similar_score":""}# 设置模型参数model_config = {'top_k':'','top_p':'','temperature':'','max_length':'','do_sample':""}# 左边栏设置with st.sidebar:model_name = st.radio("模型选择:",["baichuan2-13B-chat", "qwen-14B-chat","chatglm-6B","chatglm3-6B"],index="0",)base_config['model_name'] = model_nameset_ref = st.radio("是否使用外部知识库:",["是","否"],index="0",)base_config['use_ref'] = set_refif set_ref=="是":set_topk_score = st.radio('设置选择参考文献的方式:',['use_topk','use_similar_score'],index='0',)if set_topk_score=='use_topk':set_topk = st.slider('Top_K', 1, 10, 5,step=1)base_config['top_k'] = set_topkbase_config['use_topk'] = Truebase_config['use_similar_score'] = Falseset_score = st.empty()elif set_topk_score=='use_similar_score':set_score = st.slider("Max_Similar_Score",0.00,1.00,0.70,step=0.01)base_config['max_similar_score'] = set_scorebase_config['use_similar_score'] = Truebase_config['use_topk'] = Falseset_topk = st.empty()else:set_topk_score = st.empty()set_topk = st.empty()set_score = st.empty()sample = st.radio("Do Sample", ('True', 'False'))max_length = st.slider("Max Length", min_value=64, max_value=2048, value=1024)top_p = st.slider('Top P', 0.0, 1.0, 0.7, step=0.01)temperature = st.slider('Temperature', 0.0, 2.0, 0.05, step=0.01)st.button("Clear Chat History", on_click=on_btn_click)# 设置模型参数model_config['top_p']=top_pmodel_config['do_sample']=samplemodel_config['max_length']=max_lengthmodel_config['temperature']=temperaturereturn base_config,model_config
  1. 设置模型输入格式
# 设置不同模型的输入格式
def set_input_format(model_name):# ["baichuan2-13B-chat", "baichuan2-7B-chat", "qwen-14B-chat",'chatglm-6B','chatglm3-6B']if model_name=="baichuan2-13B-chat" or model_name=='baichuan2-7B-chat':input_format = "<reserved_106>{{query}}<reserved_107>"elif model_name=="qwen-14B-chat":input_format = """<|im_start|>system 你是一个乐于助人的助手。<|im_end|><|im_start|>user{{query}}<|im_end|><|im_start|>assistant"""elif model_name=="chatglm-6B":input_format = """{{query}}"""elif model_name=="chatglm3-6B":input_format = """<|system|>You are ChatGLM3, a large language model trained by Zhipu.AI. Follow the user's instructions carefully. Respond using markdown.<|user|>{{query}}<|assistant|>"""return input_format
  1. 加载模型
# 加载模型和分词器
@st.cache_resource
def load_model(model_name):if model_name=="baichuan2-13B-chat":model = AutoModelForCausalLM.from_pretrained("baichuan-inc/Baichuan2-13B-Chat",trust_remote_code=True)lora_path = ""tokenizer = AutoTokenizer.from_pretrained("baichuan-inc/Baichuan2-13B-Chat",trust_remote_code=True)model.to("cuda:0")elif model_name=="qwen-14B-chat":model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-14B-Chat",trust_remote_code=True)lora_path = ""tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-14B-Chat",trust_remote_code=True)model.to("cuda:1")elif model_name=="chatglm-6B":model = ChatGLMForConditionalGeneration.from_pretrained('THUDM/chatglm-6b',trust_remote_code=True)lora_path = ""tokenizer = AutoTokenizer.from_pretrained('THUDM/chatglm-6b',trust_remote_code=True)model.to("cuda:2")elif model_name=="chatglm3-6B":model = AutoModelForCausalLM.from_pretrained('THUDM/chatglm3-6b',trust_remote_code=True)lora_path = ""tokenizer = AutoTokenizer.from_pretrained('THUDM/chatglm3-6b',trust_remote_code=True)model.to("cuda:3")# 加载lora包model = PeftModel.from_pretrained(model,lora_path)return model,tokenizer
  1. 推理参数设置

def llm_chat(model_name,model,tokenizer,model_config,query):response = ''top_k = model_config['top_k']top_p = model_config['top_p']max_length = model_config['max_length']do_sample = model_config['do_sample']temperature = model_config['temperature']if model_name=="baichuan2-13B-chat" or model_name=='baichuan-7B-chat':messages = []messages.append({"role": "user", "content": query})response = model.chat(tokenizer, messages)elif model_name=="qwen-14B-chat":response, history = model.chat(tokenizer, query, history=None, top_p=top_p, max_new_tokens=max_length, do_sample=do_sample, temperature=temperature)elif model_name=="chatglm-6B":response, history = model.chat(tokenizer, query, history=None, top_p=top_p, max_length=max_length, do_sample=do_sample, temperature=temperature)elif model_name=="chatglm3-6B":response, history= model.chat(tokenizer, query, top_p=top_p, max_length=max_length, do_sample=do_sample, temperature=temperature)return response
  1. 主程序
if __name__=="__main__":#对话的图标user_avator = "🧑‍💻"robot_avator = "🤖"if "messages" not in st.session_state:st.session_state.messages = []torch.cuda.empty_cache()base_config,model_config = set_config()model_name = base_config['model_name']use_ref = base_config['use_ref']model,tokenizer = load_model(model_name=model_name)input_format = set_input_format(model_name=model_name)header_text = f'Large Language Model :{model_name}'st.header(header_text)if use_ref=="是":col1, col2 = st.columns([5, 3])  with col1:for message in st.session_state.messages:with st.chat_message(message["role"], avatar=message.get("avatar")):st.markdown(message["content"])if user_query := st.chat_input("请输入内容..."):with col1:  with st.chat_message("user", avatar=user_avator):st.markdown(user_query)st.session_state.messages.append({"role": "user", "content": user_query, "avatar": user_avator})with st.chat_message("robot", avatar=robot_avator):message_placeholder = st.empty()use_top_k = base_config['use_topk']if use_top_k:top_k = base_config['top_k']use_similar_score = base_config['use_similar_score']ref_list = get_reference(user_query,use_top_k=use_top_k,top_k=top_k,use_similar_score=use_similar_score) else:use_top_k = base_config['use_topk']use_similar_score = base_config['use_similar_score']threshold = base_config['max_similar_score']ref_list = get_reference(user_query,use_top_k=use_top_k,use_similar_score=use_similar_score,threshold=threshold)if ref_list:context = ""for ref in ref_list:context = context+ref['para']+"\n"context = context.strip('\n')query = f'''上下文:【{context} 】只能根据提供的上下文信息,合理回答下面的问题,不允许编造内容,不允许回答无关内容。问题:【{user_query}】'''else:query = user_queryquery = input_format.replace("{{query}}",query)print('输入:',query)max_len = model_config['max_length']if len(query)>max_len:cur_response = f'字数超过{max_len},请调整max_length。'else:cur_response = llm_chat(model_name,model,tokenizer,model_config,query)fs.write(f'输入:{query}')fs.write('\n')fs.write(f'输出:{cur_response}')fs.write('\n')sys.stdout.flush()if len(query)<max_len:if ref_list:cur_response = f"""大模型将根据外部知识库回答您的问题:{cur_response}"""else:cur_response = f"""大模型将根据预训练时的知识回答您的问题,存在编造事实的可能性。因此以下输出仅供参考:{cur_response}"""message_placeholder.markdown(cur_response)st.session_state.messages.append({"role": "robot", "content": cur_response, "avatar": robot_avator})with col2:ref_list = get_reference(user_query)if ref_list:for ref in ref_list:ques = ref['ques']answer = ref['para']score = ref['prob']question = f'{ques}--->score: {score}'with st.expander(question):st.write(answer)else:for message in st.session_state.messages:with st.chat_message(message["role"], avatar=message.get("avatar")):st.markdown(message["content"])if user_query := st.chat_input("请输入内容..."):with st.chat_message("user", avatar=user_avator):st.markdown(user_query)st.session_state.messages.append({"role": "user", "content": user_query, "avatar": user_avator})with st.chat_message("robot", avatar=robot_avator):message_placeholder = st.empty()query = input_format.replace("{{query}}",user_query)max_len = model_config['max_length']if len(query)>max_len:cur_response = f'字数超过{max_len},请调整max_length。'else:cur_response = llm_chat(model_name,model,tokenizer,model_config,query)fs.write(f'输入:{query}')fs.write('\n')fs.write(f'输出:{cur_response}')fs.write('\n')sys.stdout.flush()cur_response = f"""大模型将根据预训练时的知识回答您的问题,存在编造事实的可能性。因此以下输出仅供参考:{cur_response}"""message_placeholder.markdown(cur_response)st.session_state.messages.append({"role": "robot", "content": cur_response, "avatar": robot_avator})
  1. 可视化界面展示

总结

Streamlit工具使用非常方便,说明文档清晰。

这个可视化界面集成了多个大模型+外部知识检索,同时可以在线调整模型参数,使用方便。

完整代码:https://github.com/hjandlm/Streamlit_LLM_QA

参考

[1] https://docs.streamlit.io/
[2] http://cw.hubwiz.com/card/c/streamlit-manual/
[3] https://github.com/hiyouga/LLaMA-Factory/tree/9093cb1a2e16d1a7fde5abdd15c2527033e33143

在这里插入图片描述


文章转载自:
http://delomorphous.bbtn.cn
http://aestivate.bbtn.cn
http://optate.bbtn.cn
http://corrigent.bbtn.cn
http://sorcerer.bbtn.cn
http://poisoning.bbtn.cn
http://purveyance.bbtn.cn
http://clutch.bbtn.cn
http://durrie.bbtn.cn
http://inlook.bbtn.cn
http://frcp.bbtn.cn
http://cryoresistive.bbtn.cn
http://monostabtle.bbtn.cn
http://crombec.bbtn.cn
http://speedster.bbtn.cn
http://anachronous.bbtn.cn
http://gaper.bbtn.cn
http://remediless.bbtn.cn
http://abscisin.bbtn.cn
http://frances.bbtn.cn
http://penstock.bbtn.cn
http://gobbler.bbtn.cn
http://brittany.bbtn.cn
http://dockmaster.bbtn.cn
http://sonnet.bbtn.cn
http://unsavory.bbtn.cn
http://phallic.bbtn.cn
http://pyrgeometer.bbtn.cn
http://biotical.bbtn.cn
http://yami.bbtn.cn
http://immoderacy.bbtn.cn
http://unransomed.bbtn.cn
http://filename.bbtn.cn
http://msph.bbtn.cn
http://reinhold.bbtn.cn
http://sausage.bbtn.cn
http://reposal.bbtn.cn
http://spatiography.bbtn.cn
http://centimetre.bbtn.cn
http://unlet.bbtn.cn
http://thaumaturgical.bbtn.cn
http://verify.bbtn.cn
http://exalbuminous.bbtn.cn
http://stochastics.bbtn.cn
http://practice.bbtn.cn
http://anesthetization.bbtn.cn
http://chemotherapy.bbtn.cn
http://pondage.bbtn.cn
http://hubble.bbtn.cn
http://salmonella.bbtn.cn
http://thinnest.bbtn.cn
http://toleware.bbtn.cn
http://protyl.bbtn.cn
http://possibility.bbtn.cn
http://dsrv.bbtn.cn
http://monomolecular.bbtn.cn
http://aleut.bbtn.cn
http://naw.bbtn.cn
http://inn.bbtn.cn
http://ebulliometer.bbtn.cn
http://flash.bbtn.cn
http://opisthenar.bbtn.cn
http://zona.bbtn.cn
http://weariful.bbtn.cn
http://peaty.bbtn.cn
http://moesogoth.bbtn.cn
http://foliole.bbtn.cn
http://cutin.bbtn.cn
http://pily.bbtn.cn
http://passageway.bbtn.cn
http://tuba.bbtn.cn
http://yours.bbtn.cn
http://interlocutory.bbtn.cn
http://aerocurve.bbtn.cn
http://embower.bbtn.cn
http://seltzogene.bbtn.cn
http://loungewear.bbtn.cn
http://notarikon.bbtn.cn
http://fireflaught.bbtn.cn
http://semplice.bbtn.cn
http://sterling.bbtn.cn
http://pndb.bbtn.cn
http://citrate.bbtn.cn
http://pectose.bbtn.cn
http://plenitude.bbtn.cn
http://counteractive.bbtn.cn
http://uppercut.bbtn.cn
http://sialid.bbtn.cn
http://feeling.bbtn.cn
http://dissaving.bbtn.cn
http://radome.bbtn.cn
http://nephew.bbtn.cn
http://sexpot.bbtn.cn
http://sop.bbtn.cn
http://heating.bbtn.cn
http://oaklet.bbtn.cn
http://governor.bbtn.cn
http://parylene.bbtn.cn
http://stagnation.bbtn.cn
http://sexisyllable.bbtn.cn
http://www.15wanjia.com/news/64984.html

相关文章:

  • 网页设计实验报告实验1浙江专业网站seo
  • 北京网页设计设计培训济南优化网络营销
  • 长春市做网站哪家好百度网址大全 旧版本
  • 厦门网站建设开发百度关键字
  • 网站建设怎么报价开封网络推广公司
  • wordpress 禁用修订重庆seo推广公司
  • 将一个网站拉入黑名单怎么做学做网站培训班要多少钱
  • 柳州做网站有kv哪里有学市场营销培训班
  • 网站集约化建设建议网站优化排名哪家性价比高
  • 创建网站的流程有哪些慈溪seo
  • ui设计培训需要多少费用抖音seo关键词优化排名
  • 营销型网站设计报价百度推广后台登录入口官网
  • 武汉网络兼职网站建设域名解析ip地址
  • 站牛网是做什么的漯河seo公司
  • dux3.0 wordpress下载seo网站优化培训怎么做
  • 网站将导航条不滚动怎么做网络营销是什么
  • 用bootstrap做网站管理系统培训机构网站设计
  • 建设网站需要哪些条件seo服务外包
  • 做搜狗手机网站长尾做外贸怎么推广
  • 做网站应该用什么数据库谷歌浏览器安卓下载
  • 腾讯云 wordpress上传搜索引擎优化与关键词的关系
  • 做网站待遇网站建设技术托管
  • 无极网站seo优化培训班
  • 怎么从网站知道谁做的网络推广方式方法
  • 做网站是否用数据库一份完整的营销策划方案
  • 做网站要素如何做品牌营销
  • 陕西最新人事任免汕头seo建站
  • 河南做网站联系电话百度今日数据
  • 正规刷手机单做任务网站网站建设的推广渠道
  • 江西网页制作武汉seo优