0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Colabから無料で使えるGeminiでチャットする

Posted at

概要

すべてのColabユーザーが、ColabのPythonライブラリを通じてGeminiモデルに無料でアクセスできるようになったが、List形式で会話履歴を入れて生成させる方法は提供されていなかった。

この記事では、上記ライブラリと同じアクセス方法でGeminiモデルにアクセスしてチャットするシステムを構築する。

ColabのPythonライブラリでのGeminiモデルアクセスについて

この手のサービスはURLとAPIKeyが正しければ動作する。
ColabのPythonライブラリであるgoogle.colab.aiでもURLとAPIKeyを設定している部分が存在するので利用する。

アクセス可能なモデルについて

ユーザのプランによって使用可能なモデルが違うらしい。
今回のコードを使用する場合は、以下のようにモデル一覧で確認してから
image.png

ソースコードの以下の部分を変更して使ってほしい。

model='google/gemini-3-pro-preview',

今回のコードでできること

Colab上実行することで
image.png

Geminiモデルとチャットできる
image.png

動機

  • Colab上で利用できるGeminiを使い倒したい

ソースコード(Pythonファイル)

import gradio as gr
from openai import OpenAI
from google.colab import ai

# --- Colab で Gemini API にアクセスするクライアント ---
client = OpenAI(
    base_url=f'{ai._get_model_proxy_host()}/models/openapi',
    api_key=ai._get_model_proxy_token(),
)

# --- Gradio チャット関数 ---
def chatgpt_chat(message, history, system_prompt):
    chat_history = []

    # システムプロンプトを履歴に追加
    if system_prompt and system_prompt.strip():
        chat_history.append({"role": "system", "content": system_prompt})

    # 過去の会話履歴を追加
    for row in history:
        chat_history.append({"role": row["role"], "content": row["content"]})

    # 今回のユーザー入力を追加
    chat_history.append({"role": "user", "content": message})

    try:
        # Gemini API に直接送信
        response = client.chat.completions.create(
            model='google/gemini-3-pro-preview',
            messages=chat_history,
            stream=False
        )
        # レスポンスのテキストを取得
        answer = response.choices[0].message.content
    except Exception as e:
        print(f"Exception: {e}")
        return "エラーが発生しました。"

    return answer

# --- Gradio UI ---
additional_inputs = [
    gr.Textbox(label="System Prompt", value="あなたは親切なAIです。", interactive=True),
]

app = gr.ChatInterface(
    fn=chatgpt_chat,
    additional_inputs=additional_inputs,
    type="messages"
)

app.launch(debug=True, share=False, inbrowser=False)
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?