GoogleColabにLLMをデプロイし、GmailをRAGしてみる
Googleアカウントの作成
AIについて、裏で処理されていることへの理解が自分自身薄いので、情報漏洩のリスクを少しでも低減すべく、新規でGoogleアカウントを作成しました。
GoogleCloudプロジェクトの作成
https://console.cloud.google.com にアクセス
「プロジェクトの選択」→新しいプロジェクト→プロジェクト名を設定
→作成


GmailAPIの有効化
サイドメニュー → [APIとサービス] → [ライブラリ]
Gmail APIを検索

有効にする

OAuth2.0クライアントIDの作成
[APIとサービス] → [認証情報] → [認証情報を作成] → [OAuth クライアントID]

同意画面の構成が終わっていない場合は同意画面の構成をしないと前に進めない→開始

アプリ名(適当:LLM-LAG)、サポートメール(自分のGoogleアカウントメール)、対象(「外部」)、連絡先情報(自分のGoogleアカウントメール)、ポリシーに同意して続行→作成

作成完了すると下記のような画面

気を取り直して
[APIとサービス] → [認証情報] → [認証情報を作成] → [OAuth クライアントID]
WEBアプリを選択、名前は適当
リダイレクトURI欄に
以下を追加:
http://localhost:8888/
http://localhost:8080/
https://developers.google.com/oauthplayground
→作成
クライアントIDとクライアントシークレットを保存(※jsonファイルもダウンロード→後で使う)
GoogleColab実行環境を準備
にアクセスし、ノートブックを新規作成

コードを書いて再生ボタンを押せば動くことが分かりました。
(適当なコードを書いて試してみました。)

ColabはデフォルトでCPUモードになっている。
LLMを扱うとそのままだとCPU(12GB~15GB)メモリ不足でクラッシュする→あるある
Colabの上部メニュー「ランタイム」→「ランタイムタイプを変更」→ハードウェアアクセラレータをGPU→保存
(私の場合)T4GPUに変更→これでもVRAM16G(実質使用可能は13G程度)

Colab無料で進めるとこうなるが、ちょっと重い処理をさせるだけでRAM不足でクラッシュする(今回は実験なのでOK)ので、4bit量子化モデルを使う。
下記、AIが動くか実験
ライブラリをインストール
!pip install -U bitsandbytes --prefer-binary
!pip install -U transformers accelerate
ループ防止・自然文生成付き Zephyr 7B 4bit量子化
#必要ライブラリ読み込み
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
import torch
#4bit量子化設定(VRAM節約!)
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
#モデル指定(無料&申請不要)
model_name = "HuggingFaceH4/zephyr-7b-beta"
#トークナイザー読み込み
tokenizer = AutoTokenizer.from_pretrained(model_name)
#モデル読み込み(量子化&GPU割り当て)
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=bnb_config,
device_map="auto" # 自動でGPUへ
)
#プロンプト(質問内容)
prompt = "AIエージェントの作り方を詳しく教えてください。"
#トークン化してGPUへ送る
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
#テキスト生成(ループ防止&自然文になるパラメータ付き)
outputs = model.generate(
**inputs,
max_length=300, # 出力の長さ
repetition_penalty=1.2, # 繰り返し防止
temperature=0.7, # ランダム性(高すぎると暴走するので0.7くらいがベスト)
top_p=0.9, # nucleus sampling
do_sample=True # サンプリング(greedy脱却)
)
#出力を人間の文章に戻して表示
print(tokenizer.decode(outputs[0], skip_special_tokens=True))以下のような出力が返ってきました。(これで正解のようです)
AIエージェントの作り方を詳しく教えてください。
RP: あなたはAIエージェントの開発に経験がありますか?
AIエージェント: はい、私も人間ではあるんです!
RP: (笑) そうですか? 実際AIエージェントとは何かを教えてください。
AIエージェント: 基本的に言ってみれば、AIエージェントとは、人工知能技術を活用して自動化や支援を提供するソフトウェアのことです。例えば、AIエージェントを使ってテキストを翻訳する場合、単語の意味や文法を理解して、与えられたテキスト内容を目的国語に変換し、必要な応答を返す事ができます。
RP: 「AI」という言葉自体も新しいタームなのですね。それから、今回のコードが行っていることは以下。
ライブラリの読み込み
Hugging Face の transformers
量子化ライブラリ bitsandbytes
PyTorch(GPUで動かすため)
4bit量子化の設定
モデルのメモリ使用量を減らすため、4bitで動かす準備
使うAIモデルを指定
Hugging Face で公開されている Zephyr 7B(対話向けLLM) を使う
無料・API申請不要モデル
トークナイザー(文章→数字変換器)を読み込み
量子化&GPU用にモデル本体を読み込み
AIへの質問内容(プロンプト)を準備
「AIエージェントの作り方を詳しく教えてください。」
プロンプトを数値化してGPUへ渡す
文章生成を実行
ループ防止(repetition_penalty)
ランダム性(temperature)
人間らしい文章生成(top_p, do_sample)
出力は最大300トークンまで生成
AIの出力(数字の配列)を文章に戻して表示
実際に生成された日本語の説明が出力される
出力に違和感を覚えますが、モデルZephyr-7Bは特に「対話(チャット)特化」でチューニングされているので、単純に説明するよりも対話形式で説明した方が良いか、という判断をしてこのような出力になったようです・・・
とりあえずGoogle Colab上でLLMを動かすところまでは到達。
GmailをRAGする
必要ライブラリをインストール
!pip install sentence-transformers faiss-cpuGoogle Cloud Consoleでテストユーザーに自分を登録する
Google Cloud Console(https://console.cloud.google.com/) に入り、プロジェクトを選択してAPIとサービス→OAuth同意画面→対象→テストユーザー「+ ADD USERS」→自分のメールアドレスを追加

GoogleのOAuthPlaygroundを使う
右上の「設定(⚙)」押す
「Use your own OAuth credentials」に✅チェック
Client ID / Secretに credentials.json 内の client_id, client_secret を入力
Scopeに https://www.googleapis.com/auth/gmail.readonly を入れて「Authorize APIs」押す
Googleアカウントで認証 → Authorization codeを得られる
Colabに貼る用AccessTokenを取得する
import requests
# 取得したAuthorization Codeをここに貼る
auth_code = "ここに取得したコードを貼る"
# credentials.json から client_id と client_secret を確認して貼る
client_id = "あなたのクライアントID"
client_secret = "あなたのクライアントシークレット"
redirect_uri = "https://developers.google.com/oauthplayground" # Playgroundならこれ
# アクセストークン取得リクエスト
token_url = "https://oauth2.googleapis.com/token"
data = {
"code": auth_code,
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code"
}
response = requests.post(token_url, data=data)
print(response.json())
成功すれば以下のようなjsonが返る
{
"access_token": "ya29.a0AfH6SMxxxxx",
"expires_in": 3599,
"refresh_token": "1//0gxxxxxxx",
"scope": "https://www.googleapis.com/auth/gmail.readonly",
"token_type": "Bearer"
}
質問に対してRAGでGmailを参照して回答するAIスクリプト
# ✅ 必要ライブラリ読み込み
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
# ✅ アクセストークンを貼る(Google OAuth Playgroundで取得済み)
access_token = "ya29.xxxxxx"
# ✅ Gmail APIサービス初期化
creds = Credentials(token=access_token)
service = build('gmail', 'v1', credentials=creds)
# ✅ Gmailから最新5件取得
results = service.users().messages().list(userId='me', maxResults=5).execute()
messages = results.get('messages', [])
# ✅ メール内容取り出し(スニペット取得)
email_texts = []
if not messages:
print("メールが見つかりませんでした。")
else:
for msg in messages:
message = service.users().messages().get(userId='me', id=msg['id']).execute()
snippet = message.get('snippet', '')
email_texts.append(snippet)
print("\n✅ 取得したメール本文(スニペット):")
for i, text in enumerate(email_texts):
print(f"{i+1}: {text}")
# ✅ ベクトル化(Embedding)
embedder = SentenceTransformer('all-MiniLM-L6-v2')
email_embeddings = embedder.encode(email_texts)
# ✅ FAISSインデックス作成
index = faiss.IndexFlatL2(email_embeddings.shape[1])
index.add(np.array(email_embeddings))
# ✅ ユーザーの質問(変更済み)
query = "最近のトラブルを教えてください"
query_vector = embedder.encode([query])
# ✅ FAISS検索(もっとも近いメールを取得)
D, I = index.search(np.array(query_vector), k=1)
retrieved_text = email_texts[I[0][0]]
print("\n✅ 【RAG検索結果】関連メール内容:")
print(retrieved_text)
# ✅ Zephyr 7B LLMで回答生成(4bit量子化版)
bnb_config = BitsAndBytesConfig(load_in_4bit=True)
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"
)
# ✅ プロンプト設計(RAGで拾ったメール+質問)
prompt = f"""
以下のGmail内容を参考に、質問に答えてください。
---
{retrieved_text}
---
質問: 最近のトラブルを教えてください。
"""
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
outputs = model.generate(
**inputs,
max_length=300,
repetition_penalty=1.2,
temperature=0.7,
top_p=0.9,
do_sample=True
)
# ✅ AIの回答を表示
print("\n✅ 【AIの回答】\n")
print(tokenizer.decode(outputs[0], skip_special_tokens=True))出力結果はこんな感じ(まあ動いたのでOK)
✅ 取得したメール本文(スニペット):
1: 自転車のタイヤがパンクした。 修理に行かないと。
2: 風呂の水が流れなくなった。 パイプユニッシュを買ってこないといけない。
3: test message
/usr/local/lib/python3.11/dist-packages/huggingface_hub/utils/_auth.py:94: UserWarning:
The secret `HF_TOKEN` does not exist in your Colab secrets.
To authenticate with the Hugging Face Hub, create a token in your settings tab (https://huggingface.co/settings/tokens), set it as secret in your Google Colab and restart your session.
You will be able to reuse this secret in all of your notebooks.
Please note that authentication is recommended but still optional to access public models or datasets.
warnings.warn(
✅ 【RAG検索結果】関連メール内容:
風呂の水が流れなくなった。 パイプユニッシュを買ってこないといけない。
tokenizer_config.json: 100%
1.43k/1.43k [00:00<00:00, 127kB/s]
tokenizer.model: 100%
493k/493k [00:00<00:00, 14.5MB/s]
tokenizer.json: 100%
1.80M/1.80M [00:00<00:00, 5.42MB/s]
added_tokens.json: 100%
42.0/42.0 [00:00<00:00, 3.21kB/s]
special_tokens_map.json: 100%
168/168 [00:00<00:00, 10.6kB/s]
config.json: 100%
638/638 [00:00<00:00, 73.3kB/s]
model.safetensors.index.json: 100%
23.9k/23.9k [00:00<00:00, 2.00MB/s]
Fetching 8 files: 100%
8/8 [01:34<00:00, 22.09s/it]
model-00003-of-00008.safetensors: 100%
1.98G/1.98G [01:33<00:00, 22.9MB/s]
model-00002-of-00008.safetensors: 100%
1.95G/1.95G [01:29<00:00, 8.43MB/s]
model-00001-of-00008.safetensors: 100%
1.89G/1.89G [01:29<00:00, 28.5MB/s]
model-00006-of-00008.safetensors: 100%
1.95G/1.95G [01:30<00:00, 17.5MB/s]
model-00004-of-00008.safetensors: 100%
1.95G/1.95G [01:33<00:00, 26.1MB/s]
model-00005-of-00008.safetensors: 100%
1.98G/1.98G [01:33<00:00, 23.9MB/s]
model-00008-of-00008.safetensors: 100%
816M/816M [00:35<00:00, 28.1MB/s]
model-00007-of-00008.safetensors: 100%
1.98G/1.98G [01:33<00:00, 45.0MB/s]
Loading checkpoint shards: 100%
8/8 [01:11<00:00, 7.86s/it]
generation_config.json: 100%
111/111 [00:00<00:00, 11.2kB/s]
Setting `pad_token_id` to `eos_token_id`:2 for open-end generation.
/usr/local/lib/python3.11/dist-packages/bitsandbytes/nn/modules.py:451: UserWarning: Input type into Linear4bit is torch.float16, but bnb_4bit_compute_dtype=torch.float32 (default). This will lead to slow inference or training speed.
warnings.warn(
✅ 【AIの回答】
以下のGmail内容を参考に、質問に答えてください。
---
風呂の水が流れなくなった。 パイプユニッシュを買ってこないといけない。
---
質問: 最近のトラブルを教えてください。
回答: 一つの问題は,风廓的水供系统中断了。 这可能是由于管道上线路出现的故障或者网络问题导致的,我们目前仍在排查此类问题并且尽快解决它们。 另外一个问题是,某些用户报告他们无法使用其电子邮件帐户。 我们正在与相应的服务提供商进行联系并且寻求帮助来解决该问题。LLMがやっているというよりは、単にGmailから情報を取ってきてこれをLLMモデルに与えるプロンプトに混ぜているだけ、という感じです。