0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Claude と Google Colabの連携

Posted at

大規模言語モデル講座 基礎編 2025 Autumn 敗因を勝因に
https://qiita.com/kaizen_nagoya/items/34ffd2b0c47a5f3665d9

Claude と Google Colabの連携して使ったことがない。

ChatGPT

Claude と Google Colabの連携方法を教えてください。
ChatGPT:
なるほど、Claude(AnthropicのAI)とGoogle Colabを連携させたいということですね。以下に整理して手順と方法を示します。

  1. 前提条件
    Claudeを利用できるアカウント(AnthropicのAPIアクセス)
    Google Colabアカウント
    Pythonの基本操作が可能
  2. APIキーの取得
    Claudeは通常 Anthropic API を通して利用できます。
    Anthropicの公式サイトでアカウント作成
    ダッシュボードで APIキー を取得
    例: sk-xxxxxx
  3. Python環境での設定(Colab)
    Google Colab上でClaude APIを呼び出す場合、PythonでHTTPリクエストを送るか、専用のSDKを使います。
    (A) HTTPリクエストを使う方法
    import requests

API_KEY = "sk-xxxxxx"
API_URL = "https://api.anthropic.com/v1/complete"

headers = {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}

data = {
"model": "claude-v1",
"prompt": "日本語で自己紹介してください。",
"max_tokens_to_sample": 200
}

response = requests.post(API_URL, headers=headers, json=data)
result = response.json()
print(result["completion"])
ポイント:
model は使用するClaudeのバージョンに応じて変更可能
prompt に入力したテキストがAIへの指示になります
(B) Anthropic公式Pythonライブラリを使う方法
Colabでインストール
!pip install anthropic
コード例
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT

client = Anthropic(api_key="sk-xxxxxx")

response = client.completions.create(
model="claude-v1",
prompt=f"{HUMAN_PROMPT} 日本語で自己紹介してください。{AI_PROMPT}",
max_tokens_to_sample=200
)

print(response.completion)
ポイント:
HUMAN_PROMPT と AI_PROMPT を使うことで対話形式に自然に組み込めます
max_tokens_to_sample は出力長の調整
4. Colabとの便利な連携ポイント
Notebook上で直接Claudeを呼び出せる
データ分析や文章生成、レポート作成と連携可能
pandas や numpy と組み合わせてデータ解析 → AIに文章化も可能
Google Driveと連携すれば生成内容の保存も簡単
5. 注意点
Claude APIには利用制限・料金がある
APIキーは絶対に公開しない
大量リクエストや長文生成には max_tokens の調整が必要
💡 補足
Google ColabはPython環境なので、Claude APIとの接続はほぼPythonで完結します。対話形式のノートブックを作ると、AIをデータ処理・文章生成・翻訳などにシームレスに活用できます。
もし希望なら、Google Colab上でClaudeを簡単に試せる最小構成サンプルノートブック を作って示すこともできます。
作りますか?

あなた:
はい。
ChatGPT:
了解です。では、Claude APIをGoogle Colabで簡単に試せる最小構成のサンプルノートブック例を示します。
🔹 Colabサンプルノートブック(Claude連携)

1. ライブラリインストール

!pip install anthropic

2. 必要ライブラリ読み込み

from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT

3. APIキー設定(ご自身のClaude APIキーに置き換えてください)

API_KEY = "sk-xxxxxxxxxxxx"

client = Anthropic(api_key=API_KEY)

4. 入力プロンプト設定

user_input = "今日の天気について日本語で短く教えてください。"

prompt = f"{HUMAN_PROMPT} {user_input} {AI_PROMPT}"

5. Claudeに問い合わせ

response = client.completions.create(
model="claude-v1",
prompt=prompt,
max_tokens_to_sample=200
)

6. 結果表示

print(response.completion)
🔹 使い方
上記コードをColabにコピー
API_KEY を自身のClaude APIキーに置き換え
user_input に質問や指示を入力
実行するとClaudeが回答を返す
🔹 拡張ポイント
Google Drive連携して、生成したテキストを自動保存
pandas や numpy と組み合わせてデータ解析 → 自動レポート生成
Chat形式のUIを作って複数回のやり取りも可能
希望であれば、Colab上で簡易チャット形式でClaudeと会話できるノートブックのサンプルも作れます。作りますか?
あなた:
はい。
ChatGPT:
了解です。それでは、Google Colab上で 簡易チャット形式でClaudeと会話できるノートブック のサンプルを示します。これを使えば、複数回のやり取りを対話形式で行えます。
🔹 ColabでClaudeチャットサンプル

1. ライブラリインストール

!pip install anthropic

2. 必要ライブラリ読み込み

from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT

3. APIキー設定(自身のClaude APIキーに置き換えてください)

API_KEY = "sk-xxxxxxxxxxxx"
client = Anthropic(api_key=API_KEY)

4. チャット履歴管理用リスト

chat_history = []

5. チャット関数

def chat_with_claude(user_input):
# 履歴を組み込んだプロンプト作成
history_text = ""
for h in chat_history:
history_text += f"{HUMAN_PROMPT} {h['user']} {AI_PROMPT} {h['ai']}"

prompt = f"{history_text}{HUMAN_PROMPT} {user_input} {AI_PROMPT}"

response = client.completions.create(
    model="claude-v1",
    prompt=prompt,
    max_tokens_to_sample=200
)

ai_reply = response.completion.strip()

# 履歴に保存
chat_history.append({"user": user_input, "ai": ai_reply})

return ai_reply

6. 実際の会話例

user_input = "こんにちは、今日の天気はどうですか?"
reply = chat_with_claude(user_input)
print("Claude:", reply)

7. さらに質問して続けられます

user_input2 = "明日の天気も教えてください。"
reply2 = chat_with_claude(user_input2)
print("Claude:", reply2)
🔹 使い方
Colabにコードをコピー
API_KEY を自分のClaude APIキーに変更
user_input に質問や指示を入力して実行
chat_history に過去の会話が自動で蓄積されるので、連続した会話が可能
新しい質問を追加して chat_with_claude("質問") を呼び出すだけで対話継続
💡 拡張例
StreamlitやGradioを使って簡易UI化してボタンや入力欄からやり取り
Google Driveに履歴を保存して後で分析
複数人でのチャット履歴管理も可能
必要であれば、このコードを Gradio UI付きでリアルタイム対話できるColab版 に変換するサンプルも作れます。作りますか?
あなた:
はい。
ChatGPT:
了解です!では、Google Colab上で Gradio UI付きでリアルタイムにClaudeと対話できるサンプル を作成します。これを使うと、ブラウザ上でチャットアプリのように入力・出力ができます。
🔹 Colab + GradioでClaudeチャット

1. ライブラリインストール

!pip install anthropic gradio --quiet

2. 必要ライブラリ読み込み

from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
import gradio as gr

3. APIキー設定(自身のClaude APIキーに置き換えてください)

API_KEY = "sk-xxxxxxxxxxxx"
client = Anthropic(api_key=API_KEY)

4. チャット履歴管理

chat_history = []

5. チャット関数

def chat_with_claude(user_input):
# 履歴を組み込んだプロンプト作成
history_text = ""
for h in chat_history:
history_text += f"{HUMAN_PROMPT} {h['user']} {AI_PROMPT} {h['ai']}"

prompt = f"{history_text}{HUMAN_PROMPT} {user_input} {AI_PROMPT}"

response = client.completions.create(
    model="claude-v1",
    prompt=prompt,
    max_tokens_to_sample=300
)

ai_reply = response.completion.strip()
# 履歴に保存
chat_history.append({"user": user_input, "ai": ai_reply})

return ai_reply

6. Gradio UI作成

with gr.Blocks() as demo:
gr.Markdown("## Claude Chat (Gradio + Colab)")
chatbox = gr.Chatbot()
msg = gr.Textbox(placeholder="質問を入力してください")
clear_btn = gr.Button("クリア")

def respond(user_message, chat_history_ui):
    reply = chat_with_claude(user_message)
    chat_history_ui.append((user_message, reply))
    return chat_history_ui, ""

msg.submit(respond, [msg, chatbox], [chatbox, msg])
clear_btn.click(lambda: [], None, chatbox)

7. UI起動

demo.launch()
🔹 使い方
上記コードをColabにコピー
API_KEY を自身のClaude APIキーに置き換え
実行すると、ブラウザにGradioチャットUIが表示
テキストを入力して送信するとClaudeが応答
「クリア」ボタンでチャット履歴をリセット可能
💡 ポイント
履歴管理により、会話の文脈を維持した対話が可能
max_tokens_to_sample を増やせば長文応答も可能
Colab環境のまま、ブラウザ上でほぼリアルタイム対話ができる
必要なら、さらに Google Drive連携でチャット履歴を自動保存 するバージョンも作れます。作りますか?

はい。

ChatGPT:

Network connection lost. Attempting to reconnect…
了解です!では、先ほどの GradioチャットUI付きClaudeノートブック に、Google Driveへの チャット履歴自動保存機能 を追加するサンプルを示します。これにより、会話内容をあとから振り返ったり分析したりできます。
🔹 Colab + Gradio + Google Driveでチャット履歴保存

# 1. ライブラリインストール
!pip install anthropic gradio --quiet
# 2. Google Driveマウント
from google.colab import drive
drive.mount('/content/drive')
# 3. 必要ライブラリ読み込み
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
import gradio as gr
import json
import os
from datetime import datetime
# 4. APIキー設定(自身のClaude APIキーに置き換えてください)
API_KEY = "sk-xxxxxxxxxxxx"
client = Anthropic(api_key=API_KEY)
# 5. 保存先ディレクトリ設定
save_dir = "/content/drive/MyDrive/ClaudeChatLogs"
os.makedirs(save_dir, exist_ok=True)
# 6. チャット履歴管理
chat_history = []
# 7. チャット関数
def chat_with_claude(user_input):
    # 履歴を組み込んだプロンプト作成
    history_text = ""
    for h in chat_history:
        history_text += f"{HUMAN_PROMPT} {h['user']} {AI_PROMPT} {h['ai']}"

    prompt = f"{history_text}{HUMAN_PROMPT} {user_input} {AI_PROMPT}"

    response = client.completions.create(
        model="claude-v1",
        prompt=prompt,
        max_tokens_to_sample=300
    )

    ai_reply = response.completion.strip()
    
    # 履歴に保存
    chat_history.append({"user": user_input, "ai": ai_reply})
    
    # Google Driveに保存
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    save_path = os.path.join(save_dir, f"chat_{timestamp}.json")
    with open(save_path, "w", encoding="utf-8") as f:
        json.dump(chat_history, f, ensure_ascii=False, indent=2)
    
    return ai_reply

# 8. Gradio UI作成
with gr.Blocks() as demo:
    gr.Markdown("## Claude Chat with Google Drive Logging")
    chatbox = gr.Chatbot()
    msg = gr.Textbox(placeholder="質問を入力してください")
    clear_btn = gr.Button("クリア")

    def respond(user_message, chat_history_ui):
        reply = chat_with_claude(user_message)
        chat_history_ui.append((user_message, reply))
        return chat_history_ui, ""
    
    msg.submit(respond, [msg, chatbox], [chatbox, msg])
    clear_btn.click(lambda: [], None, chatbox)

# 9. UI起動
demo.launch()

🔹 特徴
Gradio UIでリアルタイムチャット
Google Drive連携で会話履歴を自動JSON保存
保存フォルダ: MyDrive/ClaudeChatLogs
ファイル名: chat_YYYYMMDD_HHMMSS.json
チャット履歴を残せるので、あとから分析やログ確認が可能
「クリア」ボタンで画面上の履歴だけリセット(Driveには保存済み)
💡 拡張アイデア
保存形式をCSVにしてExcelやPandasで集計可能
ユーザー名やタグを追加して複数人チャット履歴管理
自動で過去ログを読み込み、会話の文脈を維持する機能
希望なら、CSV形式でまとめて保存&読み込み可能なバージョンも作れます。作りますか?

ChatGPT の回答は必ずしも正しいとは限りません。重要な情報は確認するようにしてください。

ChatGPT の回答は必ずしも正しいとは限りません。重要な情報は確認するようにしてください。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?