昇思25天学习打卡营第13天|MindNLP ChatGLM-6B StreamChat

学AI还能赢奖品?每天30分钟,25天打通AI任督二脉 (qq.com)

MindNLP ChatGLM-6B StreamChat

本案例基于MindNLP和ChatGLM-6B实现一个聊天应用。

1 环境配置

%%capture captured_output
# 实验环境已经预装了mindspore==2.2.14,如需更换mindspore版本,可更改下面mindspore的版本号
!pip uninstall mindspore -y
!pip install -i https://pypi.mirrors.ustc.edu.cn/simple mindspore==2.2.14
!pip install mindnlp
!pip install mdtex2html

配置网络线路

!export HF_ENDPOINT=https://hf-mirror.com

2 代码开发

下载权重大约需要10分钟

from mindnlp.transformers import AutoModelForSeq2SeqLM, AutoTokenizer
import gradio as gr
import mdtex2html

model = AutoModelForSeq2SeqLM.from_pretrained('ZhipuAI/ChatGLM-6B', mirror="modelscope").half()
model.set_train(False)
tokenizer = AutoTokenizer.from_pretrained('ZhipuAI/ChatGLM-6B', mirror="modelscope")

   model.chat 是 ChatGLM-6B 模型自带的方法,用于生成对话。这个方法接受输入的 prompt(即用户输入的初始文本)及其相关参数,并返回生成的响应。

   tokenizer 是一个文本标记器(tokenizer),用于将文本字符串转换成模型可以处理的格式,并且将模型的输出转换回可读文本。具体来说,tokenizer 会将输入的 prompt 转换成 token ids,并在生成响应后将生成的 token ids 转换回文本。token ids 是一组数字,代表原始文本中的每个单词或符号。比如,'你好' 可能会被转换为 [12345, 67890] 这样的 token 序列。 一旦模型生成了响应的 token 序列,`tokenizer` 会将这些 token ids 转换回人类可读的文本。这就是最终的响应。

可以修改下列参数和prompt体验模型

prompt = '你好'
history = []
response, _ = model.chat(tokenizer, prompt, history=history, max_length=20)
response

   prompt 是用户提供的输入文本,它是此次对话的起点。例如,在这段代码中,prompt 是 '你好'。

   history 是一个列表,存储了之前所有的对话记录。有了这个历史记录,模型可以生成与上下文相关的响应。这在进行连续对话时特别有用。

   max_length 参数表示生成的响应的最大长度。这里的 20 指定响应最多包含 20 个 token。

response 会被赋值为模型生成的文本。这就是模型对当前 prompt 和 history 的回答。 _ 表示另一个未使用的返回值,通常是生成过程中使用的一些调试信息或其他数据。

其他测试

def chat_with_bot(prompt, history=[]):
    response, history = model.chat(tokenizer, prompt, history=history, max_length=50)
    return response, history
while True:
    user_input = input("你: ")
    if user_input.lower() == "exit":
        break
    response, history = chat_with_bot(user_input, history)
    print(f"ChatGLM-6B: {response}")
print(f"history: {history}")
你:  1
ChatGLM-6B: Hello! How can I assist you today?
你:  2
ChatGLM-6B: I\'m sorry, could you please provide more context about what you
你:  3
ChatGLM-6B: I
你:  4
ChatGLM-6B: need
你:  5
ChatGLM-6B: Sure
你:  6
ChatGLM-6B: Could
你:  exit
history: [('1', 'Hello! How can I assist you today?'), ('2', "I\\'m sorry, could you please provide more context about what you"), ('3', 'I'), ('4', 'need'), ('5', 'Sure'), ('6', 'Could')]

   MAX_HISTORY_LENGTH = 5
   
   def prune_history(history, max_length):
       if len(history) > max_length:
           return history[-max_length:]
       return history

   def chat_with_bot(prompt, history=[]):
       response, history = model.chat(tokenizer, prompt, history=history, max_length=50)
       history = prune_history(history, MAX_HISTORY_LENGTH)
       return response, history
while True:
    user_input = input("你: ")
    if user_input.lower() == "exit":
        break
    response, history = chat_with_bot(user_input, history)
    print(f"ChatGLM-6B: {response}")
print(f"history: {history}")
你:  1
ChatGLM-6B: Hello! How can I assist you today?
你:  2
ChatGLM-6B: I'm sorry, could you please provide more context about what I
你:  3
ChatGLM-6B: need
你:  4
ChatGLM-6B: Thank
你:  5
ChatGLM-6B: You
你:  6
ChatGLM-6B: For
你:  今天天气怎么样?
ChatGLM-6B: I
你:  谢谢
ChatGLM-6B: 
你:  exit
history: [('4', 'Thank'), ('5', 'You'), ('6', 'For'), ('今天天气怎么样?', 'I'), ('谢谢', '')]

from mindnlp.transformers import AutoModelForSeq2SeqLM, AutoTokenizer
import mindspore
import gradio as gr
import mdtex2html

# 加载模型和分词器
model = AutoModelForSeq2SeqLM.from_pretrained('ZhipuAI/ChatGLM-6B', mirror="modelscope").half()
model.set_train(False)
tokenizer = AutoTokenizer.from_pretrained('ZhipuAI/ChatGLM-6B', mirror="modelscope")

# 定义提示和历史
prompt = '你好'
history = []

# 分词并处理 attention mask
inputs = tokenizer(prompt, return_tensors="ms", padding=True)
attention_mask = inputs["attention_mask"].astype(mindspore.bool_)

try:
    # 与模型进行对话
    response, _ = model.chat(tokenizer, prompt, history=history, max_length=20, attention_mask=attention_mask)
    print(response)
    print(history)
except Exception as e:
    print(f"Error: {e}")

Loading checkpoint shards: 100% 8/8 [00:49<00:00,  5.33s/it]

你好👋!我是人工智能助手 ChatGLM-6B
[]

  • 10
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

109702008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值