作者: C3P00

  • LangChain 中的链

    链(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

    作业

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

  • 关于LangChain中的Chain

    大家好,我是码农小王,今天给大家带来一篇关于LangChain中的Chain的通俗易懂的Blog。

    什么是Chain?

    Chain可以把多个LLM连接起来,实现链式调用。就像组装乐高积木一样,我们可以把不同的LLM块组装在一起,构建出复杂的AI系统。

    几种常见的Chain

    1. LLMChain

    这是最基础的Chain,它接受LLM和Prompt作为输入,返回LLM生成的回复。可以快速构建一个问答系统。

    1. QACoordinationChain

    这个Chain串联问答系统,当一个LLM无法回答时,将问题传递给下一个LLM,实现多个LLM协作。

    1. SearchChain

    这个Chain实现搜索功能,它将用户查询传给搜索LLM,获取回复后再传给答疑LLM生成完整回复。

    运行示例

    导入必要的模块:

    from langchain.llms import OpenAI
    from langchain.chains import *

    加载LLM:

    llm = OpenAI(openai_api_key='你的key') 

    构建一个LLMChain:

    chain = LLMChain(llm=llm, prompt=prompt)

    提问并获取回复:

    print(chain.run("人生的意义是什么?"))  

    总结

    通过Chain模块,LangChain实现了LLM的链式调用,使构建AI系统变得像组装积木一样简单。希望大家能trying more chains, happy langchaining!

    如果文章对你有帮助,请点赞支持哦!

人生梦想 - 关注前沿的计算机技术 acejoy.com 🐾 步子哥の博客 🐾 背多分论坛 🐾 借一步网
Page Stats: PV: 824 | UV: 489
Last updated: 2025-05-17 02:00:44
沪ICP备2024052574号-1