【LangChain】结合代理和向量存储(Combine agents and vector stores)

这篇具有很好参考价值的文章主要介绍了【LangChain】结合代理和向量存储(Combine agents and vector stores)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

概述

本笔记本介绍了如何组合代理和向量存储。其用例是,您已将数据提取到向量存储中,并希望以代理方式与其进行交互。

下文讲述的方法是创建RetrievalQA,然后将其用作整体代理中的工具。

内容

创建向量存储

from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter import CharacterTextSplitter
from langchain.llms import OpenAI
from langchain.chains import RetrievalQA

llm = OpenAI(temperature=0)


from pathlib import Path

relevant_parts = []
for p in Path(".").absolute().parts:
    relevant_parts.append(p)
    if relevant_parts[-3:] == ["langchain", "docs", "modules"]:
        break
doc_path = str(Path(*relevant_parts) / "state_of_the_union.txt")

from langchain.document_loaders import TextLoader

loader = TextLoader(doc_path)
documents = loader.load()
# 初始化加载器
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
# 切割加载的 document
texts = text_splitter.split_documents(documents)

# 初始化 openai 的 embeddings 对象
embeddings = OpenAIEmbeddings()
# document 通过 openai 的 embeddings 对象计算 embedding 向量信息并临时存入 Chroma 向量数据库,用于后续匹配查询
docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union")

""" Running Chroma using direct local API.
    Using DuckDB in-memory for database. Data will be transient.     
"""
# 创建问答对象
state_of_union = RetrievalQA.from_chain_type(
    llm=llm, chain_type="stuff", retriever=docsearch.as_retriever()
)

from langchain.document_loaders import WebBaseLoader

loader = WebBaseLoader("https://beta.ruff.rs/docs/faq/")

docs = loader.load()

ruff_texts = text_splitter.split_documents(docs)
ruff_db = Chroma.from_documents(ruff_texts, embeddings, collection_name="ruff")
# 创建问答对象
ruff = RetrievalQA.from_chain_type(
    llm=llm, chain_type="stuff", retriever=ruff_db.as_retriever()
)

"""     Running Chroma using direct local API.
    Using DuckDB in-memory for database. Data will be transient.

 """

创建代理

# 创建代理

# Create the Agent
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.tools import BaseTool
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper

# 将上面的向量数据库,做成工具列表
tools = [
    Tool(
        name="State of Union QA System",
        func=state_of_union.run,
        description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.",
    ),
    Tool(
        name="Ruff QA System",
        func=ruff.run,
        description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question.",
    ),
]

# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
# verbose=True 显示详细信息,false不显示
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

agent.run(
    "What did biden say about ketanji brown jackson in the state of the union address?"
)

# 这里执行的是“State of Union QA System”工具
""" 
    > Entering new AgentExecutor chain...
     I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address.
    Action: State of Union QA System
    Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address?
    Observation:  Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
    Thought: I now know the final answer
    Final Answer: Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
    
    > Finished chain.

    "Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."

"""

agent.run("Why use ruff over flake8?")

# 这里执行“Ruff QA System”工具
"""
    > Entering new AgentExecutor chain...
     I need to find out the advantages of using ruff over flake8
    Action: Ruff QA System
    Action Input: What are the advantages of using ruff over flake8?
    Observation:  Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.
    Thought: I now know the final answer
    Final Answer: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.
    
    > Finished chain.

    'Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.'
"""

仅将代理用作路由器

#请注意,在上面的示例中,代理在查询 RetrievalQAChain 后做了一些额外的工作。您可以避免这种情况,直接返回结果。

如果您打算将代理用作路由器并且只想直接返回,RetrievalQAChain的结果,您也可以设置return_direct=True

tools = [
    Tool(
        name="State of Union QA System",
        func=state_of_union.run,
        description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question.",
        return_direct=True,
    ),
    Tool(
        name="Ruff QA System",
        func=ruff.run,
        description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question.",
        return_direct=True,
    ),
]

agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)

agent.run(
    "What did biden say about ketanji brown jackson in the state of the union address?"
)

"""
    > Entering new AgentExecutor chain...
     I need to find out what Biden said about Ketanji Brown Jackson in the State of the Union address.
    Action: State of Union QA System
    Action Input: What did Biden say about Ketanji Brown Jackson in the State of the Union address?
    Observation:  Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence.
   # 注意这里,少了Observation: xxxx
   # 注意这里,少了Thought:xxxx
    
    > Finished chain.

    " Biden said that Jackson is one of the nation's top legal minds and that she will continue Justice Breyer's legacy of excellence."
"""

agent.run("Why use ruff over flake8?")

"""
    > Entering new AgentExecutor chain...
     I need to find out the advantages of using ruff over flake8
    Action: Ruff QA System
    Action Input: What are the advantages of using ruff over flake8?
    Observation:  Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.
    # 注意这里,少了Observation: xxxx
    # 注意这里,少了Thought: xxxx
    
    > Finished chain.

    ' Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quality tools natively, including isort, yesqa, eradicate, and most of the rules implemented in pyupgrade. Ruff also supports automatically fixing its own lint violations, which Flake8 does not.'
"""

多跳向量存储推理

本质上就是一个Prompt,会用自己推理使用两个(多个)工具。

# 拿上面工具而言
tools = [
    Tool(
        name="State of Union QA System",
        func=state_of_union.run,
        description="useful for when you need to answer questions about the most recent state of the union address. Input should be a fully formed question, not referencing any obscure pronouns from the conversation before.",
    ),
    Tool(
        name="Ruff QA System",
        func=ruff.run,
        description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before.",
    ),
]

# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(
    tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
# 一个Prompt,涉及到了上面两个工具
agent.run(
    "What tool does ruff use to run over Jupyter Notebooks? Did the president mention that tool in the state of the union?"
)

"""
    > Entering new AgentExecutor chain...
     I need to find out what tool ruff uses to run over Jupyter Notebooks, and if the president mentioned it in the state of the union.
    # 注意这个使用的工具2
    Action: Ruff QA System
    Action Input: What tool does ruff use to run over Jupyter Notebooks?
    Observation:  Ruff is integrated into nbQA, a tool for running linters and code formatters over Jupyter Notebooks. After installing ruff and nbqa, you can run Ruff over a notebook like so: > nbqa ruff Untitled.html
    Thought: I now need to find out if the president mentioned this tool in the state of the union.
    # 注意这个使用的工具1
    Action: State of Union QA System
    Action Input: Did the president mention nbQA in the state of the union?
    Observation:  No, the president did not mention nbQA in the state of the union.
    Thought: I now know the final answer.
    Final Answer: No, the president did not mention nbQA in the state of the union.
    
    > Finished chain.

    'No, the president did not mention nbQA in the state of the union.'
"""

总结

文本讲述的是将agent向量存储结合起来使用。

其实和用PDF当做知识源是一个思路。

  1. 先加载知识源
  2. 将知识源用embeddings,进行相关性计算,得到可搜索对象。
  3. 将可搜索对象,llm等参数,传入RetrievalQA.from_chain_type,得到可用知识库
  4. 将知识库制作为工具
  5. 创建agent,并制定工具
  6. 运行代理

参考地址:
https://python.langchain.com/docs/modules/agents/how_to/agent_vectorstore文章来源地址https://www.toymoban.com/news/detail-542589.html

到了这里,关于【LangChain】结合代理和向量存储(Combine agents and vector stores)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Langchain使用介绍之 - 基于向量存储进行检索

    Text Embedding Models   如何将一段Document转换成向量存储到向量数据库中,首先需要了解Langchain提供了哪些将文本转换成向量的model,langchian提供了很多将自然语言转换成向量的的模型,如下图所示,除了下图列举的model,更多支持的model可参考官网信息。    这里将以Langchain提供

    2024年02月09日
    浏览(42)
  • 使用langchain与你自己的数据对话(二):向量存储与嵌入

      之前我以前完成了“使用langchain与你自己的数据对话(一):文档加载与切割”这篇博客,没有阅读的朋友可以先阅读一下,今天我们来继续讲解deepleaning.AI的在线课程“LangChain: Chat with Your Data”的第三门课:向量存储与嵌入。 Langchain在实现与外部数据对话的功能时需要经历

    2024年02月15日
    浏览(64)
  • 大模型从入门到应用——LangChain:索引(Indexes)-[向量存储器(Vectorstores)]

    分类目录:《大模型从入门到应用》总目录 LangChain系列文章: 基础知识 快速入门 安装与环境配置 链(Chains)、代理(Agent:)和记忆(Memory) 快速开发聊天模型 模型(Models) 基础知识 大型语言模型(LLMs) 基础知识 LLM的异步API、自定义LLM包装器、虚假LLM和人类输入LLM(

    2024年02月07日
    浏览(51)
  • 自然语言处理从入门到应用——LangChain:索引(Indexes)-[向量存储器(Vectorstores)]

    分类目录:《大模型从入门到应用》总目录 LangChain系列文章: 基础知识 快速入门 安装与环境配置 链(Chains)、代理(Agent:)和记忆(Memory) 快速开发聊天模型 模型(Models) 基础知识 大型语言模型(LLMs) 基础知识 LLM的异步API、自定义LLM包装器、虚假LLM和人类输入LLM(

    2024年02月12日
    浏览(70)
  • LangChain 4用向量数据库Faiss存储,读取YouTube的视频文本搜索Indexes for information retrieve

    接着前面的Langchain,继续实现读取YouTube的视频脚本来问答Indexes for information retrieve LangChain 实现给动物取名字, LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字 LangChain 3使用Agent访问Wikipedia和llm-math计算狗的平均年龄 引用向量数据库Faiss 查看OpenAI model main.p

    2024年02月05日
    浏览(58)
  • langchain agent

    每一步action,可以是另外一个chain, 核心思想:工具如果需要多种输入,也需要将参数一起构建进prompt当中 prompt

    2024年02月10日
    浏览(31)
  • LangChain(5)Conversational Agents

    Large Language Models (LLMs) 在语义知识方面表现不错,但也有一些不足,如:不能正确计算数学公式、无法获取最新知识新闻 通过 Agents 可以赋予 LLMs 更多能力,让LLM能够计算、上网查询 上面的 tools 中只有math_tool,所以 zero_shot_agent 只能做计算,不能回答其它常识问题,可以在

    2024年02月16日
    浏览(37)
  • LangChain(6)构建用户自己的Agent

    LangChain 中有一些可用的Agent内置工具,但在实际应用中我们可能需要编写自己的Agent。 输出的答案为 49.03,是个错误答案,实际上为 49.07=(7.81 * 2) * pi 可见模型并没有使用我们定义的 Circumference calculator 进行计算,而是LLM模型自己进行了推理,但LLM不善于数据计算,所以最后的

    2024年02月16日
    浏览(46)
  • LangChain Agent 执行过程解析 OpenAI

    简单来说,用户像LangChain输入的内容未知。此时可以有一套工具集合(也可以自定义工具),将这套自定义工具托管给LLM,让其自己决定使用工具中的某一个(如果存在的话) 首先,这里自定义了两个简单的工具 接下来是针对于工具的简单调用:注意,这里使用OpenAI temperature=0 需要

    2023年04月24日
    浏览(31)
  • 【Langchain Agent研究】SalesGPT项目介绍(五)

    【Langchain Agent研究】SalesGPT项目介绍(四)-CSDN博客                 上节课,我们分析了一下salesGPT项目里源代码的一些问题,重新写了一个运行方法,换了一个模型并修改了一些源代码开始把项目跑起来了,我们已经可以通过console和模型进行对话了。         我们

    2024年02月19日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包