AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


AGI|一文识别LangChain中ChatOpenAI 和OpenAI的区别
发布日期:2024-06-19 07:34:41 浏览次数: 1983



Langchain中ChatOpenAI和OpenAI 的区别

在学习LangChain的过程中,我遇到了一些疑惑。在官方示例中,我发现有些地方使用的是OpenAI模型,而在其他一些地方却使用了ChatOpenAI模型。


我理解,不同的模型可能具有不同的功能和优化点,但具体到OpenAI与ChatOpenAI,它们在性能、特点和使用场景上有何不同呢?


本篇文章为大家分享一下我的研究结果~


 作者 

廖盈盈 | 前端开发工程师

学无止境。加油,奥力给~


Part1

LangChain官网的解释


从LangChain的官网上了解了粗略的概念的,就是OpenAI是属于LLMs,而ChatOpenAI是属于聊天模型。所以要理解ChatOpenAI 和 OpenAI 的区别,就得先知道LLMs和聊天模型的区别。那接下来就打开官网看看这俩到底是什么。


在 LangChain 官网和中文网上的相关解释:


Models

There are two main types of models that LangChain integrates with: LLMs and Chat Models. These are defined by their input and output types.

(LangChain 集成的模型主要有两种类型:LLM 和聊天模型。它们由它们的输入和输出类型定义。)


LLMs

LLMs in LangChain refer to pure text completion models. The APIs they wrap take a string prompt as input and output a string completion. OpenAI’s GPT-3 is implemented as an LLM.

(LangChain中的LLMs指的是纯文本补全模型。它们包装的 API 将字符串提示作为输入并输出字符串完成。OpenAI 的 GPT-3 是作为LLM实施的。)


Chat Models

Chat models are often backed by LLMs but tuned specifically for having conversations. Crucially, their provider APIs use a different interface than pure text completion models. Instead of a single string, they take a list of chat messages as input and they return an AI message as output…

(聊天模型通常由LLMs支持,但专门针对对话进行了调整。至关重要的是,他们的提供商 API 使用与纯文本完成模型不同的接口。他们不是使用单个字符串,而是将聊天消息列表作为输入,并返回 AI 消息作为输出…)


来源:

https://python.langchain.com/docs/modules/model_io/concepts


中文网:


LangChain中有两种类型的语言模型,称为:


  • LLMs: 这是一个以字符串作为输入并返回字符串的语言模型

  • ChatModels: 这是一个以消息列表作为输入并返回消息的语言模型


LLMs的输入/输出简单易懂 - 字符串。但是ChatModels呢?那里的输入是一个ChatMessage列表,输出是一个单独的ChatMessage。一个ChatMessage具有两个必需的组件:


  • content: 这是消息的内容。

  • role: 这是ChatMessage来自的实体的角色。


来源:

https://python.langchain.com.cn/docs/get_started/quickstart


简单的总结一下上边的内容:


  • OpenAI属于LLMs,其输入是字符串,输出也是字符串;


  • ChatOpenAI属于聊天模型,其输入是消息列表,输出是消息列表。



Part2

两者的选择


知道了LLMs和聊天模型的区别,那我们在实际使用的过程中该怎么选择呢?


ChatOpenAI侧重于模型被给与一组消息来构成会话,模型基于这组会话会进行后续的响应。OpenAI是基于问与答,没有会话的概念。


选择ChatOpenAI的情况是需要构建一个能够进行实时对话交流的聊天机器人,用于与用户进行自然语言交互和提供实时的响应。这种情况下,ChatOpenAI可以用于开发聊天机器人、虚拟助手或客服系统等应用。


选择OpenAI的情况是需要进行通用的机器学习和人工智能研究,包括开发和训练各种类型的机器学习模型,如图像识别、自然语言处理、语音识别等。OpenAI提供了一系列强大的机器学习工具和算法,适用于广泛的应用领域,并且能够满足复杂的研究和开发需求。



Part3

LangChain中ChatOpeAI和OpenAI支持的模型


要研究LangChian的ChatOpenAI 和 OpenAI支持的模型。


当然,最直接的探索ChatOpenAI 和 OpenAI和区别方法是查看源码。我们这里打开LangChian中的ChatOpenAI 和 OpenAI的源码来看看这两个支持的模型:


LangChian封装的OpenAI源码中,OpenAI继承一个名为BaseOpenAI的类



在BaseOpenAI中列举了OpenAI的模型,具体的每个模型可以做什么事情可以查看OpenAI官网:https://platform.openai.com/docs/models/overview


@staticmethod
    def modelname_to_contextsize(modelname: str) -> int:
        ...
        model_token_mapping = {
            "gpt-4": 8192,
            "gpt-4-0314": 8192,
            "gpt-4-0613": 8192,
            "gpt-4-32k": 32768,
            "gpt-4-32k-0314": 32768,
            "gpt-4-32k-0613": 32768,
            "gpt-3.5-turbo": 4096,
            "gpt-3.5-turbo-0301": 4096,
            "gpt-3.5-turbo-0613": 4096,
            "gpt-3.5-turbo-16k": 16385,
            "gpt-3.5-turbo-16k-0613": 16385,
            "gpt-3.5-turbo-instruct": 4096,
            "text-ada-001": 2049,
            "ada": 2049,
            "text-babbage-001": 2040,
            "babbage": 2049,
            "text-curie-001": 2049,
            "curie": 2049,
            "davinci": 2049,
            "text-davinci-003": 4097,
            "text-davinci-002": 4097,
            "code-davinci-002": 8001,
            "code-davinci-001": 8001,
            "code-cushman-002": 2048,
            "code-cushman-001": 2048,
        }

        # handling finetuned models
        if "ft-" in modelname:
            modelname = modelname.split(":")[0]

        context_size = model_token_mapping.get(modelname, None)

        if context_size is None:
            raise ValueError(
                f"Unknown model: {modelname}. Please provide a valid OpenAI model name."
                "Known models are: " + ", ".join(model_token_mapping.keys())
            )

        return context_size


OpenAI类的modelname_to_contextsize方法列举了LangChian中OpenAI支持的模型,在其构造方法中可以看到这些模型不是所有的都能支持。


def __new__(cls, **data: Any) -> Union[OpenAIChat, BaseOpenAI]:  # type: ignore
        """Initialize the OpenAI object."""
        model_name = data.get("model_name", "")
        if (
            model_name.startswith("gpt-3.5-turbo") or model_name.startswith("gpt-4")
        ) and "-instruct" not in model_name:
            warnings.warn(
                "You are trying to use a chat model. This way of initializing it is "
                "no longer supported. Instead, please use: "
                "`from langchain_community.chat_models import ChatOpenAI`"
            )
            return OpenAIChat(**data)
        return super().__new__(cls)


在BaseOpenAI的___new___方法中可以看到以模型名“gpt-3.5-turbo”和“gpt-4”开头且不包含“-instruct”的是是chat模型。也就是OpenAI中列举的模型中以gpt-3.5-turbo和gpt-4开头是ChatOpenAI 支持的模型,其余都是OpenAI支持的模型。


OpenAI支持的模型:


  • gpt-3.5-turbo-instruct

  • text-ada-001

  • ada

  • text-babbage-001

  • babbage

  • text-curie-001

  • curie davinci

  • text-davinci-003

  • text-davinci-002

  • code-davinci-002

  • code-davinci-001

  • code-cushman-002

  • code-cushman-001


当然,LangChian可能会更新所支持的OpenAI模型,具体的以最新LangChian源码为准。


ChatOpenAI支持的模型:


  • gpt-4

  • gpt-4-0314

  • gpt-4-0613

  • gpt-4-32k

  • gpt-4-32k-0314

  • gpt-4-32k-0613

  • gpt-3.5-turbo

  • gpt-3.5-turbo-0301

  • gpt-3.5-turbo-0613

  • gpt-3.5-turbo-16k

  • gpt-3.5-turbo-16k-0613



Part4

使用方法


直接官方例子:


(一)OpenAI 的使用:


官方链接:https://python.langchain.com/docs/modules/model_io/llms/quick_start


大型语言模型(LLMs)是LangChain的核心组件。LangChain不为自己的LLMs提供服务,而是提供一个标准接口来与许多不同的LLMs进行交互。


有很多 LLM 提供商(OpenAI、Cohere、Hugging Face 等)——LLM 类为所有提供商提供标准接口。


安装 OpenAI Python 包:


pip install openai


访问 API 需要 API 密钥,您可以通过创建帐户并前往 此处获取该密钥。一旦我们有了密钥,我们就需要通过运行以下命令将其设置为环境变量:


export OPENAI_API_KEY="..."


如果您不想设置环境变量,可以openai_api_key在启动 OpenAI LLM 类时直接通过命名参数传递密钥:


from langchain_openai import OpenAI

llm = OpenAI(openai_api_key="...")


LLMs 实现Runnable 接口,这是LangChain 表达式语言 (LCEL)的基本构建块。这意味着它们支持invoke、 ainvoke、stream、astream、batch、abatch、astream_log调用。


LLM 接受字符串作为输入,或可以强制为字符串提示的对象,包括List[BaseMessage]和PromptValue。


llm.invoke(
    "What are some theories about the relationship between unemployment and inflation?"
)


'\n\n1. The Phillips Curve Theory: This suggests that there is an inverse relationship between unemployment and inflation, meaning that when unemployment is low, inflation will be higher, and when unemployment is high, inflation will be lower.\n\n2. The Monetarist Theory: This theory suggests that the relationship between unemployment and inflation is weak, and that changes in the money supply are more important in determining inflation.\n\n3. The Resource Utilization Theory: This suggests that when unemployment is low, firms are able to raise wages and prices in order to take advantage of the increased demand for their products and services. This leads to higher inflation.'


(二)ChatOpenAI 的使用:


官方链接:https://python.langchain.com/docs/modules/model_io/chat/quick_start


聊天模型是语言模型的变体。虽然聊天模型在底层使用语言模型,但它们使用的接口有点不同。聊天模型没有使用“文本输入、文本输出”的接口,而是使用“聊天消息”作为输入和输出的接口。


与OpenAI一样,ChatOpenAI类也是集成OpenAI官方的模型,所以一样需要一样的密钥。


同样如果不想设置环境变量,可以openai_api_key在启动 OpenAI LLM 类时直接通过命名参数传递密钥:


from langchain_openai import ChatOpenAI

chat = ChatOpenAI(openai_api_key="...")


聊天模型界面基于消息而不是原始文本。LangChain目前支持的消息类型有AIMessage, HumanMessage, SystemMessage,FunctionMessage和ChatMessage- ChatMessage接受任意角色参数。大多数时候,您只需处理HumanMessage、AIMessage和 SystemMessage


聊天模型实现了Runnable 接口,这是LangChain 表达式语言(LCEL)的基本构建块。这意味着它们支持invoke、 ainvoke、stream、astream、batch、abatch、astream_log调用。


聊天模型接受List[BaseMessage]作为输入或可以强制为消息的对象,包括str(转换为HumanMessage)和PromptValue。


from langchain_core.messages import HumanMessage, SystemMessage

messages = [
    SystemMessage(content="You're a helpful assistant"),
    HumanMessage(content="What is the purpose of model regularization?"),
]


chat.invoke(messages)


AIMessage(content="The purpose of model regularization is to prevent overfitting in machine learning models. Overfitting occurs when a model becomes too complex and starts to fit the noise in the training data, leading to poor generalization on unseen data. Regularization techniques introduce additional constraints or penalties to the model's objective function, discouraging it from becoming overly complex and promoting simpler and more generalizable models. Regularization helps to strike a balance between fitting the training data well and avoiding overfitting, leading to better performance on new, unseen data.")



Part5

其他


在探索LangChian的ChatOpenAI 和 OpenAI这两个类时,了解到这两个类使用OpenAI接口不一样, OpenAI使用的是/v1/completions接口,而ChatOpenAI 使用的是/v1/chat/completions。


详细的可以查看OpenAI官网:


https://platform.openai.com/docs/models/model-endpoint-compatibility



53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询