Source code for langchain_community.chat_loaders.gmail
importbase64importrefromtypingimportAny,Iteratorfromlangchain_core._api.deprecationimportdeprecatedfromlangchain_core.chat_loadersimportBaseChatLoaderfromlangchain_core.chat_sessionsimportChatSessionfromlangchain_core.messagesimportHumanMessagedef_extract_email_content(msg:Any)->HumanMessage:from_email=Noneforvaluesinmsg["payload"]["headers"]:name=values["name"]ifname=="From":from_email=values["value"]iffrom_emailisNone:raiseValueErrorforpartinmsg["payload"]["parts"]:ifpart["mimeType"]=="text/plain":data=part["body"]["data"]data=base64.urlsafe_b64decode(data).decode("utf-8")# Regular expression to split the email body at the first# occurrence of a line that starts with "On ... wrote:"pattern=re.compile(r"\r\nOn .+(\r\n)*wrote:\r\n")# Split the email body and extract the first partnewest_response=re.split(pattern,data)[0]message=HumanMessage(content=newest_response,additional_kwargs={"sender":from_email})returnmessageraiseValueErrordef_get_message_data(service:Any,message:Any)->ChatSession:msg=service.users().messages().get(userId="me",id=message["id"]).execute()message_content=_extract_email_content(msg)in_reply_to=Noneemail_data=msg["payload"]["headers"]forvaluesinemail_data:name=values["name"]ifname=="In-Reply-To":in_reply_to=values["value"]ifin_reply_toisNone:raiseValueErrorthread_id=msg["threadId"]thread=service.users().threads().get(userId="me",id=thread_id).execute()messages=thread["messages"]response_email=Noneformessageinmessages:email_data=message["payload"]["headers"]forvaluesinemail_data:ifvalues["name"]=="Message-ID":message_id=values["value"]ifmessage_id==in_reply_to:response_email=messageifresponse_emailisNone:raiseValueErrorstarter_content=_extract_email_content(response_email)returnChatSession(messages=[starter_content,message_content])
[docs]@deprecated(since="0.0.32",removal="1.0",alternative_import="langchain_google_community.GMailLoader",)classGMailLoader(BaseChatLoader):"""Load data from `GMail`. There are many ways you could want to load data from GMail. This loader is currently fairly opinionated in how to do so. The way it does it is it first looks for all messages that you have sent. It then looks for messages where you are responding to a previous email. It then fetches that previous email, and creates a training example of that email, followed by your email. Note that there are clear limitations here. For example, all examples created are only looking at the previous email for context. To use: - Set up a Google Developer Account: Go to the Google Developer Console, create a project, and enable the Gmail API for that project. This will give you a credentials.json file that you'll need later. """