背景

想基于ChatGLM3-6B用LangChain做LLM应用,需要先了解下LangChain中对LLM的封装。本文以一个hello world的封装来示例。

LangChain中对LLM的封装

继承关系:BaseLanguageModel——》BaseLLM——》LLM

LLM类

简化和LLM的交互

_call抽象方法定义

    @abstractmethod
    def _call(
        self,
        prompt: str,
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> str:
        """Run the LLM on the given prompt and input."""

 BaseLLM类

BaseLLM类其实有两个abstract方法:_generate方法和_llm_type方法

注意:LLM类仅实现了_generate方法,未实现_llm_type方法

    @abstractmethod
    def _generate(
        self,
        prompts: List[str],
        stop: Optional[List[str]] = None,
        run_manager: Optional[CallbackManagerForLLMRun] = None,
        **kwargs: Any,
    ) -> LLMResult:
        """Run the LLM on the given prompts."""

    @property
    @abstractmethod
    def _llm_type(self) -> str:
        """Return type of llm."""

BaseLanguageModel类

和语言模型交互的基础抽象类。

    """Abstract base class for interfacing with language models.

    All language model wrappers inherit from BaseLanguageModel.

    """

 LangChain封装自定义的LLM

封装一个MyLLM类,继承自LLM类,实现最简单的hello world功能。

需要实现两个函数:

  1. _llm_type方法
  2. _call方法
from typing import Any, List, Optional
from langchain.llms.base import LLM
from langchain_core.callbacks import CallbackManagerForLLMRun


class MyLLM(LLM):

    def __init__(self):
        super().__init__()

    @property
    def _llm_type(self) -> str:
        return "MyLLM"

    def _call(self, prompt: str, stop: Optional[List[str]] = None, run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any) -> str:
        if len(prompt) < 10:
            return prompt
        else:
            return prompt[:10]

mllm = MyLLM()
print(mllm._llm_type)
# mllm._llm_type = "haha" _llm_type该属性是无法被修改的
print(mllm("hello world!"))

关于@property

@property常用在实例方法前,目的在于把该实例方法转换为同名的只读属性,方法可以像属性一样被访问。

@property的作用主要有两个:

  • @property装饰的只读属性不能被随意篡改
  • 相比于类的普通属性,@property装饰的只读属性可以添加逻辑语句,例如:

@property
def enable(self):
    return self.age > 10

 参考

  1. LLM大语言模型(八):ChatGLM3-6B使用的tokenizer模型BAAI/bge-large-zh-v1.5-CSDN博客 
  2. LLM大语言模型(七):部署ChatGLM3-6B并提供HTTP server能力
  3. LLM大语言模型(四):在ChatGLM3-6B中使用langchain_chatglm3-6b langchain-CSDN博客
  4. LLM大语言模型(一):ChatGLM3-6B本地部署-CSDN博客
Logo

分享最新的 NVIDIA AI Software 资源以及活动/会议信息,精选收录AI相关技术内容,欢迎大家加入社区并参与讨论。

更多推荐