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

28 篇文章 12 订阅

概述

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

下文讲述的方法是创建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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山鬼谣me

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值