LangChain 中的链

175次阅读
没有评论

链(chain)是 LangChain 中的一个重要概念,它可以将 LLM(大型语言模型)进行串联,或者将链与链之间串联起来。链大大简化了复杂应用程序的实现,并使其模块化,这也使调试、维护和改进应用程序变得更容易。

基础的链:LLMChain

最基础的链是 LLMChain,它接受 LLM、提示词模版等组件,然后返回 LLM 的回复。

实跑代码

以下是一个使用 LLMChain 的简单示例:

from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain

# 创建 LLM 实例
llm = OpenAI(temperature=0, openai_api_key="YOUR_API_KEY")

# 创建提示词模版
prompt = PromptTemplate(input_variables=["color"],
    template="What is the hex code of color {color}?",
)

# 创建 LLMChain 实例
chain = LLMChain(llm=llm, prompt=prompt)

# 基于链提问
print(chain.run("green"))
print(chain.run("cyan"))
print(chain.run("magento"))

输出:

The hex code of color green is #00FF00.
The hex code of color cyan is #00FFFF.
The hex code for the color Magento is #E13939.

从 LangChainHub 加载链

LangChainHub 是一个托管各种 LangChain 组件的项目,其中包括链。您可以使用 load_chain 函数从 LangChainHub 加载链。

from langchain.chains import load_chain
import os

# 设置 OpenAI API Key
os.environ['OPENAI_API_KEY'] = "YOUR_API_KEY"

# 加载链
chain = load_chain("lc://chains/llm-math/chain.json")

# 基于链提问
chain.run("whats the area of a circle with radius 2?")

输出:

> Entering new LLMMathChain chain...
whats the area of a circle with radius 2?
Answer: 12.566370614359172
> Finished chain.

Answer: 12.566370614359172

作业

使用今天学到的用法,自己跑一下代码,然后将结果截图分享出来。

正文完
 
评论(没有评论)