自然语言处理从入门到应用——LangChain:链(Chains)-[通用功能:链的保存(序列化)与加载(反序列化)]

分类目录:《自然语言处理从入门到应用》总目录


本文介绍了如何将链保存(序列化)到磁盘和从磁盘加载(反序列化)。我们使用的序列化格式是jsonyaml。目前,只有一些链支持这种类型的序列化。随着时间的推移,我们将增加支持的链条数量。

将链保存(序列化)到磁盘

首先,让我们可以使用.save方法将链保存到磁盘,并指定一个带有jsonyaml扩展名的文件路径。

复制代码
from langchain import PromptTemplate, OpenAI, LLMChain
template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate(template=template, input_variables=["question"])
llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0), verbose=True)

llm_chain.save("llm_chain.json")

现在让我们来看看保存的文件中的内容:

csharp 复制代码
!cat llm_chain.json

输出:

csharp 复制代码
{
    "memory": null,
    "verbose": true,
    "prompt": {
        "input_variables": [
            "question"
        ],
        "output_parser": null,
        "template": "Question: {question}\n\nAnswer: Let's think step by step.",
        "template_format": "f-string"
    },
    "llm": {
        "model_name": "text-davinci-003",
        "temperature": 0.0,
        "max_tokens": 256,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "n": 1,
        "best_of": 1,
        "request_timeout": null,
        "logit_bias": {},
        "_type": "openai"
    },
    "output_key": "text",
    "_type": "llm_chain"
}

从磁盘加载(反序列化)链

我们可以使用load_chain方法从磁盘加载链:

csharp 复制代码
from langchain.chains import load_chain
chain = load_chain("llm_chain.json")
chain.run("whats 2 + 2")

日志输出:

复制代码
> Entering new LLMChain chain...
Prompt after formatting:
Question: whats 2 + 2

Answer: Let's think step by step.

> Finished chain.

输出:

复制代码
' 2 + 2 = 4'

分别保存组件

在上面的例子中我们可以看到提示和LLM配置信息与整个链条保存在同一个json中,但我们也可以将它们分开保存。这通常有助于使保存的组件更加模块化。为了做到这一点,我们只需要指定llm_path而不是llm组件,并且指定prompt_path而不是prompt组件。

csharp 复制代码
llm_chain.prompt.save("prompt.json")

输入:

csharp 复制代码
!cat prompt.json

输出:

csharp 复制代码
{
    "input_variables": [
        "question"
    ],
    "output_parser": null,
    "template": "Question: {question}\n\nAnswer: Let's think step by step.",
    "template_format": "f-string"
}

输入:

复制代码
llm_chain.llm.save("llm.json")

输入:

复制代码
!cat llm.json

输出:

复制代码
{
    "model_name": "text-davinci-003",
    "temperature": 0.0,
    "max_tokens": 256,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0,
    "n": 1,
    "best_of": 1,
    "request_timeout": null,
    "logit_bias": {},
    "_type": "openai"
}

输入:

复制代码
config = {
    "memory": None,
    "verbose": True,
    "prompt_path": "prompt.json",
    "llm_path": "llm.json",
    "output_key": "text",
    "_type": "llm_chain"
}

import json

with open("llm_chain_separate.json", "w") as f:
    json.dump(config, f, indent=2)

输入:

复制代码
!cat llm_chain_separate.json

输出:

复制代码
{
  "memory": null,
  "verbose": true,
  "prompt_path": "prompt.json",
  "llm_path": "llm.json",
  "output_key": "text",
  "_type": "llm_chain"
}

我们可以以相同的方式加载它:

csharp 复制代码
chain = load_chain("llm_chain_separate.json")
chain.run("whats 2 + 2")

日志输出:

复制代码
> Entering new LLMChain chain...
Prompt after formatting:
Question: whats 2 + 2

Answer: Let's think step by step.

> Finished chain.

输出:

复制代码
' 2 + 2 = 4'

从LangChainHub加载

本节介绍如何从LangChainHub加载链。

csharp 复制代码
from langchain.chains import load_chain

chain = load_chain("lc://chains/llm-math/chain.json")
chain.run("whats 2 raised to .12")

日志输出:

复制代码
> Entering new LLMMathChain chain...
whats 2 raised to .12
Answer: 1.0791812460476249
> Finished chain.

输出:

复制代码
'Answer: 1.0791812460476249'

有时候链会需要额外的参数,这些参数在链序列化时未包含在内。例如,一个用于对向量数据库进行问答的链条将需要一个向量数据库作为参数。

csharp 复制代码
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import CharacterTextSplitter
from langchain import OpenAI, VectorDBQA
from langchain.document_loaders import TextLoader
loader = TextLoader('../../state_of_the_union.txt')
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)

embeddings = OpenAIEmbeddings()
vectorstore = Chroma.from_documents(texts, embeddings)
# Running Chroma using direct local API.
# Using DuckDB in-memory for database. Data will be transient.

chain = load_chain("lc://chains/vector-db-qa/stuff/chain.json", vectorstore=vectorstore)
query = "What did the president say about Ketanji Brown Jackson"
chain.run(query)

输出:

复制代码
" The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans, and will continue Justice Breyer's legacy of excellence."

参考文献:

1\] LangChain官方网站:https://www.langchain.com/ \[2\] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/ \[3\] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

相关推荐
Blossom.118几秒前
用一颗MCU跑通7B大模型:RISC-V+SRAM极致量化实战
人工智能·python·单片机·嵌入式硬件·opencv·机器学习·risc-v
mit6.8243 分钟前
[GazeTracking] 摄像头交互与显示 | OpenCV
人工智能·opencv·交互
Brianna Home33 分钟前
从“码农”到“导演”:AI结对编程如何重塑软件工程范式
大数据·人工智能·深度学习·自然语言处理·chatgpt
oe101933 分钟前
实测Triton-Copilot:AI如何助力高性能算子开发
人工智能·pytorch·copilot·vibecoding·flagos
IT_陈寒39 分钟前
JavaScript性能优化:3个被低估的V8引擎技巧让你的代码提速50%
前端·人工智能·后端
hazy1k1 小时前
K230基础-录放音频
人工智能·stm32·单片机·嵌入式硬件·音视频·k230
众趣科技2 小时前
数字孪生重构智慧园区:众趣科技何以成为 VR 园区领域标杆
人工智能·3d·智慧城市·空间计算
心勤则明3 小时前
Spring AI 会话记忆实战:从内存存储到 MySQL + Redis 双层缓存架构
人工智能·spring·缓存
ARM+FPGA+AI工业主板定制专家5 小时前
基于GPS/PTP/gPTP的自动驾驶数据同步授时方案
人工智能·机器学习·自动驾驶
长鸳词羡5 小时前
wordpiece、unigram、sentencepiece基本原理
人工智能