GMail
此載入器說明如何從 GMail 載入資料。您可能有很多種想要從 GMail 載入資料的方式。此載入器目前對於如何執行此操作相當有主見。它的運作方式是首先尋找您已發送的所有訊息。然後尋找您回覆先前電子郵件的訊息。然後提取先前的電子郵件,並建立該電子郵件的訓練範例,然後是您的電子郵件。
請注意,這裡有明顯的限制。例如,建立的所有範例僅查看先前的電子郵件以獲取上下文。
使用方法
-
設定 Google 開發人員帳戶:前往 Google 開發人員控制台,建立專案,並為該專案啟用 Gmail API。這將為您提供稍後需要的 credentials.json 檔案。
-
安裝 Google Client Library:執行以下命令以安裝 Google Client Library
%pip install --upgrade --quiet google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
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("email_token.json"):
creds = Credentials.from_authorized_user_file("email_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(
# your creds file here. Please create json file as here https://cloud.google.com/docs/authentication/getting-started
"creds.json",
SCOPES,
)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open("email_token.json", "w") as token:
token.write(creds.to_json())
from langchain_community.chat_loaders.gmail import GMailLoader
API 參考:GMailLoader
loader = GMailLoader(creds=creds, n=3)
data = loader.load()
# Sometimes there can be errors which we silently ignore
len(data)
2
from langchain_community.chat_loaders.utils import (
map_ai_messages,
)
API 參考:map_ai_messages
# This makes messages sent by hchase@langchain.com the AI Messages
# This means you will train an LLM to predict as if it's responding as hchase
training_data = list(
map_ai_messages(data, sender="Harrison Chase <hchase@langchain.com>")
)