LoginSignup
0
0

LINEAPI×CHATGPTAPI×DOCKER×CLOUDRUN×PYTHONで爆速でchatbotを作ってみる

Last updated at Posted at 2023-06-01

完成したラインボット
どんな質問にも答えてくれる「解答キッド」
https://liff.line.me/1645278921-kWRPP32q/?accountId=524aznwp

#リポジトリー
https://github.com/Kobajun0219/Line-bot-chatgpt

#参考にした記事

#ソースコード

Sample.py
from flask import Flask
from flask import request
import os
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import (MessageEvent, TextMessage, TextSendMessage,)

import openai

# generate instance
app = Flask(__name__)

#key
CHANNEL_SECRET = os.environ["CHANNEL_SECRET"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]

# API_KEY
openai.api_key = os.environ["API_KEY"]

line_bot_api = LineBotApi(ACCESS_TOKEN)
handler = WebhookHandler(CHANNEL_SECRET)

# endpoint
@app.route("/")
def test():
    return "<h1>It Works!</h1>"

# endpoint from linebot
@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
		signature = request.headers['X-Line-Signature']

		# get request body as text
		body = request.get_data(as_text=True)
		app.logger.info("Request body: " + body)

		# handle webhook body
		try:
			handler.handle(body, signature)
		except InvalidSignatureError:
			print("Invalid signature. Please check your channel access token/channel secret.")
			abort(400)
		return 'OK'

# handle message from LINE
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
  response_text = generate_response(event.message.text)
  line_bot_api.reply_message(
			event.reply_token,
			TextSendMessage(text=response_text))


# OpenAIのAPIを使ってChat GPTに入力を渡し、応答を取得する
def generate_response(input_text):
    model_engine = "text-davinci-002"
    prompt = f"{input_text.strip()} \nAI:"
    completions = openai.Completion.create(
        engine=model_engine,
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )
    message = completions.choices[0].text.strip()
    return message


if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

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