LangChain学习文档
Chains(链)
【LangChain】不同的调用方式(Different call methods)
概述
单独使用 LLM 对于简单的应用程序来说是OK的,但更复杂的应用程序需要 LLM链 - 彼此链接或与其他组件链接。
LangChain
为此类“链式”应用提供了Chain
接口。我们将链非常笼统地定义为对组件的调用序列,其中可以包括其他链。基本接口很简单:
class Chain(BaseModel, ABC):
"""Base interface that all chains should implement."""
memory: BaseMemory
callbacks: Callbacks
def __call__(
self,
inputs: Any,
return_only_outputs: bool = False,
callbacks: Callbacks = None,
) -> Dict[str, Any]:
...
这种将组件组合成一个链的想法很简单但很强大。它极大地简化了复杂应用程序的实现并使之更加模块化,从而使调试、维护和改进应用程序变得更加容易。
欲了解更多信息,可以查看:
为什么我们需要chains
链允许我们将多个组件组合在一起以创建一个单一的、连贯的应用程序。例如,我们可以创建一个链,它接受用户输入,使用 PromptTemplate
对其进行格式化,然后将格式化的响应传递给 LLM
。我们可以通过将多个链组合在一起,或者将链与其他组件组合来构建更复杂的链。
开始使用
使用LLMChain
LLMChain
是构建区块链的基础。它采用提示模板(Prompt template
),根据用户输入对其进行格式化,然后返回LLM
的响应。
要使用LLMChain
,首先创建一个提示模板。
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
# temperature=0.9是随机度,0-1,越大随机度越高,信息回答越不准确
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
input_variables=["product"],
template="What is a good name for a company that makes {product}?",
)
我们现在可以创建一个非常简单的链,它将接受用户输入,用它格式化prompt
,然后将其发送给LLM
。
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
# Run the chain only specifying the input variable.
print(chain.run("colorful socks"))
结果:
Colorful Toes Co.
如果有多个变量,可以使用字典(键值对)一次性输入它们。
prompt = PromptTemplate(
input_variables=["company", "product"],
template="What is a good name for {company} that makes {product}?",
)
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run({
'company': "ABC Startup",
'product': "colorful socks"
}))
结果:
Socktopia Colourful Creations.
你也可以在LLMChain
中使用聊天模型:
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
human_message_prompt = HumanMessagePromptTemplate(
prompt=PromptTemplate(
template="What is a good name for a company that makes {product}?",
input_variables=["product"],
)
)
chat_prompt_template = ChatPromptTemplate.from_messages([human_message_prompt])
# 这里创建的是聊天模型
chat = ChatOpenAI(temperature=0.9)
chain = LLMChain(llm=chat, prompt=chat_prompt_template)
print(chain.run("colorful socks"))
结果:
Rainbow Socks Co.
总结
- 创建大模型
llm = OpenAI(temperature=0.9)
- 创建提示:prompt:本质上就是向大模型提出的问题:
prompt = PromptTemplate(
input_variables=["company", "product"],
template="What is a good name for {company} that makes {product}?",
)
- 将
llm、prompt
作为参数,创建chain:chain = LLMChain(llm=llm, prompt=prompt)
- 执行chain:
chain.run("colorful socks")
参考地址: