langchain-链
本文参考自大佬教程。
链的作用
连接整合LLM、提示词模板的一个工具,使得调用LLM模型时能够更加简单、方便。
最基础的链 LLMChain
作为极简教程,我们从最基础的概念,与组件开始。LLMChain 是 LangChain 中最基础的链。本课就从 LLMChain 开始,学习链的使用。
LLMChain 接受如下组件:
- LLM
- 提示词模版
使用实例:
- 准备必要的组件
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
llm = OpenAI(temperature=0, openai_api_key="您的有效openai ai key")
prompt = PromptTemplate(
input_variables=["color"],
template="What is the hex code of color {color}?",
)
- 基于组件创建 LLMChain 实例
我们要创建的链,基于提示词模版,提供基于颜色名字询问对应的16进制代码的能力。
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)
- 基于链提问
现在我们利用创建的 LLMChain 实例提问。注意,提问中我们只需要提供第一步中创建的提示词模版变量的值。我们分别提问green,cyan,magento三种颜色的16进制代码。
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加载链
本课以链LLM-Math为例,介绍如何从 LangChainHub 加载链并使用它。这是一个使用LLM和Python REPL来解决复杂数学问题的链。
加载
使用 load_chain 函数从hub加载。
from langchain.chains import load_chain
import os
os.environ['OPENAI_API_KEY'] = "您的有效openai api key"
chain = load_chain("lc://chains/llm-math/chain.json")
注:
load_chain 函数的参数是hub中分享的链的json定义。参数格式:lc://<链json文件在LangChainHub的相对路径>。
以meth的地址为例:
GitHub地址:https://github.com/hwchase17/langchain-hub/blob/master/chains/llm-math/chain.json
参数地址: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

浙公网安备 33010602011771号