项目裁缝:使用千问大模型与wxauto实现微信自动聊天

项目裁缝:使用千问大模型与wxauto实现微信自动聊天

1.Qwen-7B-Chat 模型的下载

首先需要下载通义千问的Qwen-7B-Chat的模型文件,其下载地址为阿里官方的大语言模型社区,模搭ModelScope,其中通义千问的Qwen-7B-Chat 的下载和相关介绍的地址为https://modelscope.cn/models/qwen/Qwen-7B-Chat/summary
在这里插入图片描述

千问大模型有两种下载方式,分别是SDK(安装安装工具包下载)与使用git下载。
使用SDK使用的是modelscope库,安装modelscope库的指令为
pip install modelscope

在安装好modelscope库后运行以下代码即可将模型下载到本地,记得将cache_dir修改为模型下载的地址,否则将会下载到默认的.cache/modelscope目录下

from modelscope import snapshot_download
model_dir = snapshot_download('qwen/Qwen-7B-Chat',cache_dir='自己的地址')

2.Qwen-7B-Chat 环境的安装

官方文档中要求的配置环境如下:

  • python 3.8及以上版本
    pytorch 1.12及 以上版本,推荐使用2.0及以上版本
    建议使用CUDA 11.4及以上(GPU用户、flash-attention用户等需要考虑此选项)
    python 3.8 and above
    pytorch 1.12 and above 2.0 and above are recommended
    CUDA 11.4 and above are recommended(this is GPU user,flash-attention user,etc.)
    从要求中可以看出需要下载CUDA与pytorch。
    CUDA 安装可以参考以下文章进行
    CUDA安装及环境配置——最新详细版
    但由于CUDA官网加载过慢,本项目使用的CUDA 11.8是由b站仪酷智能科技提供的百度网盘下载链接如下CUDA11.8及对应CUDNN下载链接:

之后还需要安装modelscope
最后是官方说的运行Qwen-7B所需要安装的依赖。

pip install transformers==4.32.0 accelerate tiktoken einops scipy transformers_stream_generator==0.0.4 peft deepspeed

安装过程中可能会出现DeepSpeed 安装出错的问题,解决方法参考文章Python|Windows 安装 DeepSpeed 安装方法及报错 Unable to pre-compile async_io 处理
主要步骤分为以下几步:

1.克隆 DeepSpeed 仓库

git clone https://github.com/microsoft/DeepSpeed.git

2.使用 PowerShell,进入 DeepSpeed 仓库路径

3.设置环境变量

Set-Item Env:\DS_BUILD_OPS 0

4.编译 DeepSpeed 仓库

执行 build_win.bat 脚本编译,其中在配置环境变量后,也是通过 setup.py 完成编译:.\build_win.bat

5.进入 dist 路径

在编译好后会在DeepSpeed路径下生成一个dist文件,进入文件夹查看安轮子是否存在。

6.安装编译生成的包

pip install deepspeed-0.14.4+eda5075b-py3-none-any.whl

3.运行本地的部署代码实现多轮对话

在安装好环境以及下载了模型文件之后,就可以运行官方的例程代码来观察对话效果,官方的快速开始代码如下:

from modelscope import AutoModelForCausalLM, AutoTokenizer
from modelscope import GenerationConfig

# Note: The default behavior now has injection attack prevention off.
tokenizer = AutoTokenizer.from_pretrained("qwen/Qwen-7B-Chat", trust_remote_code=True)

# use bf16
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, bf16=True).eval()
# use fp16
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True, fp16=True).eval()
# use cpu only
# model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="cpu", trust_remote_code=True).eval()
# use auto mode, automatically select precision based on the device.
model = AutoModelForCausalLM.from_pretrained("qwen/Qwen-7B-Chat", device_map="auto", trust_remote_code=True).eval()

# Specify hyperparameters for generation. But if you use transformers>=4.32.0, there is no need to do this.
# model.generation_config = GenerationConfig.from_pretrained("Qwen/Qwen-7B-Chat", trust_remote_code=True) # 可指定不同的生成长度、top_p等相关超参

# 第一轮对话 1st dialogue turn
response, history = model.chat(tokenizer, "你好", history=None)
print(response)
# 你好!很高兴为你提供帮助。

# 第二轮对话 2nd dialogue turn
response, history = model.chat(tokenizer, "给我讲一个年轻人奋斗创业最终取得成功的故事。", history=history)
print(response)
# 这是一个关于一个年轻人奋斗创业最终取得成功的故事。
# 故事的主人公叫李明,他来自一个普通的家庭,父母都是普通的工人。从小,李明就立下了一个目标:要成为一名成功的企业家。
# 为了实现这个目标,李明勤奋学习,考上了大学。在大学期间,他积极参加各种创业比赛,获得了不少奖项。他还利用课余时间去实习,积累了宝贵的经验。
# 毕业后,李明决定开始自己的创业之路。他开始寻找投资机会,但多次都被拒绝了。然而,他并没有放弃。他继续努力,不断改进自己的创业计划,并寻找新的投资机会。
# 最终,李明成功地获得了一笔投资,开始了自己的创业之路。他成立了一家科技公司,专注于开发新型软件。在他的领导下,公司迅速发展起来,成为了一家成功的科技企业。
# 李明的成功并不是偶然的。他勤奋、坚韧、勇于冒险,不断学习和改进自己。他的成功也证明了,只要努力奋斗,任何人都有可能取得成功。

# 第三轮对话 3rd dialogue turn
response, history = model.chat(tokenizer, "给这个故事起一个标题", history=history)
print(response)
# 《奋斗创业:一个年轻人的成功之路》

4.结合Swift库实现流式输出

使用Swift库实现流式输出需要现下载Swift库安装命令为

pip install ms-swift

而并不是pip install swift,如果你用的是pip install swift安装会安装不上,会出现如下错误,提示你要取下载红帽和Ubtuntu版本的库,但是这是Liunx系统的库,所以安装不上,只有运行pip install ms-swift才能安装成功。
使用本地模型的多轮对话和流式输出的最终代码如下:

from modelscope import AutoModelForCausalLM, AutoTokenizer
from swift.llm import  inference_stream,get_template

model_path = "D:\qwen\Qwen-7B-Chat"

tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", trust_remote_code=True).eval()
template_type = 'qwen'
template = get_template(template_type, tokenizer)
history = None

before_len = 0

while True:
    query = input('User:')
    gen = inference_stream(model, template, query, history)
    print(f'System:', end="")
    for response, h in gen:

        print(response[before_len:],end="")
        before_len = len(response)
        history = h
    print()

本项目Qwen部署及代码参考通义千问本地部署教程 Qwen-1.5-1.8B/7B/14B Windows-详细认真版

5.使用wxauto调取微信聊天记录并发送消息

首先需要安装wxauto库,安装指令为

pip install wxauto

wxauto获取微信窗口信息的方式有两种分别为GetAllNewMessage和GetNextNewMessage,这两种方法用于获取微信主窗口的新消息,返回消息对象列表
GetAllNewMessage方法获取所有新消息代码如下

from wxauto import WeChat

wx = WeChat()

# 获取所有新消息
msgs = wx.GetAllNewMessage()

GetNextNewMessage方法获取下一条新消息代码如下

from wxauto import WeChat

wx = WeChat()

# 获取下一条新消息
msgs = wx.GetNextNewMessage()

这两种方法获取到的msgs数据类型均为dict,结构如下:

{
‘张三’: [msg1, msg2, …],
‘李四’: [msg1, msg2, …],

}

简单发送文字消息主要用到了SendMsg,代码如下

from wxauto import WeChat

wx = WeChat()

# 发送消息给文件传输助手
msg = 'hello, wxauto!'
who = '文件传输助手'
wx.SendMsg(msg=msg, who=who)

wxauto库更多使用方法请参考官方文档wxauto

6.项目缝合

将前面本地部署的千问大模型与wxauto获取实时聊天记录与发送消息相缝合具体代码如下:

from modelscope import AutoModelForCausalLM, AutoTokenizer
from swift.llm import  inference_stream,get_template
from wxauto import WeChat

model_path = "模型路径"

tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", trust_remote_code=True).eval()
template_type = 'qwen'
template = get_template(template_type, tokenizer)
history = None

before_len = 0
wx = WeChat()
while True:
    msgs = wx.GetNextNewMessage()
    if msgs != {}:
        print(msgs)
        print(list(msgs.values()))
        name = list(msgs.values())[0][-1][0]
        xiaoxi = list(msgs.values())[0][-1][1]
        if name != 'Self':
            print('开始生成文字回复')
            query = xiaoxi
            gen = inference_stream(model, template, query, history)
            print(f'System:', end="")
            str1 = ''
            for response, h in gen:
                print(response[before_len:],end="")
                str1 += response[before_len:]
                before_len = len(response)
                history = h
            wx.SendMsg(msg=str1, who=list(msgs.keys())[0])
            print()

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值