LangChain 大型语言模型(LLMs)基础
大型语言模型(LLMs)是 LangChain 的核心组件。LangChain 本身不提供大型语言模型,而是提供了一个标准接口,通过该接口我们可以与各种 LLMs 进行交互。LLM 类是专为与 LLM 接口设计的类。有许多 LLM 提供者(如 OpenAI、Cohere、Hugging Face),此类旨在为所有 LLM 提供一个标准接口。
在本文中,我们将专注于通用的 LLM 功能,并演示如何使用 OpenAI LLM 包装器,其功能对于所有 LLM 类型都是通用的。
初始化模型
首先,需要导入 OpenAI 类并实例化一个 LLM 对象。可以通过指定模型名称、温度参数等来配置行为。
from langchain.llms import OpenAI
llm = OpenAI(model_name="text-ada-001", n=2, best_of=2)
生成文本
生成文本(Generate Text)是 LLM 最基本的功能,其传入一个字符串并返回一个字符串:
llm("Tell me a joke")
输出示例:
\n\nWhy did the chicken cross the road?\n\nTo get to the other side.
批量生成
我们还可以用一个输入列表来调用它,得到比仅输入文本更完整的响应。这个完整的响应包括多个顶级响应,以及 LLM 供应商特定的信息。
llm_result = llm.generate(["Tell me a joke", "Tell me a poem"] * 15)
print(len(llm_result.generations))
输出:
30
访问具体的生成结果:
llm_result.generations[0]
输出:
[Generation(text='\n\nWhy did the chicken cross the road?\n\nTo get to the other side!'),
Generation(text='\n\nWhy did the chicken cross the road?\n\nTo get to the other side.')]


