小工具知识网

当前位置: 首页 > 行业知识 > LangChain大模型应用落地实践(二):使用LLMs模块接入自定义大模型,以ChatGLM为例

行业知识

LangChain大模型应用落地实践(二):使用LLMs模块接入自定义大模型,以ChatGLM为例

2026-11-28 15:09:17 来源:互联网转载

angChain���本:0.0.147 ;(没想到第二更LangChain已经更新到147了)

一、国内外大模型发布现状

图1 大模型时间线(2023-arxiv-A Survey of Large Language Models)

模型名称企业/高校发布时间
ERNIE Bot(文心一言)百度2023年3月
ChatGLM清华大学2023年3月
通义千问阿里2023年4月
MOSS复旦大学2023年4月

从图1中可以看出,大模型时代的起始最早可以追溯到2019年Google推出的T5大模型,直到ChatGPT在22年底推出,23年初开放测试后爆火。至此,真正进入大模型的高速发展时期。

2023年4月,OpenAI API进一步封锁国内用户的使用,身边挺多朋友的OpenAI账号被封。因此,我们的目光陆续转移到国内的大模型。国内的大语言模型主要包括了上表中的几个,其中清华大学发布的ChatGLM-6B是比较平民的大模型版本,在保证一定的效果的基础上也支持单卡部署,是很好的实验Baseline。

从ChatGLM Github[ChatGLM-6B, Github]的介绍中可以知道,其硬件需求一张RTX3090就能满足。

量化等级最低GPU现存(推理)最低GPU显存(高效参数微调)
FP1613GB14GB

二、LLMs接入OpenAI

虽然OpenAI API的使用已经越来越困难,但我还是循例写一下这部分的接入。

在OpenAI官网注册,获得对应的API key。

2.1 Python环境依赖

pip install langchain==0.0.147pip install openai==0.27.4

2.2 使用LangChain调用GPTs

import osfrom langchain.schema import HumanMessagefrom langchain.chat_models import ChatOpenAI# global environmentos.environ["OPENAI_API_KEY"] = "sk-*********************************"# llm initializationllm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)while True:    human_input = input("(human): ")    human_input = [HumanMessage(content=human_input)]    ai_output = llm(human_input)    print(f"(ai): {ai_output.content}")

访问如果需要代理,可以通过openai包进行配置,代码如下所示:

import osimport openaifrom langchain.schema import HumanMessagefrom langchain.chat_models import ChatOpenAIopenai.proxy = {    "http": "{proxy_ip}:{port}"}# global environmentos.environ["OPENAI_API_KEY"] = "sk-*********************************"# llm initializationllm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)while True:    human_input = input("(human): ")    human_input = [HumanMessage(content=human_input)]    ai_output = llm(human_input)    print(f"(ai): {ai_output.content}")

三、LLMs接入ChatGLM

ChatGLM是清华大学团队推出的平民大模型,使用RTX3090单卡即可部署,代码库开源,是目前大模型的最佳平替。

3.1 ChatGLM 本地部署

开发环境准备

requirements.txt:

  • 从ChatGLM代码库中复制它的requirements.txt下来;
  • 参考:https://github.com/THUDM/ChatGLM-6B/blob/main/requirements.txt;
    pip install -r requirements.txt

    模型文件准备

    方法1:直接从huggingface模型仓库拉取模型文件(需要先安装Git LFS,拉取速度很慢,不建议);

    git clone https://huggingface.co/THUDM/chatglm-6b

    方法2:从huggingface模型残酷拉取模型实现,然后从清华仓库下载模型参数文件,然后替换到chatglm-6b文件夹中;

    GIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/THUDM/chatglm-6b# 下载模型参数文件...mv chatglm-6b/* THUDM/chatglm-6b/

    方法3:点赞+收藏+关注,并评论,我会私信分享模型文件的百度云盘链接;

    模型本地调用

    一切准备就绪后,我们可以通过下列代码在本地测试ChatGLM;(记得根据实际情况修改使用的显卡参数:CUDA_VISIBLE_DEVICES)

    import osfrom transformers import AutoTokenizer, AutoModelos.environ["CUDA_VISIBLE_DEVICES"] = "2"tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True)model = AutoModel.from_pretrained("THUDM/chatglm-6b", trust_remote_code=True).half().cuda()model = model.eval()human_input = "你好"response, history = model.chat(tokenizer, human_input, history=[])print(f"Human: {human_input}")print(f"AI: {response}")

    运行后可以得到模型的下列输出:

    Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████| 8/8 [00:07 Dict:        """构造请求体        """        query = {            "human_input": prompt        }        return query    @classmethod    def _post(cls, url: str,        query: Dict) -> Any:        """POST请求        """        _headers = {"Content_Type": "application/json"}        with requests.session() as sess:            resp = sess.post(url,                 json=query,                 headers=_headers,                 timeout=60)        return resp        def _call(self, prompt: str,         stop: Optional[List[str]] = None) -> str:        """_call        """        # construct query        query = self._construct_query(prompt=prompt)        # post        resp = self._post(url=self.url,            query=query)                if resp.status_code == 200:            resp_json = resp.json()            predictions = resp_json["response"]            return predictions        else:            return "请求模型"         @property    def _identifying_params(self) -> Mapping[str, Any]:        """Get the identifying parameters.        """        _param_dict = {            "url": self.url        }        return _param_dictif __name__ == "__main__":    llm = ChatGLM()    while True:        human_input = input("Human: ")        begin_time = time.time() * 1000        # 请求模型        response = llm(human_input, stop=["you"])        end_time = time.time() * 1000        used_time = round(end_time - begin_time, 3)        logging.info(f"chatGLM process time: {used_time}ms")        print(f"ChatGLM: {response}")

    使用LLM模块封装我们的模型接口的一个好处是有利于后续跟LangChain的其他模块协同,在这里给大家举一个LangChain Cache的例子,LangChain给LLM模块配置了Cache,如果同一个问题被第二次提问,模型可以快速给出答案。

    启动Cache,需要在脚本中增加这两行代码即可:

    from langchain.cache import InMemoryCache# 启动llm的缓存langchain.llm_cache = InMemoryCache()

    启动Cache后,ChatGLM的访问效果如下所示,当第二次请求模块同一个问题时,模块处理用户问题所用的时间少了一个数量级:

    Human: 你好INFO:root:chatGLM process time: 993.685msChatGLM: 你好 !我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。Human: 你好INFO:root:chatGLM process time: 0.116msChatGLM: 你好 !我是人工智能助手 ChatGLM-6B,很高兴见到你,欢迎问我任何问题。

    Reference

    • [ChatGLM-6B, Github] https://github.com/THUDM/ChatGLM-6B
    • [Survey of LLM, arxiv, 2023] A Survey of Large Language Models

      一起学AI,关注我 持续更新中

       

上一篇:火箭下载秘籍,轻松掌握高效下载技巧!

下一篇:服务器电脑怎么装机械硬盘?