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?

【実践的解説】ChainlitとGoogle Gemini APIで作る最新Python AIチャットアプリ

Last updated at Posted at 2025-08-11

はじめに 〜ChainlitとGemini APIの魅力〜

AIチャットボットや対話アプリ開発で今注目されているのが、シンプルなUI開発が可能なChainlitと、Googleが提供する強力な生成AI「Gemini API」の組み合わせです。Gemini APIはAI Studio経由で誰でも簡単にAPIキーを取得でき、Pythonからの利用も公式にサポートされています。本記事ではAI Studio発行のGemini APIキーを活用し、Chainlitで完全動作の対話型AIアプリを実装する方法を13章に分け、解説します。


1. Gemini APIキーの取得と保存方法

Gemini APIをPythonで利用するには、まずGoogle AI Studioにアクセスし、無料プランでAPIキーを発行します。取得したAPIキーは「.env」ファイルなど安全な場所へ必ずコピー・保存してください。これで認証情報の準備は万全です。

# .envファイルの例
GEMINI_API_KEY=ここに取得したAPIキーを貼り付ける

2. 必要なPythonパッケージのインストール

ChainlitとGemini APIを連携するには、公式Pythonクライアントをインストールします。コマンド一発でOKです。

pip install chainlit google-generativeai python-dotenv

環境変数操作も行うため「python-dotenv」も導入します。


3. 「Hello Chainlit × Gemini」—最小構成チャット

まずはGemini APIに簡単な質問を投げてChat UIに返す、極めてシンプルなサンプルです。

import chainlit as cl
from google.generativeai import configure, GenerativeModel
import os
from dotenv import load_dotenv

load_dotenv()
configure(api_key=os.getenv("GEMINI_API_KEY"))
model = GenerativeModel("gemini-1.5-flash")

@cl.on_message
async def main(message: cl.Message):
    response = model.generate_content(message.content)
    await cl.Message(content=response.text).send()

4. モデルの指定とバージョン活用

Gemini APIはモデルバージョンを選択できます。アプリの目的に応じて適切なモデル名(例:「gemini-1.5-flash」「gemini-2.5-flash」)をコードで指定しましょう。

model = GenerativeModel("gemini-2.5-flash")

5. プロンプトの工夫と日本語対応

Geminiは日本語も高精度で理解します。ユーザー入力や指示文を柔軟に処理できるよう、プロンプト生成部分を工夫します。

user_prompt = f"日本語で丁寧に説明してください:{message.content}"
response = model.generate_content(user_prompt)

6. 画像生成・出力の対応

Gemini APIでは画像入力や画像説明も実装可能です。Chainlitでユーザー画像を受け付け、その内容を要約・質問する例も展開できます。

import base64

@cl.on_message
async def main(message: cl.Message):
    if message.files:
        # 画像ファイルのBase64化
        img = message.files[0].content
        img_b64 = base64.b64encode(img).decode()
        response = model.generate_content({
            "role": "user",
            "parts": [{"inline_data": {"mime_type": "image/png", "data": img_b64}}]
        })
        await cl.Message(content=response.text).send()
    else:
        await cl.Message(content="画像をアップロードしてください。").send()

7. 応答温度・生成設定の使い分け

Geminiは「temperature」等のパラメータで回答傾向を調整できます。設定値の実験も大切です。

response = model.generate_content(
    message.content,
    generation_config={"temperature": 0.8}
)

8. ストリーミング応答のUX最適化

レスポンスが長文の場合、Chainlitの「途中経過表示」でユーザー体験を大きく向上できます。

@cl.on_message
async def main(message: cl.Message):
    msg = cl.Message(content="")
    await msg.send()
    gen = model.generate_content(message.content, stream=True)
    for chunk in gen:
        msg.content += chunk.text
        await msg.update()

9. システムプロンプトで特殊キャラや命令を指定

Geminiでは会話の前提やキャラクター性も明示的に指定可能です。

sys_prompt = "AIアシスタント:丁寧語を使うこと。必要なら挨拶も。"
prompt = f"{sys_prompt}\nユーザー: {message.content}"
response = model.generate_content(prompt)

10. ファイルアップロード・分析への応用

Chainlitではテキストファイルのアップロード受付が容易。Geminiの「長文要約」などに使えます。

@cl.on_message
async def main(message: cl.Message):
    if message.files:
        file_txt = message.files[0].content.decode()
        prompt = f"次のテキストを要約してください:{file_txt}"
        response = model.generate_content(prompt)
        await cl.Message(content=response.text).send()
    else:
        await cl.Message(content="ファイルをアップロードしてください").send()

11. ボタンインターフェースで選択肢型QA

選択肢ボタンをUIに出現させてGeminiへの指示切り替えもできます。

@cl.on_message
async def main(message: cl.Message):
    await cl.Message(
        content="質問ジャンルを選んでください:",
        buttons=[cl.Button(label="天気", value="天気"),
                 cl.Button(label="ニュース", value="ニュース")]
    ).send()

@cl.on_button("天気")
async def on_weather(message: cl.Message):
    response = model.generate_content("今の東京の天気を日本語で解説")
    await cl.Message(content=response.text).send()

12. チャットの履歴や文脈・記憶活用

ユーザーの過去発言を踏まえてやりとりする「文脈保持」も可能。アプリで簡単な履歴変数を扱います。

user_history = {}

@cl.on_message
async def main(message: cl.Message):
    uid = message.author
    user_history.setdefault(uid, []).append(message.content)
    # 直近2つの発言を文脈として付けて質問
    prompt = "ユーザー履歴: " + "".join(user_history[uid][-2:])
    response = model.generate_content(f"{prompt}\n次の質問に答えて:{message.content}")
    await cl.Message(content=response.text).send()

13. Gemini×Chainlitで高度なAIチャットボット構築

最後はすべてを統合し、個別ユーザーごとに状態管理・役割設定・リアルタイム応答などを総動員した本格AIチャットサービスを目指します。

# include all previous features: .env, model config, history, streaming, etc.

import chainlit as cl
from google.generativeai import configure, GenerativeModel
import os
from dotenv import load_dotenv

load_dotenv()
configure(api_key=os.getenv("GEMINI_API_KEY"))
model = GenerativeModel("gemini-2.5-flash")
history = {}

@cl.on_message
async def main(message: cl.Message):
    uid = message.author
    history.setdefault(uid, []).append(message.content)
    sysmsg = "あなたは親切な日本語AIです。"
    conv = "\n".join(history[uid][-5:])
    full_msg = f"{sysmsg}\n直近の会話:{conv}\nユーザー: {message.content}"
    msg = cl.Message(content="")
    await msg.send()
    gen = model.generate_content(full_msg, stream=True)
    for chunk in gen:
        msg.content += chunk.text
        await msg.update()

まとめ 〜AIチャットアプリの未来と展望〜

ChainlitとGoogle AI StudioのGemini APIで構築するAIチャットは、極めて手軽で柔軟な開発が可能です。本記事で紹介した13の実践例を基に、日本語にも完全対応した高度なAIサービスを実現しましょう。Gemini APIキー発行から本格アプリ開発まで、一歩ずつ進めれば誰でもプロ品質のチャットボットを生み出せます。ぜひ自身のアイデアで拡張してください。

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?