给rwkv-pytorch 写个chat ui demo

2024-04-20 06:44
文章标签 ui pytorch demo chat 写个 rwkv

本文主要是介绍给rwkv-pytorch 写个chat ui demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

rwkv-pytorch 项目地址

rwkv-pytorch

from nicegui import uimessage_dict = {1: [{"name":"Assistant","text":"你好"}]}
current_name = 1
import aiohttpasync def get_text_async(text="Hello, how are you?"):# 定义API的URLurl = "http://127.0.0.1:8000/generate/"# 定义要发送的数据data = {"text": text}# 发送POST请求async with aiohttp.ClientSession() as session:async with session.post(url, json=data) as response:# 解析响应内容res = await response.json()print(res)return res["response"].split("\n\n")[1][11:]async def send_message_async(text,name):# 获取输入文本input_text = text.value# 将响应消息添加到消息字典message_dict[current_name].append({"name": "User", "text": text.value})# 刷新聊天窗口chat_win_refresh.refresh()# 发送消息并等待响应response_text = await get_text_async(name+":"+input_text+"\n\nAssistant:")# 将响应消息添加到消息字典message_dict[current_name].append({"name":"Assistant","text":response_text})# 刷新聊天窗口chat_win_refresh.refresh()def basic_left_layout():with ui.column():ui.label("这是设置")ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')ui.label('I\'m a column')@ui.refreshable
def chat_win_refresh():with ui.scroll_area().style("height: {}px; width: {}px;".format(500, 725)) as area:for history in message_dict[current_name]:if history["name"]=="User":ui.chat_message(history["text"],name=history["name"],stamp='now',avatar='https://robohash.org/ui',sent=True).style("margin-right: 1px;margin-left: auto;")else:ui.chat_message(history["text"],name=history["name"],stamp='now',avatar='https://robohash.org/ui', sent=False).style("margin-left: 1px;")area.scroll_to(percent=1)def basic_right_layout_children():with ui.column().style("margin-top: 5px;"):with ui.card().style("width:780px; margin-top: 5px;"):chat_win_refresh()with ui.card().style("width:780px;"):with ui.row():text = ui.textarea(label='Text', placeholder='start typing').style("width:605px;")# button 可以是一个图片表示区别机器方可ui.button('Click me!', on_click=lambda: send_message_async(text,"User"))def basic_main_layout():with ui.column().style("margin:auto;"):with ui.card().style("height: {}px; width: {}px;".format(60, 1016)):ui.label("I'm a card")with ui.row():with ui.card().style("height: {}px; width: {}px;margin-top: 25px;".format(725, 200)):with ui.scroll_area().style("height: {}px; width: {}px;".format(800, 200)):basic_left_layout()# with ui.card().style("height: {}px; width: {}px;".format(1000, 800)):with ui.scroll_area().style("height: {}px; width: {}px;".format(1000, 816)):basic_right_layout_children()basic_main_layout()
ui.run(host="127.0.0.1", port=808)

服务

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import torch
from src.model import RWKV_RNN
from src.sampler import sample_logits
from src.rwkv_tokenizer import RWKV_TOKENIZERapp = FastAPI()# 定义请求体模型
class MessageRequest(BaseModel):text: str# 定义响应体模型
class MessageResponse(BaseModel):response: str# 初始化模型和分词器
def init_model():args = {'MODEL_NAME': 'weight/RWKV-x060-World-1B6-v2-20240208-ctx4096','vocab_size': 65536,'device': "cpu",'onnx_opset': '12',}device = args['device']assert device in ['cpu', 'cuda', 'musa', 'npu']if device == "musa":import torch_musaelif device == "npu":import torch_npumodel = RWKV_RNN(args).to(device)tokenizer = RWKV_TOKENIZER("asset/rwkv_vocab_v20230424.txt")return model, tokenizer, devicemodel, tokenizer, device = init_model()# 生成文本的函数
def generate_text(input_text):# 设置续写的初始字符串和参数batch_size = 1TEMPERATURE = 2.5TOP_P = 0.1LENGTH_PER_TRIAL = 50encoded_input = tokenizer.encode([input_text] * batch_size)token = torch.tensor(encoded_input).long().to(device)state = torch.zeros(batch_size, model.state_size[0], model.state_size[1]).to(device)with torch.no_grad():token_out, state_out = model.forward_parallel(token, state)out = token_out[:, -1]for step in range(LENGTH_PER_TRIAL):token_sampled = sample_logits(out, TEMPERATURE, TOP_P)token = torch.cat((token, token_sampled.unsqueeze(1)), 1)with torch.no_grad():out, state = model.forward(token_sampled, state)decoded_sequences = tokenizer.decode(token.cpu().tolist())return decoded_sequences[-1]# 定义路由
@app.post("/generate/", response_model=MessageResponse)
async def create_message(message_request: MessageRequest):try:response_text = generate_text(message_request.text)return MessageResponse(response=response_text)except Exception as e:raise HTTPException(status_code=500, detail=str(e))# 运行FastAPI应用
if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)

简单的请求

import requests# 定义API的URL
url = "http://127.0.0.1:8000/generate/"# 定义要发送的数据
data = {"text": "你好,这是一个测试。"}# 发送POST请求
response = requests.post(url, json=data)# 打印响应内容
print(response.json()["response"])

这篇关于给rwkv-pytorch 写个chat ui demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/919547

相关文章

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

基于CTPN(tensorflow)+CRNN(pytorch)+CTC的不定长文本检测和识别

转发来源:https://swift.ctolib.com/ooooverflow-chinese-ocr.html chinese-ocr 基于CTPN(tensorflow)+CRNN(pytorch)+CTC的不定长文本检测和识别 环境部署 sh setup.sh 使用环境: python 3.6 + tensorflow 1.10 +pytorch 0.4.1 注:CPU环境

PyTorch模型_trace实战:深入理解与应用

pytorch使用trace模型 1、使用trace生成torchscript模型2、使用trace的模型预测 1、使用trace生成torchscript模型 def save_trace(model, input, save_path):traced_script_model = torch.jit.trace(model, input)<

CocoStudio中的UI弄到项目中

1、   与alpah版相比,beta版中更改了创建的脚本,可以自定义项目的目录,接下来我们看看。先上图: 2、项目创建     找到 cocos2dx根目录/tools/project-creator/create_project.py文件,双击运行即可。如果未安装python环境,则需要下载安装。脚本运行起来,会显示一个图形界面,用以设置相应的项目

【Qt6.3 基础教程 17】 Qt布局管理详解:创建直观和响应式UI界面

文章目录 前言布局管理的基础为什么需要布局管理器? 盒布局:水平和垂直排列小部件示例:创建水平盒布局 栅格布局:在网格中对齐小部件示例:创建栅格布局 表单布局:为表单创建标签和字段示例:创建表单布局 调整空间和伸缩性示例:增加弹性空间 总结 前言 当您开始使用Qt设计用户界面(UI)时,理解布局管理是至关重要的。布局管理不仅关系到UI的外观,更直接影响用户交互的体验。本篇博

基于uni-app和图鸟UI开发上门服务小程序

一、技术栈选择 uni-app:我们选择了uni-app作为开发框架,因为它基于Vue.js,允许我们编写一次代码,发布到多个平台,包括iOS、Android、Web以及各种小程序。uni-app的丰富组件库、高效的状态管理以及便捷的预览调试功能,极大提升了开发效率。 图鸟UI:图鸟UI是基于uni-app的UI框架,它提供了大量美观且实用的组件和页面模板,帮助我们快速构建出风格统一、用户体

pytorch国内镜像源安装及测试

一、安装命令:  pip install torch torchvision torchaudio -i https://pypi.tuna.tsinghua.edu.cn/simple  二、测试: import torchx = torch.rand(5, 3)print(x)

PyTorch nn.MSELoss() 均方误差损失函数详解和要点提醒

文章目录 nn.MSELoss() 均方误差损失函数参数数学公式元素版本 要点附录 参考链接 nn.MSELoss() 均方误差损失函数 torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean') Creates a criterion that measures the mean squared err

玩转Web之Json(三)-----easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析

最近做一个项目时,需要在dataGird中插入<input>,即文本输入框,当点击提交时,需要把文本框里填的数据返以及其他列的一些信息以json数组的格式返回到后台,虽然我实现了该功能,但一直没找到简便的方法,今天终于在一位版主的点拨下找到了非常简单的方法。   var all = $("#dg").datagrid("getData");var json =JSON.

玩转Web之easyui(三)-----easy ui dataGird 重新指定url以获取不同数据源信息

如果已经写了一个dataGird并且已经通过url绑定数据源,能不能在其他地方改变url使其从不同数据源获取信息,从而实现查询等操作?答案当然是肯定的,而且仅需要几行代码 $('#btnq').bind('click', function(){ $('#dg').datagrid({ url: '../servlet/Student_search' });//重新指定url$('#dg'