from langchain.agents import Tool from langchain_community.utilities import GoogleSerperAPIWrapper from src.config.env import SERPER_API_KEY from langchain_google_community import GmailToolkit from langchain_google_community.gmail.utils import ( build_resource_service, get_gmail_credentials, ) from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request import os def get_gmail_tool(): creds = Credentials( token=None, refresh_token=os.getenv("GMAIL_REFRESH_TOKEN"), token_uri="https://oauth2.googleapis.com/token", client_id=os.getenv("GMAIL_CLIENT_ID"), client_secret=os.getenv("GMAIL_CLIENT_SECRET"), scopes=["https://mail.google.com/"] ) creds.refresh(Request()) service = build_resource_service(credentials=creds) return GmailToolkit(api_resource=service) def get_tools(rag_chain): tools = [] # === RAG Tool === tools.append( Tool( name="RAG", func=lambda x: rag_chain.invoke({"input": x}), description="Use this for questions about UWF, using the Student Handbook as context." ) ) # === Google Search Tool === search = GoogleSerperAPIWrapper(serper_api_key=SERPER_API_KEY) tools.append( Tool( name="Google Search", func=search.run, description="Fallback when RAG does not contain the information." ) ) # === Gmail Tool via Hugging Face Secrets === try: toolkit = get_gmail_tool() gmail_send_tool = next( (tool for tool in toolkit.get_tools() if tool.__class__.__name__ == "GmailSendMessage"), None ) if gmail_send_tool: # Gmail Send Helper def send_email_function(input_data): if isinstance(input_data, str): input_data = {"message": input_data} input_data.setdefault("to", "default_advisor@gmail.com") input_data.setdefault("subject", "Meeting Request") input_data.setdefault("message", "Dear Advisor, the student would like to book a meeting with you.") return gmail_send_tool(input_data) tools.append( Tool( name="Gmail", func=send_email_function, description="Send email to the advisor if the student requests it." ) ) except Exception as e: print(f"[Warning] Gmail tool could not be initialized: {e}") return tools