如何使用 LangChain 构建一个使用工具的 Agent
本 Notebook 将引导你了解如何使用 LangChain 来增强 OpenAI 模型访问外部工具的能力。特别是,你将能够创建使用自定义工具来回答用户查询的 LLM Agent。
什么是 Langchain?
LangChain 是一个用于开发由语言模型驱动的应用程序的框架。他们的框架使你能够构建分层的、上下文感知并能够作为 Agent 与其环境动态交互的 LLM 驱动的应用程序,从而简化你的代码并为你的客户提供更动态的用户体验。
为什么 LLM 需要使用工具?
LLM 的一个常见挑战是其训练数据缺乏时效性和特异性——答案可能过时,并且鉴于其知识库的巨大多样性,它们容易产生幻觉。工具是允许 LLM 在受控的上下文中回答问题的一种绝佳方法,该上下文可以利用你现有的知识库和内部 API——与其尝试通过提示工程将 LLM 引导至你想要的答案,不如允许它动态调用工具来获取信息、解析并提供给客户。
为 LLM 提供工具访问权限可以使它们能够根据来自搜索引擎、API 或你自己的数据库的上下文来回答问题。与直接回答不同,拥有工具访问权限的 LLM 可以执行中间步骤来收集相关信息。工具也可以组合使用。例如,可以使语言模型使用搜索工具查找定量信息,并使用计算器执行计算。
Notebook 各部分
- 设置: 导入包并连接到 Pinecone 向量数据库。
- LLM Agent: 构建一个利用 ReAct 框架的修改版本进行思维链推理的 Agent。
- 带历史记录的 LLM Agent: 为 LLM 提供访问对话中先前步骤的能力。
- 知识库: 创建一个“你应该知道的事情”播客剧集的知识库,可通过工具访问。
- 带工具的 LLM Agent: 扩展 Agent 以访问多个工具,并测试它是否使用它们来回答问题。
%load_ext autoreload
%autoreload 2
autoreload 扩展已加载。要重新加载它,请使用:
%reload_ext autoreload
设置
导入库并设置与 Pinecone 向量数据库的连接。
你可以将 Pinecone 替换为任何其他向量存储或数据库——Langchain 原生支持一系列选择,而其他连接器则需要你自己开发。
!pip install openai
!pip install pinecone-client
!pip install pandas
!pip install typing
!pip install tqdm
!pip install langchain
!pip install wget
import datetime
import json
import openai
import os
import pandas as pd
import pinecone
import re
from tqdm.auto import tqdm
from typing import List, Union
import zipfile
# Langchain 导入
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
from langchain.prompts import BaseChatPromptTemplate, ChatPromptTemplate
from langchain import SerpAPIWrapper, LLMChain
from langchain.schema import AgentAction, AgentFinish, HumanMessage, SystemMessage
# LLM 包装器
from langchain.chat_models import ChatOpenAI
from langchain import OpenAI
# 对话内存
from langchain.memory import ConversationBufferWindowMemory
# 嵌入和向量存储
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
# 向量存储索引
index_name = 'podcasts'
要获取连接 Pinecone 的 API 密钥,你可以设置一个免费账户,并将其存储在下面的 api_key
变量中,或存储在你的环境变量 PINECONE_API_KEY
下。
api_key = os.getenv("PINECONE_API_KEY") or "PINECONE_API_KEY"
# 在 Pinecone 控制台中查找 API 密钥旁边的环境
env = os.getenv("PINECONE_ENVIRONMENT") or "PINECONE_ENVIRONMENT"
pinecone.init(api_key=api_key, environment=env)
pinecone.whoami()
pinecone.list_indexes()
['podcasts']
如果你想清除索引,或者索引尚不存在,请运行此代码块
# 检查具有相同名称的索引是否已存在 - 如果存在,则删除它
if index_name in pinecone.list_indexes():
pinecone.delete_index(index_name)
# 创建新索引
pinecone.create_index(name=index_name, dimension=1536)
index = pinecone.Index(index_name=index_name)
# 确认我们的索引已创建
pinecone.list_indexes()
LLM Agent
Langchain 中的LLM Agent 有许多可配置的组件,这些组件在 Langchain 文档中有详细介绍。
我们将使用一些核心概念来创建一个能够以我们想要的方式进行对话、可以使用工具来回答问题,并使用适当的语言模型来驱动对话的 Agent。
- Prompt Template: 用于控制 LLM 行为以及它如何接受输入和产生输出的输入模板——这是驱动你应用程序的大脑(文档)。
- Output Parser: 一种解析提示输出的方法。如果 LLM 使用特定的标头生成输出,你可以启用复杂的交互,其中变量由 LLM 在其响应中生成并传递到链的下一步(文档)。
- LLM Chain: Chain 将提示模板与将执行它的 LLM 结合起来——在这种情况下,我们将使用
gpt-3.5-turbo
,但此框架可以与 OpenAI 的 completions 模型或其他 LLM 完全一起使用(文档)。 - Tool: LLM 可以用来检索信息或执行命令的外部服务,以防用户需要(文档)。
- Agent: 将所有这些结合在一起的粘合剂,Agent 可以调用多个 LLM Chain,每个 Chain 都有自己的工具。Agent 可以通过你自己的逻辑进行扩展,以允许重试、错误处理以及你选择添加可靠性的任何其他方法(文档)。
注意: 在使用此 cookbook 的 Search 工具之前,你需要先在 https://serpapi.com/ 上注册并生成 API 密钥。一旦你有了它,请将其存储在名为 SERPAPI_API_KEY
的环境变量中。
# 初始化一个搜索工具——请注意,你需要按照上面的说明将 SERPAPI_API_KEY 设置为环境变量
search = SerpAPIWrapper()
# 定义一个工具列表
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
)
]
# 使用工具、用户输入和用于模型记录其工作过程的便笺本来设置提示
template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s
Question: {input}
{agent_scratchpad}"""
# 设置一个提示模板
class CustomPromptTemplate(BaseChatPromptTemplate):
# 要使用的模板
template: str
# 可用的工具列表
tools: List[Tool]
def format_messages(self, **kwargs) -> str:
# 获取中间步骤(AgentAction、Observation 元组)
# 以特定方式格式化它们
intermediate_steps = kwargs.pop("intermediate_steps")
thoughts = ""
for action, observation in intermediate_steps:
thoughts += action.log
thoughts += f"\nObservation: {observation}\nThought: "
# 将 agent_scratchpad 变量设置为该值
kwargs["agent_scratchpad"] = thoughts
# 从提供的工具列表中创建 tools 变量
kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools])
# 为提供的工具创建工具名称列表
kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
formatted = self.template.format(**kwargs)
return [HumanMessage(content=formatted)]
prompt = CustomPromptTemplate(
template=template,
tools=tools,
# 此处省略了 `agent_scratchpad`、`tools` 和 `tool_names` 变量,因为它们是动态生成的
# 此处包含了 `intermediate_steps` 变量,因为它是必需的
input_variables=["input", "intermediate_steps"]
)
class CustomOutputParser(AgentOutputParser):
def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
# 检查 Agent 是否应该结束
if "Final Answer:" in llm_output:
return AgentFinish(
# return_values 通常总是一个包含单个 `output` 键的字典
# 目前不建议尝试其他任何操作 :)
return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
log=llm_output,
)
# 解析出 action 和 action input
regex = r"Action: (.*?)[\n]*Action Input:[\s]*(.*)"
match = re.search(regex, llm_output, re.DOTALL)
# 如果无法解析输出,则会引发错误
# 你可以在此处添加自己的逻辑来以不同的方式处理错误,例如传递给人类、给出固定响应
if not match:
raise ValueError(f"Could not parse LLM output: `{llm_output}`")
action = match.group(1).strip()
action_input = match.group(2)
# 返回 action 和 action input
return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output)
output_parser = CustomOutputParser()
# 初始化我们的 LLM——默认是 'gpt-3.5-turbo'
llm = ChatOpenAI(temperature=0)
# 由 LLM 和提示组成的 LLM Chain
llm_chain = LLMChain(llm=llm, prompt=prompt)
# 使用工具、LLM Chain 和 output_parser 来创建一个 Agent
tool_names = [tool.name for tool in tools]
agent = LLMSingleActionAgent(
llm_chain=llm_chain,
output_parser=output_parser,
# 我们使用“Observation”作为停止序列,因此它将在收到工具输出时停止
# 如果你更改了提示模板,也需要相应地调整此设置
stop=["\nObservation:"],
allowed_tools=tool_names
)
# 初始化将响应我们查询的 Agent
# 设置 verbose=True 以共享 LLM 经历的 CoT 推理过程
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
agent_executor.run("How many people live in canada as of 2023?")
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: Hmm, I be not sure of the answer to that one. Let me think.
Action: Search
Action Input: "Canada population 2023" [0m
Observation: [36;1m [1;3m39,566,248 [0m [32;1m [1;3mAhoy, that be a lot of people! But I need to make sure this be true.
Action: Search
Action Input: "Canada population 2023 official source" [0m
Observation: [36;1m [1;3mThe current population of Canada is 38,664,637 as of Wednesday, April 19, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data. Canada population is equivalent to 0.48% of the total world population. [0m [32;1m [1;3mArrr, that be the official number! I be confident in me answer now.
Final Answer: The population of Canada as of 2023 is 38,664,637. Arg! [0m
[1m> Finished chain. [0m
'The population of Canada as of 2023 is 38,664,637. Arg!'
agent_executor.run("How many in 2022?")
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: Hmm, I'm not sure what this question is asking about. I better use the search tool.
Action: Search
Action Input: "2022 events" [0m
Observation: [36;1m [1;3m8. Humanitarian Crises Deepen · 7. Latin America Moves Left. · 6. Iranians Protest. · 5. COVID Eases. · 4. Inflation Returns. · 3. Climate Change ... [0m [32;1m [1;3mAhoy, it looks like this be a question about what be happenin' in 2022. Let me search again.
Action: Search
Action Input: "2022 calendar" [0m
Observation: [36;1m [1;3mUnited States 2022 – Calendar with American holidays. Yearly calendar showing months for the year 2022. Calendars – online and print friendly – for any year ... [0m [32;1m [1;3mShiver me timbers, it looks like this be a question about the year 2022. Let me search one more time.
Action: Search
Action Input: "What be happenin' in 2022?" [0m
Observation: [36;1m [1;3m8. Humanitarian Crises Deepen · 7. Latin America Moves Left. · 6. Iranians Protest. · 5. COVID Eases. · 4. Inflation Returns. · 3. Climate Change ... [0m [32;1m [1;3mAvast ye, it looks like the same results be comin' up. I reckon there be no clear answer to this question.
Final Answer: Arg, I be sorry matey, but I can't give ye a clear answer to that question. [0m
[1m> Finished chain. [0m
"Arg, I be sorry matey, but I can't give ye a clear answer to that question."
LLM Agent with History
将 LLM Agent 扩展为能够保留内存并将其作为上下文在对话中继续使用。
我们在此示例中使用简单的 ConversationBufferWindowMemory
,它保留最近两次对话的滚动窗口。LangChain 还有其他内存选项,具有不同的权衡,适用于不同的用例。
# 设置一个可以内插历史记录的提示模板
template_with_history = """You are SearchGPT, a professional search engine who provides informative answers to users. Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin! Remember to give detailed, informative answers
Previous conversation history:
{history}
New question: {input}
{agent_scratchpad}"""
prompt_with_history = CustomPromptTemplate(
template=template_with_history,
tools=tools,
# 历史模板包含“history”作为输入变量,因此我们可以将其内插到提示中
input_variables=["input", "intermediate_steps", "history"]
)
llm_chain = LLMChain(llm=llm, prompt=prompt_with_history)
tool_names = [tool.name for tool in tools]
agent = LLMSingleActionAgent(
llm_chain=llm_chain,
output_parser=output_parser,
stop=["\nObservation:"],
allowed_tools=tool_names
)
# 初始化内存,k=2 以保留最后两次对话
# 将内存提供给 Agent
memory = ConversationBufferWindowMemory(k=2)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True, memory=memory)
agent_executor.run("How many people live in canada as of 2023?")
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: I need to find the most recent population data for Canada.
Action: Search
Action Input: "Canada population 2023" [0m
Observation: [36;1m [1;3m39,566,248 [0m [32;1m [1;3mThis data seems reliable, but I should double-check the source.
Action: Search
Action Input: "Source of Canada population 2023" [0m
Observation: [36;1m [1;3mThe current population of Canada is 38,664,637 as of Wednesday, April 19, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data. Canada population is equivalent to 0.48% of the total world population. [0m [32;1m [1;3mI now know the final answer
Final Answer: As of April 19, 2023, the population of Canada is 38,664,637. [0m
[1m> Finished chain. [0m
'As of April 19, 2023, the population of Canada is 38,664,637.'
agent_executor.run("how about in mexico?")
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: I need to search for the current population of Mexico.
Action: Search
Action Input: "current population of Mexico" [0m
Observation: [36;1m [1;3mMexico, officially the United Mexican States, is a country in the southern portion of North America. It is bordered to the north by the United States; to the south and west by the Pacific Ocean; to the southeast by Guatemala, Belize, and the Caribbean Sea; and to the east by the Gulf of Mexico. [0m [32;1m [1;3mThat's not the answer to the question, I need to refine my search.
Action: Search
Action Input: "population of Mexico 2023" [0m
Observation: [36;1m [1;3m132,709,512 [0m [32;1m [1;3mI now know the final answer.
Final Answer: As of 2023, the population of Mexico is 132,709,512. [0m
[1m> Finished chain. [0m
'As of 2023, the population of Mexico is 132,709,512.'
Knowledge base
为 Agent 创建一个自定义向量存储以用作工具来回答问题。我们将结果存储在 Pinecone 中,该数据库受 LangChain 支持(文档、API 参考)。有关开始使用 Pinecone 或其他向量数据库的帮助,我们有一个 cookbook 来帮助你入门。
你可以在 LangChain 文档中查看还有哪些向量存储和数据库可用。
在此示例中,我们将使用“你应该知道的事情”播客的文字记录,该记录由 OSF DOI 10.17605/OSF.IO/VM9NT 提供。
import wget
# 这是包含转录播客的 zip 存档的 URL
# 注意:此数据已拆分为块,并包含来自 OpenAI 的 `text-embedding-3-small` 嵌入模型的嵌入
content_url = 'https://cdn.openai.com/API/examples/data/sysk_podcast_transcripts_embedded.json.zip'
# 下载文件(它大约为 541 MB,因此需要一些时间)
wget.download(content_url)
100% [......................................................................] 571275039 / 571275039
'sysk_podcast_transcripts_embedded.json.zip'
# 加载播客
with zipfile.ZipFile("sysk_podcast_transcripts_embedded.json.zip","r") as zip_ref:
zip_ref.extractall("./data")
f = open('./data/sysk_podcast_transcripts_embedded.json')
processed_podcasts = json.load(f)
# 查看内容
pd.DataFrame(processed_podcasts).head()
id | filename | title | url | text_chunk | embedding | cleaned_id | |
---|---|---|---|---|---|---|---|
0 | sysk_with_transcripts_SYSK Selects How Crime S... | sysk_with_transcripts_SYSK Selects How Crime S... | \n\nSYSK Selects How Crime Scene Cleanup Works | https://chtbl.com/track/5899E/podtrac.com/pts/... | Title: sysk_with_transcripts_SYSK Selects How ... | [0.021279960870742798, -0.005817972123622894, ... | sysk_with_transcripts_SYSK Selects How Crime S... |
1 | sysk_with_transcripts_SYSK Selects How Crime S... | sysk_with_transcripts_SYSK Selects How Crime S... | \n\nSYSK Selects How Crime Scene Cleanup Works | https://chtbl.com/track/5899E/podtrac.com/pts/... | Title: sysk_with_transcripts_SYSK Selects How ... | [0.013859338127076626, 0.00857278611510992, 0.... | sysk_with_transcripts_SYSK Selects How Crime S... |
2 | sysk_with_transcripts_SYSK Selects How Crime S... | sysk_with_transcripts_SYSK Selects How Crime S... | \n\nSYSK Selects How Crime Scene Cleanup Works | https://chtbl.com/track/5899E/podtrac.com/pts/... | Title: sysk_with_transcripts_SYSK Selects How ... | [0.015242221765220165, 0.016030369326472282, 0... | sysk_with_transcripts_SYSK Selects How Crime S... |
3 | sysk_with_transcripts_SYSK Selects How Crime S... | sysk_with_transcripts_SYSK Selects How Crime S... | \n\nSYSK Selects How Crime Scene Cleanup Works | https://chtbl.com/track/5899E/podtrac.com/pts/... | Title: sysk_with_transcripts_SYSK Selects How ... | [0.004371842369437218, -0.003036574460566044, ... | sysk_with_transcripts_SYSK Selects How Crime S... |
4 | sysk_with_transcripts_SYSK Selects How Crime S... | sysk_with_transcripts_SYSK Selects How Crime S... | \n\nSYSK Selects How Crime Scene Cleanup Works | https://chtbl.com/track/5899E/podtrac.com/pts/... | Title: sysk_with_transcripts_SYSK Selects How ... | [0.017309172078967094, 0.015154214575886726, 0... | sysk_with_transcripts_SYSK Selects How Crime S... |
# 将文本嵌入添加到 Pinecone
batch_size = 100 # 我们一次创建和插入多少个嵌入
for i in tqdm(range(0, len(processed_podcasts), batch_size)):
# 查找批次的结束
i_end = min(len(processed_podcasts), i+batch_size)
meta_batch = processed_podcasts[i:i_end]
# 获取 ID
ids_batch = [x['cleaned_id'] for x in meta_batch]
# 获取要编码的文本
texts = [x['text_chunk'] for x in meta_batch]
# 添加嵌入
embeds = [x['embedding'] for x in meta_batch]
# 清理元数据
meta_batch = [{
'filename': x['filename'],
'title': x['title'],
'text_chunk': x['text_chunk'],
'url': x['url']
} for x in meta_batch]
to_upsert = list(zip(ids_batch, embeds, meta_batch))
# 向上插入到 Pinecone
index.upsert(vectors=to_upsert)
# 配置将由我们的检索器使用的嵌入,使其成为 OpenAI Embeddings,与我们嵌入的语料库匹配
embeddings = OpenAIEmbeddings()
# 从现有的 Pinecone 索引加载 docsearch 对象,以便我们可以从中检索
docsearch = Pinecone.from_existing_index(index_name,embeddings,text_key='text_chunk')
retriever = docsearch.as_retriever()
query_docs = retriever.get_relevant_documents("can you live without a bank account")
# 打印出最相关的检索文档的标题和内容
print("\n".join(['Title: ' + x.metadata['title'].strip() + '\n\n' + x.page_content + '\n\n' for x in query_docs]))
Title: sysk: Can You Live Without a Bank Account?
Title: sysk_with_transcripts_Can you live without a bank account.json; And if you had a life, you didn't necessarily rectify your bank checkbook every day. Oh, wait, what is balancing a checkbook mean? Seriously? Yeah. Thank God for my wife. So another reason you might avoid a bank is philosophically. There may be a longstanding distrust of banks in your family that you don't want to put your money in, or you may just want to be like, you know what? I don't want to take part in this modern society. I want to kind of drop out a bit. And a really good first move is to shut your bank account down. That's a big statement. Oh, yeah, it is. But a lot of people that are underbanked and don't have accounts aren't there on purpose. It's not some philosophical statement. A lot of times it's simply because they are poor and they don't have a lot of alternatives. Yeah. And the other thing about not having a bank account, not only do you not have a bank account, you also are, like, basically just avoiding banks altogether. There's plenty of other things that banks offer, like loans and mortgage, lollipops, stuff like that. Yeah. Maybe some free nasty coffee. So when you don't have a banking account, that's like the most basic unit of the banking world. Right. If you don't have that, you obviously aren't going to be exposed to all these other things that can help. Things like build your credit history through like a revolving loan or a mortgage or a car loan or something like that that you can build up your credit for and ultimately save money. So when you don't have a bank account, for whatever reason, you are effectively out of the banking system. The problem is you can live parallel to the banking system outside of it, but it can be really dangerous, especially if you're just dealing with cash, because that cash has to stay somewhere, whether it's on you or in your mattress or in a coffee can in your backyard. You're exposed for having that readily available to anybody who finds it or comes into your house with a gun to get it. Yes.
Title: sysk: Can You Live Without a Bank Account?
Title: sysk_with_transcripts_Can you live without a bank account.json; And it doesn't have to be an everyday thing. You can host when you want. Like, let's say you're taking a week's vacation. Why not host your home? Because that money could go toward paying for your current vacation or towards your retirement fund or even towards your kids college fund. Yeah. For anything. And listen, if you're worried about your stuff, don't be. Air cover for hosts. Let hosts welcome guests into their home without having to worry. You get $1 million in damage protection anytime you're hosting. Plus pet damage protection and income loss protection, too. And are you ready for this? Air cover for host is completely free every time you host on airbnb. Free with a capital F, with air cover for Host. It makes hosting a no brainer, and the benefits really start adding up. So learn more and host with peace of mind at Airbnb comaircoverforhosts. Capital One offers commercial solutions you can bank on. Now more than ever, your business faces specific challenges and unique opportunities. That's why Capital One offers a comprehensive suite of financial services custom tailored to your short and long term goals, backed by the expertise, strategy and resources of a top ten commercial bank, a dedicated team works with you to support your success and help you achieve your goals. Explore the possibilities at CapitalOne. comCOMMERCIAL all right, so if you live in modern society today, it is pretty tough to get by without a bank. Most cases these days you have well, I don't know about most cases, but in many cases you have automatic deposits of your work checks. Sure. A lot of people pay their bills wirelessly, online, directly from their bank. You might have a student loan, you might have a car loan, you might have your house mortgage, you might pay your credit card bills. All this stuff is running through a bank, most likely. And you would think it's probably impossible to not have a bank account these days. And I would say pretty much all Americans have them. Not true. Well, pretty much all Americans do. Like 93% do. Yeah, but that's not all. No, it's true.
Title: sysk: Can You Live Without a Bank Account?
Title: sysk_with_transcripts_Can you live without a bank account.json; Yeah. 7% of Americans do not have bank accounts. About 9 million people last year in 2015 did not have bank accounts. 9 million people is a lot of people. No, it really is. And apparently that's household sorry, not people. Yeah, right. You're that is a big distinction, too. And the FDIC said, man, that's the lowest since we've been tracking this by far. And someone said, well, how long have you been tracking this? They said, well, the last six years. Really? Yeah, which I'm like. Really? That's when they started tracking it, but apparently so 2009. So if you want another number, the 9 million American households don't have bank accounts at all, then there are 25 million households in addition to that. So that makes almost like 34 million households, which that's a substantial number at this point. Sure. The 25 million are what's called underbanked, meaning they may have a bank account, but they don't use the bank account. Yeah. They don't use it because they are probably afraid of overdraft fees. Or they have maybe a bank account that got grandfathered in so that they don't have to pay minimum amount fees. And who knows? There's all sorts of reasons for people to not use a bank account that they have, but probably cheap among them is overdressed, which you'll talk more about. Yeah. And the majority of these underbank people in the United States are poor, usually. A lot of times they're minorities, a lot of times they're less educated. And these communities, there's a few reasons why they may not want to use a bank one. Maybe they don't trust banks. And if you look in the history of the United States or certainly even we're just talking about the Wells Fargo scandal, when you see stuff like that on the news, it should be upsetting to everyone. But obviously if you're poor and you don't have a lot of money, that may scare you into not wanting to use a bank at all. Right? Yeah.
Title: sysk: Can You Live Without a Bank Account?
Title: sysk_with_transcripts_Can you live without a bank account.json; Maybe at the time, I might be making it up. I seem to remember them saying that, and I was like, I don't want that. Just let the check bounce and I'll take it up with them. Yes. The way it was marketed, though, was like, hey, we value you. We want to make sure that you can pay all your bills. So if something happens and you're overdrafted we'll cover it. We're just going to charge you a fee. And it sounds good, but again, when you go from high to low and all of a sudden your overdraft fees go from one to four or five or however many, that's a huge problem. Well, and the people that are overdrafting and the people that are at least able to afford those fees. Exactly. So it's a disproportionate burden on the poor, which makes it, as a scam, one of the more evil scams around. Yes. It's just wrong, then the idea that if you open an account, you should not opt in for overdraft protection. And it's easy to say when you're talking about checks for, like you're writing a check for a Mountain Dew and some cheetos. Yeah, who cares if you're short for that? You can go without that. But when you're talking about your rent check or like an actual grocery bill or something like that, it sucks that you can't get that stuff. But it's better to have to put a couple of things back than to pay $35 for one $2 item that you went over by, right? Yeah, that's a good point. And this was in my case, too. This is also back in the day when you I mean, a lot of times it was a mystery how much you had in your account. Right. Like, you couldn't just get on your phone before you write the check and be like, oh, well, no, I don't have enough money to cover this. Yeah, because even if you balanced your checkbook, sometimes you forgot to carry the one, it wasn't always 100% accurate.
LLM Agent with Tools
通过创建利用我们 Pinecone 知识库的RetrievalQA Chain 来扩展我们的工具列表。
from langchain.chains import RetrievalQA
retrieval_llm = OpenAI(temperature=0)
podcast_retriever = RetrievalQA.from_chain_type(llm=retrieval_llm, chain_type="stuff", retriever=docsearch.as_retriever())
expanded_tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
),
Tool(
name = 'Knowledge Base',
func=podcast_retriever.run,
description="Useful for general questions about how to do things and for details on interesting topics. Input should be a fully formed question."
)
]
# 使用我们新工具列表重新初始化 Agent
prompt_with_history = CustomPromptTemplate(
template=template_with_history,
tools=expanded_tools,
input_variables=["input", "intermediate_steps", "history"]
)
llm_chain = LLMChain(llm=llm, prompt=prompt_with_history)
multi_tool_names = [tool.name for tool in expanded_tools]
multi_tool_agent = LLMSingleActionAgent(
llm_chain=llm_chain,
output_parser=output_parser,
stop=["\nObservation:"],
allowed_tools=multi_tool_names
)
multi_tool_memory = ConversationBufferWindowMemory(k=2)
multi_tool_executor = AgentExecutor.from_agent_and_tools(agent=multi_tool_agent, tools=expanded_tools, verbose=True, memory=multi_tool_memory)
multi_tool_executor.run("Hi, I'd like to know how you can live without a bank account")
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: This is an interesting question. I'm not sure if I have the answer in my knowledge base, so I might need to search for it.
Action: Search
Action Input: "How to live without a bank account" [0m
Observation: [36;1m [1;3mUnderbanked households have a checking or savings account but also use alternative financial services such as money orders, check cashing, international remittances, payday loans, refund anticipation loans, rent-to-own services, pawnshop loans, or auto title loans, according to the FDIC. [0m [32;1m [1;3mIt seems like there are alternative financial services available for those who don't have a bank account. I should look into this further to provide a more comprehensive answer.
Action: Search
Action Input: "Alternative financial services for those without a bank account" [0m
Observation: [36;1m [1;3mInstead, people who are unbanked use alternative financial services—payday loans, money orders, check cashing services, pawnshop loans, and the like—to meet their banking needs. These financial services fill an important role for unbanked individuals, but they can also cause further financial hardship. [0m [32;1m [1;3mIt's important to note that while there are alternatives to having a bank account, relying solely on these services can lead to financial difficulties. I should provide some information on the potential drawbacks of not having a bank account.
Action: Knowledge Base
Action Input: "What are the drawbacks of not having a bank account?" [0m
Observation: [33;1m [1;3m Not having a bank account can be dangerous, as the cash has to be stored somewhere and can be exposed to anyone who finds it or comes into the house with a gun to get it. Additionally, not having a bank account means not being exposed to other things that can help, such as building credit history through loans or mortgages, which can ultimately save money. Finally, not having a bank account can be a disproportionate burden on the poor, as overdraft fees can be expensive. [0m [32;1m [1;3mIt's important to provide some resources for those who may be interested in learning more about alternative financial services or how to open a bank account.
Action: Knowledge Base
Action Input: "Resources for alternative financial services or opening a bank account" [0m
Observation: [33;1m [1;3m There are a few resources available for alternative financial services or opening a bank account. Prepaid credit cards are becoming more popular and can be found at convenience stores. Capital One offers commercial solutions and a comprehensive suite of financial services tailored to short and long term goals. Airbnb also offers Air Cover for Hosts, which provides $1 million in damage protection, pet damage protection, and income loss protection. [0m [32;1m [1;3mIt's important to note that while prepaid credit cards and alternative financial services can be helpful, they may not offer the same level of protection and benefits as a traditional bank account. It's also important to do research and compare options before making a decision.
Final Answer: While it is possible to live without a bank account by using alternative financial services, it may come with potential drawbacks and limitations. It's important to do research and compare options before making a decision, and there are resources available for those who may be interested in opening a bank account or exploring alternative financial services. [0m
[1m> Finished chain. [0m
"While it is possible to live without a bank account by using alternative financial services, it may come with potential drawbacks and limitations. It's important to do research and compare options before making a decision, and there are resources available for those who may be interested in opening a bank account or exploring alternative financial services."
multi_tool_executor.run('Can you tell me some interesting facts about whether zoos are good or bad for animals')
[1m> Entering new AgentExecutor chain... [0m
[32;1m [1;3mThought: This is a complex topic that requires a balanced perspective
Action: Knowledge Base
Action Input: "What are the arguments for and against zoos?" [0m
Observation: [33;1m [1;3m The arguments for zoos include that they have gotten a lot better in the last 30-40 years, they participate in research and conservation projects, and they can help save species from extinction. The arguments against zoos include that they are still businesses, they can be counterproductive in terms of educating the public, and they can have a negative impact on the life span of animals in captivity. [0m [32;1m [1;3mIt's important to consider both sides of the argument before coming to a conclusion
Action: Search
Action Input: "What are some examples of successful zoo conservation projects?" [0m
Observation: [36;1m [1;3mThere are dedicated species survival programs which have helped species come out from the brink of extinction, good examples of that being the black-footed ferrets, the red wolves, the Przewalski's wild horse, and the California condors. [0m [32;1m [1;3mWhile there are valid arguments on both sides, it seems that zoos can have a positive impact on conservation efforts for endangered species.
Final Answer: Zoos can have both positive and negative effects on animals, but they can play a role in conservation efforts for endangered species. It's important to consider both sides of the argument and do research before forming an opinion. [0m
[1m> Finished chain. [0m
"Zoos can have both positive and negative effects on animals, but they can play a role in conservation efforts for endangered species. It's important to consider both sides of the argument and do research before forming an opinion."
你现在有了一个用于部署带工具的对话 Agent 的模板。如果你想用自定义 Agent 来添加自己的重试行为或处理输入/输出变量,请遵循本文。
期待看到你构建的东西!