メインコンテンツへスキップ

RAGによるGmail取得範囲を広げてみた

    これの続編です。
    前回はとりあえず動くことを確認したので少しだけ汎用性を増しました(Gmail取得範囲を広げました)。

    Gmail × FAISS × Zephyr-7B-Beta(量子化)

    # ✅ 必要ライブラリをインストール(初回のみ)
    !pip install -U transformers accelerate bitsandbytes sentence-transformers faiss-cpu google-api-python-client google-auth google-auth-oauthlib
    
    # ✅ ライブラリ読み込み
    from googleapiclient.discovery import build
    from google.oauth2.credentials import Credentials
    from sentence_transformers import SentenceTransformer
    import faiss
    import numpy as np
    from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
    import torch
    import re
    
    # ✅ アクセストークンを貼る(OAuth Playgroundなどで取得)
    access_token = "ya29.xxxxxxxxxxxxxxxxxxxxxxxxx"  # ← 自分のトークンに差し替えてください
    
    # ✅ Gmail API認証
    creds = Credentials(token=access_token)
    service = build('gmail', 'v1', credentials=creds)
    
    # ✅ Gmailから最新50件のメール取得(件名+本文)
    results = service.users().messages().list(userId='me', maxResults=50).execute()
    messages = results.get('messages', [])
    
    email_texts = []
    for msg in messages:
        message = service.users().messages().get(userId='me', id=msg['id']).execute()
        snippet = message.get('snippet', '')
        headers = message.get("payload", {}).get("headers", [])
        subject = next((h["value"] for h in headers if h["name"] == "Subject"), "")
        combined_text = f"件名: {subject} 本文: {snippet}"
        email_texts.append(combined_text)
    
    print(f"\n✅ 全件取得完了: {len(email_texts)} 件")
    for i, text in enumerate(email_texts[:5]):
        print(f"{i+1}: {text[:80]}...")
    
    # ✅ 本文クリーン関数(文末「。」 or 空白でカット)
    def clean_text(text, max_chars=800):
        text = re.sub(r"&", "&", text)
        text = re.sub(r"http\S+", "", text)
        text = re.sub(r"※.*?クリック.*?。?", "", text)
        text = re.sub(r"[\n\r]", " ", text).strip()
        if len(text) <= max_chars:
            return text
        end = text.rfind("。", 0, max_chars)
        if end != -1:
            return text[:end + 1]
        space = text.rfind(" ", 0, max_chars)
        return text[:space] + "…" if space != -1 else text[:max_chars] + "…"
    
    # ✅ 意味ベクトルモデル(E5)
    embedder = SentenceTransformer("intfloat/e5-base-v2")
    corpus = [f"passage: {text}" for text in email_texts]
    email_embeddings = embedder.encode(corpus, normalize_embeddings=True)
    
    # ✅ FAISSインデックス構築
    index = faiss.IndexFlatIP(email_embeddings.shape[1])
    index.add(np.array(email_embeddings))
    
    # ✅ 質問(自由に変更OK)
    query = "最近発生した問題について教えてください。"
    query_embedding = embedder.encode([f"query: {query}"], normalize_embeddings=True)
    
    # ✅ 類似メール検索
    D, I = index.search(np.array(query_embedding), k=1)
    retrieved_text = email_texts[I[0][0]]
    short_context = clean_text(retrieved_text)
    
    # ✅ プロンプト作成
    prompt = f"""以下は最近受信したメールの抜粋です。
    
    {short_context}
    
    この内容を参考に、最近の問題について日本語で説明してください。
    """
    
    # ✅ Zephyr用 4bit量子化設定
    bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_use_double_quant=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16
    )
    
    # ✅ モデル読み込み(申請不要・会話特化)
    model_name = "HuggingFaceH4/zephyr-7b-beta"
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        quantization_config=bnb_config,
        device_map="auto"
    )
    
    # ✅ 推論実行
    inputs = tokenizer(prompt.strip(), return_tensors="pt").to("cuda")
    outputs = model.generate(
        **inputs,
        max_new_tokens=300,
        temperature=0.9,
        top_p=0.95,
        do_sample=True,
        repetition_penalty=1.1
    )
    
    # ✅ 結果表示
    print("\n📩 【LLMに渡したメール要約文】\n")
    print(short_context)
    
    print("\n📨 【LLMに渡したプロンプト全文】\n")
    print(prompt.strip())
    
    print("\n💬 【AIの回答】\n")
    print(tokenizer.decode(outputs[0], skip_special_tokens=True))
    

    Google ColabのT4ではVRAM不足になることが多々ある。
    LLMに与えるプロンプトが長くなると(つまりLLMに渡すトークン数が多くなるということで)VRAM不足でクラッシュする。
    文章の短いメールがFAISSで選ばれた場合は上手く動くはず。



    あなたへのおすすめ