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模块化的能力确实得到提升。

参考资料

相关推荐
FutureUniant2 分钟前
GitHub每日最火火火项目(9.21)
人工智能·计算机视觉·ai·github·音视频
菜♕卷15 分钟前
深度学习-03 Pytorch
人工智能·pytorch·深度学习
明明真系叻17 分钟前
第十二周:机器学习笔记
人工智能·机器学习
AI王也1 小时前
ChatGPT搭上langchain的知识库RAG应用,效果超预期
人工智能·chatgpt·langchain·aigc
沧穹科技1 小时前
音频北斗定位系统有什么用?
人工智能
Bruce小鬼2 小时前
最新版本TensorFlow训练模型TinyML部署到ESP32入门实操
人工智能·python·tensorflow
玖石书3 小时前
ollama安装(ubuntu20.04)
llm·安装·ollama
sp_fyf_20243 小时前
计算机人工智能前沿进展-大语言模型方向-2024-09-20
人工智能·搜索引擎·语言模型
kinlon.liu3 小时前
AI与自然语言处理(NLP):中秋诗词生成
人工智能·自然语言处理
正义的彬彬侠3 小时前
举例说明计算一个矩阵的秩的完整步骤
人工智能·机器学习·矩阵·回归