LangChain工具箱Toolkits之使用Gmail工具箱实现邮件查询、邮件发送、邮件删除等操作

Toolkits工具箱

Toolkits概述:

定义: Toolkits是为特定任务设计的工具集合,它们具有方便的加载方法。

目的: 用于执行特定的任务,比如文本分析、图像生成等。

使用: 通过get_tools方法可以获取toolkit中的所有工具列表。

使用Toolkits

# 初始化Toolkit: 通过传递所需的参数来创建toolkit的实例。
toolkit = ExampleToolkit(...)

# 获取工具列表: 使用get_tools方法从toolkit实例中获取工具列表。
tools = toolkit.get_tools()

# 创建Agent: 利用获取的工具列表和其他必要参数(如LLM模型、提示等)来创建一个agent
agent = create_agent_method(llm, tools, prompt)

工具箱列表

以下是一部分常见、更实用的工具箱,每个工具箱中都有一系列工具。更多工具箱参考:官方文档

工具名称中文说明
Amadeus Toolkit将 LangChain 连接到 Amadeus 旅行信息 API
Azure Cognitive Services Toolkit与Azure Cognitive Services API交互,以实现一些多模态功能
CSV Agent用代理与 CSV 互动
Document Comparison使用代理比较文件
GitHub ToolkitGitHub 工具箱包含使LLM 代理与 GitHub 存储库互动的工具,这些工具是 PyGitHub 库的封装
Gmail Toolkit将 LangChain 电子邮件连接到 Gmail API
JiraJira 工具箱
JSON Agent与大型JSON/dict 对象互动的代理
MultiOn Toolkit将 LangChain 连接到你浏览器中的MultiOn 客户端
Office365 Toolkit将 LangChain 连接到 Office365 电子邮件和日历等
Pandas Dataframe Agent与Pandas Dataframe 互动的代理
PlayWright Browser Toolkit通过浏览器导航 Web 并与动态渲染的网站互动
PowerBI Dataset Agent用于与 PowerBI 数据集互动的代理
Python Agent用于编写并执行 Python 代码以回答问题的代理
Spark Dataframe Agent与Spark Dataframe 和 Spark Connect 互动的代理
Spark SQL Agent与Spark SQL 互动的代理
SQL Database Agent与SQL 数据库互动的代理
Vectorstore Agent从一个或多个Vectorstore 检索信息的代理
Xorbits Agent与Xorbits Pandas Dataframe 互动的代理

使用Gmail工具箱

通过Gmail工具箱,可以通过LangChain应用查询邮件、删除垃圾邮件,甚至让它帮你撰写邮件等操作。

Gmail API配置

访问Gmail API的Python快速入门 ,根据文档说明进行相关配置操作。

1.创建项目并基于该项目进行操作
在这里插入图片描述

2.启用Gmail AP
在这里插入图片描述
3.配置 OAuth 权限请求页面
在这里插入图片描述
注意:这里需要添加相关权限,并且这里权限列表有分页,一定要勾选全部授权
在这里插入图片描述

4.为桌面应用授权凭据,注意下载JSON文件,并重命名为credentials.json
在这里插入图片描述

5.安装Python版Google客户端库

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

6.创建一个名为quickstart.py的文件

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]


def main():
  """Shows basic usage of the Gmail API.
  Lists the user's Gmail labels.
  """
  creds = None
  # The file token.json stores the user's access and refresh tokens, and is
  # created automatically when the authorization flow completes for the first
  # time.
  if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
  # If there are no (valid) credentials available, let the user log in.
  if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
      creds.refresh(Request())
    else:
      flow = InstalledAppFlow.from_client_secrets_file(
          "credentials.json", SCOPES
      )
      creds = flow.run_local_server(port=0)
    # Save the credentials for the next run
    with open("token.json", "w") as token:
      token.write(creds.to_json())

  try:
    # Call the Gmail API
    service = build("gmail", "v1", credentials=creds)
    results = service.users().labels().list(userId="me").execute()
    labels = results.get("labels", [])

    if not labels:
      print("No labels found.")
      return
    print("Labels:")
    for label in labels:
      print(label["name"])

  except HttpError as error:
    # TODO(developer) - Handle errors from gmail API.
    print(f"An error occurred: {error}")


if __name__ == "__main__":
  main()

7.将credentials.json文件放到与quickstart.py文件同目录下,执行如下命令,根据密钥生成开发Token,会自动打开浏览器

python3 quickstart.py

8.根据提示授予访问权限,然后最终在quickstart.py文件同目录下生成token.json文件
在这里插入图片描述

开发Gmail App

连接到Gmail API,查询用户的邮件,并通过LangChain的Agent框架智能化地调用API(用语言而不是具体API),与邮件进行互动。

创建工具包​

默认情况下,工具包读取本地 credentials.json 文件。

# 导入与Gmail交互所需的工具包
from langchain_community.agent_toolkits import GmailToolkit

# 初始化Gmail工具包
toolkit = GmailToolkit()

自定义身份验证​

使用以下方法创建 googleapi 资源。可以手动构建 googleapi 资源以进行更多身份验证控制。

# 从gmail工具中导入
from langchain_community.tools.gmail import get_gmail_credentials
from langchain_community.tools.gmail.utils import build_resource_service

# 获取Gmail API的凭证,并指定相关的权限范围
credentials = get_gmail_credentials(
    token_file="token.json",  # Token文件路径
    scopes=["https://mail.google.com/"],  # 具有完全的邮件访问权限
    client_secrets_file="credentials.json",  # 客户端的秘密文件路径
)
# 使用凭证构建API资源服务
api_resource = build_resource_service(credentials=credentials)
toolkit = GmailToolkit(api_resource=api_resource)

# 获取工具
tools = toolkit.get_tools()
print(tools)
[GmailCreateDraft(api_resource=<googleapiclient.discovery.Resource object at 0x000002212A24BBB0>),
GmailSendMessage(api_resource=<googleapiclient.discovery.Resource object at 0x000002212A24BBB0>), 
GmailSearch(api_resource=<googleapiclient.discovery.Resource object at 0x000002212A24BBB0>), 
GmailGetMessage(api_resource=<googleapiclient.discovery.Resource object at 0x000002212A24BBB0>), 
GmailGetThread(api_resource=<googleapiclient.discovery.Resource object at 0x000002212A24BBB0>)]

初始化Agent

# 导入与聊天模型相关的包
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_openai_functions_agent

# 初始化聊天模型
llm = ChatOpenAI(temperature=0, model='gpt-4')

# 获取要使用的提示
instructions = """You are an assistant."""
base_prompt = hub.pull("langchain-ai/openai-functions-template")
prompt = base_prompt.partial(instructions=instructions)

# 初始化agent
agent = create_openai_functions_agent(llm, tools, prompt)

# 通过传入代理和工具创建代理执行程序
agent_executor = AgentExecutor(
    agent=agent, tools=tools, verbose=True, handle_parsing_errors=True
)

运行Agent

查询最新邮件

# 使用agent运行一些查询或指令
result = agent_executor.invoke({"input": "未读邮件有几封?最新的邮件是谁发给我的?"})
# 打印结果
print(result)

查看Gamil邮箱
在这里插入图片描述

执行日志如下:
在这里插入图片描述

发送邮件

# 使用agent运行一些查询或指令
result = agent_executor.invoke({"input": "向邮箱:xxx@qq.com发送邮件。邮件主题:Gmail Agent Test 邮件内容: 进行Gmail Tools Test."})
# 打印结果
print(result)

出现异常:

Exception: An error occurred: <HttpError 403 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">

经过一番折腾,直到查看上面生成Token的quickstart.py文件代码,才发现一个关键点:

# If modifying these scopes, delete the file token.json.
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]

保持怀疑猜测态度,查看添加的权限,发现生成Token时,代码中SCOPES只是配置了readonly
在这里插入图片描述
这里需要发送邮件,因此解决办法如下,添加相应权限

SCOPES = ["https://www.googleapis.com/auth/gmail.readonly","https://www.googleapis.com/auth/gmail.send"]

注意:需要删除token.json,然后重新执行代码生成token.json文件

再次执行,日志如下
在这里插入图片描述
查看收件箱
在这里插入图片描述

注意

TimeoutError

TimeoutError异常日志如下:

TimeoutError: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。

分析:

1.Gmail API调用,需要访问国外服务器,出现此异常正常,但是我这里使用了Proxy,不应该出现才对。

2.对于Python,目前只是能用,谈不上精通,简单查看了源代码,我想修改相应代码配置Proxy可以解决

这里开启了Proxy软件的一个Tun模式解决了该问题

SCOPES权限不足

在执行相关命令时,可能出现权限不足的问题,此时需要查看添加权限信息,并在生成Token的代码文件的中SCOPES添加相应权限,然后删除token.json,然后再次授权生成token.json。具体参考上面发送邮件遇到异常的处理

权限不足异常提示

Exception: An error occurred: <HttpError 403 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">

添加相应权限

# If modifying these scopes, delete the file token.json.
SCOPES = [
# 在该插件运行时查看您的电子邮件
"https://www.googleapis.com/auth/gmail.readonly",
# 代表您发送电子邮件
"https://www.googleapis.com/auth/gmail.send"
]

Token限制

在使用Agent执行指令时,最好添加限制约束,否则将出现Token上限问题。

openai.BadRequestError: Error code: 400 - {'error': {'message': "This model's maximum context length is 8192 tokens. However, your messages resulted in 8486 tokens (7985 in the messages, 501 in the functions). Please reduce the length of the messages or functions. (request id: 20240412160742577297722dQQe4WVJ)", 'type': 'invalid_request_error', 'param': 'messages', 'code': 'context_length_exceeded'}}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CodeDevMaster

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

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

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

打赏作者

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

抵扣说明:

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

余额充值