简单个人网站制作,软文推广法,电子商务网站的构建,网站搭建平台目录 背景准备工作工具添加LangChain 已实现工具Calculator、Weather Tool配置 自定义工具自定义kuakuawo Agent 多工具使用参考 背景
LangChain是一个用于开发由语言模型驱动的应用程序的框架。它使应用程序能够:
具有上下文意识#xff1a;将语言模型与上下文源(提示指令将语言模型与上下文源(提示指令少量示例基于其响应的内容等)联系起来。推理依靠语言模型进行推理(关于如何根据提供的上下文进行回答采取什么行动等)。
相信大家都很熟悉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: Cant instantiate abstract class Weather with abstract method _arun
示例如下
class Weather(BaseTool):name weatherdescription Use for searching weather at a specific locationasync 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_KEYYOUR_API_KEY_HERE
run_tool([Weather()], llm, [今天北京天气怎么样,Whats 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 kuakuawodescription Use for generating a awesome praise for userdef __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], llmllm)[0])else:loaded_tolls.append(tool)agent initialize_agent(loaded_tolls, llm,agentAgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,verboseTrue,handle_parsing_errorsTrue)for prompt in prompt_chain:agent.run(prompt)if __name__ __main__:llm ChatGLM3()llm.load_model(model_name_or_pathMODEL_PATH)# kuakuawo 导入自定义的工具run_tool([KuaKuaWo()], llm, [请夸一夸隔壁老王])运行效果如下 Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████| 7/7 [00:0700: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的装饰器