当前位置: 首页 > news >正文

大模型从入门到应用——LangChain:代理(Agents)-[代理执行器(Agent Executor):结合使用Agent和VectorStore]

分类目录:《大模型从入门到应用》总目录


代理执行器接受一个代理和工具,并使用代理来决定调用哪些工具以及以何种顺序调用。本文将参数如何结合使用Agent和VectorStore。这种用法是将数据加载到VectorStore中,并希望以Agent的方式与之进行交互。

推荐的方法是创建一个RetrievalQA,然后将其作为整体Agent中的工具来使用。让我们在下面看一下如何实现,我们可以使用多个不同的vectordbs,将Agent作为它们之间的路由器。有两种不同的方法可以实现这一点:

  • 让Agent像正常工具一样使用vectorstores
  • 设置return_direct=True来将Agent真正用作路由

创建VectorStore

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)
texts = text_splitter.split_documents(documents)embeddings = OpenAIEmbeddings()
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.

创建代理

# 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.
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.
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?")

输出:

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.'

仅将Agent用作路由器

如果我们打算将Agent用作路由,并且只想直接返回RetrievalQAChain的结果,我们还可以设置return_direct=True

需要注意的是,在上面的示例中,Agent在查询RetrievalQAChain之后还做了一些额外的工作,我们可以避免这样做,直接返回结果。

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.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.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.'

多跳向量存储推理

由于vectorstores可以很容易地作为Agent中的工具使用,因此可以轻松使用现有的Agent框架回答依赖于vectorstores的多跳问题。

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)
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.
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.ipynb
Thought:I now need to find out if the president mentioned this tool in the state of the union.
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.'

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

http://www.lryc.cn/news/169180.html

相关文章:

  • 【算法题】100040. 让所有学生保持开心的分组方法数
  • TrOCR – 基于 Transformer 的 OCR 入门
  • 单例模式优缺点
  • 【Java 基础篇】Java 字节流详解:从入门到精通
  • Vue记录(下篇)
  • 【测试开发】概念篇 · 测试相关基础概念 · 常见开发模型 · 常见测试模型
  • 1. 快速体验 VSCode 和 CMake 创建 C/C++项目
  • 【JAVA-Day18】用大白话讲解 Java 中的内存机制
  • [Hadoop] start-dfs.sh ssh报错
  • amlogic 多wifi 多bluetooh 兼容方案
  • Apache Hive概述,模拟实现Hive功能,Hive基础架构
  • postgresql|数据库|centos7下基于postgresql-12的主从复制的pgpool-4.4的部署和使用
  • python之pyQt5实例:PyQtGraph的应用
  • Java——键盘输入的几种常见方式
  • Shell脚本中文英文多语言国际化和命令行批处理(bash sh cmd bat)中定义函数的简单写法
  • stringBuffer.append(analyze);使用这个拼接时候如何在字符串参数字符串参数整数参数字符串数组参数内容之间添加空格
  • 点云从入门到精通技术详解100篇-大范围田间场景 3D 点云语义分割研究(续)
  • Mysql详解Explain索引优化最佳实践
  • STM32H7 Azure RTOS
  • 基于LUT查找表方法的图像gamma校正算法FPGA实现,包括tb测试文件和MATLAB辅助验证
  • Function模块
  • Prometheus PromQL数据查询语言
  • 如何将转换器应用于时序模型
  • 数据结构:队列
  • AUTOSAR汽车电子嵌入式编程精讲300篇-基于AUTOSAR架构的AT控制系统研究与实现
  • 计网第五章(运输层)(四)(TCP的流量控制)
  • 【华为OD机试python】查找众数及中位数【2023 B卷|100分】
  • 阿里云无影云电脑详细介绍:价格、使用和功能优势说明
  • 【实践篇】MySQL执行计划详解
  • 二维凸包(Graham) 模板 + 详解