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

LLM大语言模型(四):在ChatGLM3-6B中使用langchain

目录

  • 背景
  • 准备工作
  • 工具添加
    • LangChain 已实现工具
      • Calculator、Weather Tool配置
    • 自定义工具
      • 自定义kuakuawo Agent
  • 多工具使用
  • 参考

背景

LangChain是一个用于开发由语言模型驱动的应用程序的框架。它使应用程序能够:

  1. 具有上下文意识:将语言模型与上下文源(提示指令,少量示例,基于其响应的内容等)联系起来。
  2. 推理:依靠语言模型进行推理(关于如何根据提供的上下文进行回答,采取什么行动等)。

相信大家都很熟悉LangChain里很流行的两个概念Chain和Agent,本文将介绍在ChatGLM3-6B里是如何使用LangChain的。

准备工作

进入如下目录: cd langchain_demo

修改模型文件的路径:在 main.py 文件中,修改 model_path = ¥你本地的模型文件路径¥ 路径,也可以填写 THUDM/chatglm3-6b 自动下载模型(推荐使用本地模型,如果你能使用魔法当我没说)。
模型下载参考:LLM大语言模型(一):ChatGLM3-6B本地部署

安装依赖:推荐使用conda环境, pip install -r .requirements.txt

工具添加

LangChain 已实现工具

参考 langchain 工具相关函数,在 main.py 中导入工具模块,例如导入 arxiv 工具

run_tool(["arxiv"], llm, ["帮我查询AgentTuning相关工作"
])

Calculator、Weather Tool配置

如果你的 Python 环境中 LangChain 的版本低于 0.0.278 则需要在这两个预定义工具类中实现 _arun 方法
否则将会出现
TypeError: Can't instantiate abstract class Weather with abstract method _arun

示例如下:

class Weather(BaseTool):name = "weather"description = "Use for searching weather at a specific location"async def _arun(self, *args: Any, **kwargs: Any) -> Any:# 用例中没有用到 arun 不予具体实现pass

运行 main.py 文件

python main.py

模型会因找不到 arxiv 工具的 yaml 文件描述而中断,需要用户手动构建 ./Tool/arxiv.yaml 文件。用户可自行添加工具描述,也可以参考 LangChain 对该工具的描述。

arxiv 这个例子而言,参考内容位于 ./Tool/arxiv_example.yaml 文件,可参考该文件构建 Tool/arxiv.yaml 文件(最简单的方式修改名称即可),重新运行模型就能合理调用工具。

有些工具需要导入 API_KEY,按照 langchain 报错添加到环境变量即可。

自定义工具

如果用户想自定义工具,可以参考 Tool/Weather.py 以及 Tool/Weather.yaml 文件,重载新的 Tool 类,实现其对应的 _run() 方法,然后在 main.py 中导入该工具模块,例如导入 Weather 工具,即可以调用

# 对同一个工具调用多次
# 需要 export SENIVERSE_KEY=<YOUR_API_KEY_HERE>
run_tool([Weather()], llm, ["今天北京天气怎么样?","What's the weather like in Shanghai today",
])

自定义kuakuawo Agent

参考Weather.py实现KuaKuaWo.py

import os
from typing import Anyimport requests
from langchain.tools import BaseToolclass KuaKuaWo(BaseTool):name = "kuakuawo"description = "Use for generating a awesome praise for user"def __init__(self):super().__init__()async def _arun(self, *args: Any, **kwargs: Any) -> Any:# 用例中没有用到 arun 不予具体实现passdef get_weather(self, name):return f"{name} 你真的太棒了"  # 简单粗暴直接返回def _run(self, para: str) -> str:return self.get_weather(para)if __name__ == "__main__":kuakuawo_tool = KuaKuaWo()kuakuawo_info = kuakuawo_tool.run("张三")print(kuakuawo_info)

生成kuakuawo.yaml文件

name: kuakuawo
description: Use for generating a awesome praise for user
parameters:type: objectproperties:name:type: stringdescription: User namerequired:- name

main.py中导入KuaKuaWo工具


MODEL_PATH = os.environ.get('MODEL_PATH', '¥你的本地模型路径¥')def run_tool(tools, llm, prompt_chain: List[str]):loaded_tolls = []for tool in tools:if isinstance(tool, str):loaded_tolls.append(load_tools([tool], llm=llm)[0])else:loaded_tolls.append(tool)agent = initialize_agent(loaded_tolls, llm,agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,verbose=True,handle_parsing_errors=True)for prompt in prompt_chain:agent.run(prompt)if __name__ == "__main__":llm = ChatGLM3()llm.load_model(model_name_or_path=MODEL_PATH)# kuakuawo 导入自定义的工具run_tool([KuaKuaWo()], llm, ["请夸一夸隔壁老王"])

运行效果如下:
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████| 7/7 [00:07<00:00, 1.05s/it]

Action:

{"action": "kuakuawo", "action_input": "隔壁老王"}

Observation: 隔壁老王 你真的太棒了

Action:

{"action": "Final Answer", "action_input": "谢谢夸奖,请问有什么我可以帮助您的吗?"}

Finished chain.

多工具使用

可以将多个工具组装在一起让模型自动选择调用,例如

    run_tool([Calculator(), "arxiv", KuaKuaWo()], llm, ["帮我检索GLM-130B相关论文","根号3减去根号二再加上4等于多少?","请夸一夸张三李四"])

Entering new AgentExecutor chain…

Action:

{"action": "arxiv", "action_input": "GLM-130B"}

Observation: Published: 2023-10-25
Title: GLM-130B: An Open Bilingual Pre-trained Model
Authors: Aohan Zeng, Xiao Liu, Zhengxiao Du, Zihan Wang, Hanyu Lai, Ming Ding, Zhuoyi Yang, Yifan Xu, Wendi Zheng, Xiao Xia, Weng Lam Tam, Zixuan Ma, Yufei Xue, Jidong Zhai, Wenguang Chen, Peng Zhang, Yuxiao Dong, Jie Tang
Summary: We introduce GLM-130B, a bilingual (English and Chinese) pre-trained language
model with 130 billion parameters. It is an attempt to open-source a 100B-scale
model at least as good as GPT-3 (davinci) and unveil how models of such a scale
can be successfully pre-trained. Over the course of this effort, we face
numerous unexpected technical and engineering challenges, particularly on loss
spikes and divergence. In this paper, we introduce the training process of
GLM-130B including its design choices, training strategies for both efficiency
and stability, and engineering efforts. The resultant GLM-130B model offers
significant outperformance over GPT-3 175B (davinci) on a wide range of popular
English benchmarks while the performance advantage is not observed in OPT-175B
and BLOOM-176B. It also consistently and significantly outperforms ERNIE TITAN
3.0 260B – the largest Chinese language model – across related benchmarks.
Finally, we leverage a unique scaling property of GLM-130B to reach INT4
quantization without post training, with almost no performance loss, making it
the first among 100B-scale models and more importantly, allowing its effective
inference on 4 × \times ×RTX 3090 (24G) or 8 × \times ×RTX 2080 Ti (11G) GPUs, the
most affordable GPUs required for using 100B-scale models. The GLM-130B model
weights are publicly accessible and its code, training logs, related toolkit,
and lessons learned are open-sourced at
\url{https://github.com/THUDM/GLM-130B/}.
Thought:
Action:

{"action": "Final Answer", "action_input": "根据您的查询,我找到了一篇名为“GLM-130B: An Open Bilingual Pre-trained Model”的论文 ,由Aohan Zeng, Xiao Liu, Zhengxiao Du, Zihan Wang, Hanyu Lai, Ming Ding, Zhuoyi Yang, Yifan Xu, Wendi Zheng, Xiao Xia, Weng Lam Tam, Zixuan Ma, Yufei Xue, Jidong Zhai, Wenguang Chen, Peng Zhang, Yuxiao Dong, Jie Tang等人发表于2023年10月25日。该论文介绍了 一种名为GLM-130B的双语(英语和中文)预训练语言模型,具有1300亿参数。该模型是在尝试开放源代码100B规模的语言模型至少与GPT-3(davinci)相当,并揭示如何成功预训练这样的模型。在本文中,我们介绍了GLM-130B的训练过程,包括其设计选择,对效率和稳定性的训练策略,以及工程努力。GLM-130B模型在大多数流行的英语基准上显著优于GPT-3 175B (davinci),但在OPT-175B和BLOOM-176B上并未观察到性能优势。同时,它也 consistently显著优于ERNIE TITAN 3.0 260B -- 最大的中文语言模型 --  across 相关基准。最后,我们利用GLM-130B的独特标度特性,在 不进行后训练的情况下达到INT4量化,性能损失几乎为零,使其能够在4xRTX 3090 (24G)或8xRTX 2080 Ti (11G) GPU上有效推理,这些GPU是最实惠的用于100B规模模型的GPU。GLM-130B模型权重是公开可用的,其代码,训练日志,相关工具包和相关教训都 open-sourced at\nhttps://github.com/THUDM/GLM-130B/。"
}

Finished chain.

Entering new AgentExecutor chain…

Action:

{"action": "Calculator", "action_input": "sqrt(3)-sqrt(2)+4"}

Observation: 4.317837245195782
Thought:
Action:

{"action": "Final Answer", "action_input": "分析「根号3减去根号二再加上4等于多少」这个问题,我们可以通过请求Python解释器执行「sqrt(3)-sqrt(2)+4」得到答案:4.317837245195782"
}

Finished chain.

Entering new AgentExecutor chain…

Action:

{"action": "kuakuawo", "action_input": "李四"}

Observation: 李四 你真的太棒了
Thought:
Action:

{"action": "Final Answer", "action_input": "谢谢夸奖!请问有什么我可以帮助你的吗?"}

Finished chain.

参考

LLM大语言模型(一):ChatGLM3-6B本地部署
LLM大语言模型(二):Streamlit 无需前端经验也能画web页面
LLM大语言模型(三):使用ChatGLM3-6B的函数调用功能前先学会Python的装饰器

http://www.lryc.cn/news/274433.html

相关文章:

  • Dubbo入门介绍和实战
  • 如何实现无人机识别功能
  • Python学习笔记(四)流程控制方法
  • 【Qt- C++ Qml 交互】
  • ubuntu 20.04 自由切换 python 的版本
  • 程序性能优化全能手册
  • LiveSIPB流媒体国网B接口功能-国网B接口服务安装使用说明
  • 利用小红书笔记详情API:为内容运营提供强大的支持
  • 地理空间分析1——入门Python地理空间分析
  • 哈尔滨爆火的背后有什么值得我们学习的,2024普通人如何创业/2024风口行业
  • element中Tree 树形控件实现多选、展开折叠、全选全不选、父子联动、默认展开、默认选中、默认禁用、自定义节点内容、可拖拽节点、手风琴模式
  • 数据结构OJ实验15-插入排序与交换排序
  • 鹿目标检测数据集VOC格式500张
  • 静态网页设计——电影推荐网(HTML+CSS+JavaScript)
  • ARM CCA机密计算架构软件栈简介
  • C#编程-使用集合
  • linux 设备模型之设备
  • 电源滤波可采用 RC、LC、π 型滤波。电源滤波建议优选磁珠,然后才是电感。同时电阻、电感和磁珠必须考虑其电阻产生的压降。
  • STM32通用定时器-输入捕获-脉冲计数
  • Flutter GetX 之 路由管理
  • 基于单片机的农田灌溉系统(论文+源码)
  • 分布式缓存 -- 基础
  • 云计算复习笔记--期末
  • 【WPF.NET开发】WPF中的焦点
  • 【计算机设计大赛作品】豆瓣电影数据挖掘可视化—信息可视化赛道获奖项目深入剖析【可视化项目案例-22】
  • VS2019启动编辑并继续不起作用(.NET)
  • FFmpeg处理音视频的常用API及一般流程
  • Kotlin协程学习之-01
  • 214.【2023年华为OD机试真题(C卷)】测试用例执行计划(排序题-JavaPythonC++JS实现)
  • 数一下 1到 100 的所有整数中出现多少个数字9并输出这些数字