Getting Started#

这篇笔记将介绍如何使用 LangChain 中的 LLM 类。

LLM 类是专门用于与 LLM(linguistic language model)进行接口交互的类。存在许多 LLM 供应商(例如 OpenAI、Cohere、Hugging Face 等),这个类旨在提供一个通用的标准接口。在文档的这一部分,我们将重点介绍通用 LLM 功能。有关使用特定 LLM 包装器的示例的详细信息,请参见 [How-To 部分]。(how_to_guides.rst).

这篇笔记中,我们将使用 OpenAI 的 LLM 包装器,尽管突出显示的所有功能对于所有 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.'

Generate: 更广义地说,您可以使用输入列表调用它,返回比仅文本更完整的响应。这种完整的响应包括多个高排名的响应,以及 LLM 提供者特定的信息。

llm_result = llm.generate(["Tell me a joke", "Tell me a poem"]*15)
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.')]
llm_result.generations[-1]
[Generation(text="\n\nWhat if love neverspeech\n\nWhat if love never ended\n\nWhat if love was only a feeling\n\nI'll never know this love\n\nIt's not a feeling\n\nBut it's what we have for each other\n\nWe just know that love is something strong\n\nAnd we can't help but be happy\n\nWe just feel what love is for us\n\nAnd we love each other with all our heart\n\nWe just don't know how\n\nHow it will go\n\nBut we know that love is something strong\n\nAnd we'll always have each other\n\nIn our lives."),
 Generation(text='\n\nOnce upon a time\n\nThere was a love so pure and true\n\nIt lasted for centuries\n\nAnd never became stale or dry\n\nIt was moving and alive\n\nAnd the heart of the love-ick\n\nIs still beating strong and true.')]

您还可以访问返回的特定于提供者的信息。这些信息在提供者之间并没有标准化。

llm_result.llm_output
{'token_usage': {'completion_tokens': 3903,
  'total_tokens': 4023,
  'prompt_tokens': 120}}

Number of Tokens: 您还可以估计一个文本在该模型中有多少令牌。这是有用的,因为模型具有上下文长度(并且令牌越多越昂贵),这意味着您需要知道您要传递的文本有多长。

请注意,默认情况下,使用 tiktoken 估计令牌 (除了<3.8的版本以外,均使用HuggingFace令牌处理器)

llm.get_num_tokens("what a joke")
3