LangChain 六 链

欢迎来到我的LangChain系列,如果您也和我一样,想通过学习LangChain开始AI应用开发。那就请一起来学习它的各个功能模块和demo实例。

LangChain 一 hello LLM - 掘金 (juejin.cn)

LangChain 二 模型 - 掘金 (juejin.cn)

LangChain 三 Data Connections - 掘金 (juejin.cn)

LangChain 四 Prompts

LangChain 五 输出解析器

前言

LangChain将复杂的应用流程"链"了起来,今天,我们一起来学习Chain模块。

链有很多好处, 比如它可以让我们的AI应用更模块化,方便调试和协作。链定义了组件的调用顺序,也包括各式的链,来完成我们的应用开发。

LLMChain

LangChain提供了各式的链,各模块化的组件,当然有相应的链来封装。大模型处理这块,最简单的LLMChain上场了。LLMChain包括以下组件:

  • LLM
  • PromptTemplate   LLM 和Prompt 是AI应用的基础,LLMChain将两者结合封装后,向外提供的运行语义就简单多了。
ini 复制代码
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}?",
)

首先我们实例化了llm和prompt。

ini 复制代码
from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)

接着, 将llm和prompt组合起来,实例化LLMChain。

bash 复制代码
print(chain.run("green"))
print(chain.run("cyan"))
print(chain.run("magento"))

最后,我们要向大模型提问,就是向LLMChain提问。

LangChainHub

LangChain也提供了一个Hub 来收集并分享常用的LangChain基本元素。github.com/hwchase17/l..., 点开我们可以玩一些Chain。

  • hello world 链

首先,每个链都有一个json文件。

由前几节的内容,我们应该能够理解这个json文件,它里面定义了prompt 的模板、参数,llm的模型、自由度等参数,output_key 表明输出是文本。看完我们就知道怎么用了。

  1. 提示词模版 - 请求LLM回答一个 topic 参数指定的话题的笑话
  2. LLM - OpenAI的 text-davince-003 模型(包括模型相关参数的设置)
  • llm-math

让我们来玩下数学链。

javascript 复制代码
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")

在这里, 我们选择从hub里加载。我们加载了load_chain模块,从LangChainHub加载llm-math。

arduino 复制代码
chain.run("whats the area of a circle with radius 2?")

基于math chain 提出计算面积的问题。

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

Answer: 12.566370614359172

总结

本文介绍了LangChain的Chain模块,AI模块化的能力确实得到提升。

参考资料

相关推荐
蹦蹦跳跳真可爱5897 分钟前
Python----目标检测(使用YOLO 模型进行线程安全推理和流媒体源)
人工智能·python·yolo·目标检测·目标跟踪
思尔芯S2C13 分钟前
思尔芯携手Andes晶心科技,加速先进RISC-V 芯片开发
人工智能·科技·fpga开发·risc-v·debugging·prototyping·soc validation
风铃儿~21 分钟前
Spring AI 入门:Java 开发者的生成式 AI 实践之路
java·人工智能·spring
晓枫-迷麟23 分钟前
【使用conda】安装pytorch
人工智能·pytorch·conda
爱补鱼的猫猫1 小时前
Pytorch知识点2
人工智能·pytorch·python
deephub1 小时前
提升模型泛化能力:PyTorch的L1、L2、ElasticNet正则化技术深度解析与代码实现
人工智能·pytorch·python·深度学习·机器学习·正则化
小于不是小鱼呀1 小时前
手撕 K-Means
人工智能·算法·机器学习
lilye661 小时前
精益数据分析(95/126):Socialight的定价转型启示——B2B商业模式的价格策略与利润优化
人工智能·数据挖掘·数据分析