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

背景

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 Any

import requests
from langchain.tools import BaseTool


class 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 不予具体实现
        pass

    def 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: object
  properties:
    name:
      type: string
      description: User name
  required:
    - 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的装饰器

  • 20
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Hugo Lei

赏你了,我的一点心意

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

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

打赏作者

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

抵扣说明:

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

余额充值