見出し画像

Gemini APIとLINE Bot APIを組み合わせたチャットボット(GeminOwl)の構築

はじめに

Gemini APIとLINE Bot APIを組み合わせて、ユーザーと対話するLINE Botを作成していきます。


こちらの記事もおすすめ


環境変数の設定

最初のステップは、Gemini APIキー、LINEのアクセストークン、LINEチャンネルシークレット、NgrokのAuthtokenを`.env`ファイルに設定することです。これにより、機密情報の安全な管理が可能になります。


GEMINI_API_KEY=あなたのGeminiAPIキー
LINE_ACCESS_TOKEN=あなたのLineアクセストークン
LINE_CHANNEL_SECRET=あなたのLineチャンネルシークレット
NGROK_AUTHTOKEN=""

Docker環境の構築

次に、`docker-compose.yml`ファイルを作成して、サービスの設定を行います。ここでは、ビルド設定、環境変数、ボリュームマウント、ポート設定、実行コマンドを定義します。


version: '3.8'
services:
  geminowl:
    build: .
    environment:
      - GEMINI_API_KEY=${GEMINI_API_KEY}
      - LINE_ACCESS_TOKEN=${LINE_ACCESS_TOKEN}
      - LINE_CHANNEL_SECRET=${LINE_CHANNEL_SECRET}
      - NGROK_AUTHTOKEN=${NGROK_AUTHTOKEN}
    volumes:
      - .:/app
    ports:
      - "5000:5000"
    command: python gemini_line_bot.py

Dockerfileの作成

`Dockerfile`では、Pythonの公式イメージをベースにして、必要なライブラリをインストールします。


# 基本イメージとしてPythonの公式イメージを使用
FROM python:3.11

# 作業ディレクトリを設定
WORKDIR /app

# 必要なPythonライブラリをインストール
COPY requirements.txt ./
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt
RUN pip install -q -U google-generativeai

LINE Botの実装

`line_bot_base.py`ファイルでは、LINE Botの基本的な機能を実装します。このクラスは、サブクラスによる拡張を想定しています。


# line_bot_base.py
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage

class LineBot:
    def __init__(self, access_token, channel_secret):
        self.line_bot_api = LineBotApi(access_token)
        self.handler = WebhookHandler(channel_secret)

    def create_app(self):
        app = Flask(__name__)

        @app.route("/", methods=['POST'])
        def callback():
            signature = request.headers['X-Line-Signature']
            body = request.get_data(as_text=True)
            app.logger.info("Request body: " + body)

            try:
                self.handler.handle(body, signature)
            except InvalidSignatureError:
                print("Invalid signature.")
                abort(400)

            return 'OK'

        @self.handler.add(MessageEvent, message=TextMessage)
        def handle_message(event):
            self.handle_text_message(event)

        return app

    def handle_text_message(self, event):
        pass  # このメソッドはサブクラスでオーバーライドされることを想定しています

Gemini APIの統合

`gemini_line_bot.py`では、LINE BotにGemini APIを統合し、ユーザーからのメッセージに対して応答を生成します。


# gemini_line_bot.py
from line_bot_base import LineBot
from linebot.models import TextSendMessage
import google.generativeai as genai
import os
from pyngrok import ngrok, conf

# 環境変数から設定を読み込み
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
CHANNEL_SECRET = os.getenv("LINE_CHANNEL_SECRET")
NGROK_AUTHTOKEN = os.getenv("NGROK_AUTHTOKEN")

# Ngrok設定
conf.get_default().auth_token = NGROK_AUTHTOKEN
ngrok_tunnel = ngrok.connect(5000)
print("Ngrok Tunnel URL:", ngrok_tunnel.public_url)

# Gemini APIの設定
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel('gemini-pro')

class GeminiLineBot(LineBot):
    def handle_text_message(self, event):
        user_message = event.message.text
        response = model.start_chat().send_message(user_message)
        reply_text = response.text

        self.line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=reply_text),
        )

if __name__ == "__main__":
    bot = GeminiLineBot(ACCESS_TOKEN, CHANNEL_SECRET)
    app = bot.create_app()
    app.run(port=5000)

ライブラリの依存関係

最後に、`requirements.txt`ファイルに必要なライブラリを記述します。


flask
line-bot-sdk
google-generativeai
pyngrok

Botの起動


docker-compose up --build


おわりに

これらの手順に従うことで、Gemini APIを利用した対話型LINE Botを効率的に構築できます。DockerとNgrokの利用は開発プロセスを容易にし、`.env`ファイルによる機密情報の安全な管理を実現します。

リポジトリ


参考URL

https://developers.line.biz/ja/docs/messaging-api/overview/

https://blog.google/technology/ai/gemini-api-developers-cloud/

https://ai.google.dev/tutorials/python_quickstart

この記事が気に入ったらサポートをしてみませんか?