FastAPI with ChatGPT in Linebot
安裝要求
- FastAPI、Uvicorn
- openai
- linebot
cmd
pip install fastapi uvicorn openai line-bot-sdk
引入套件
引入已安裝的需求套件
py
# main.py
import logging, uvicorn
from fastapi import FastAPI, Request, HTTPException
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import openai, os
密碼區
前提先到 openai、linebot 建立 token (api key)
py
# main.py
openai.api_key = os.getenv("OPENAI_API_KEY")
line_bot_api = LineBotApi(os.getenv("LINE_CHANNEL_ACCESS_TOKEN"))
handler = WebhookHandler(os.getenv("LINE_CHANNEL_SECRET"))
對話空白框
先建立空白對話區塊
py
# main.py
conversation = []
設定ChatGPT回應
py
class ChatGPT:
def __init__(self):
self.messages = conversation
# 指定gpt3.5模組
self.model = os.getenv("OPENAI_MODEL", default = "gpt-3.5-turbo")
# 定義回饋內容
def get_response(self, user_input):
conversation.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(
model=self.model,
messages = self.messages
)
conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']})
print("AI回答內容:")
print(response['choices'][0]['message']['content'].strip())
return response['choices'][0]['message']['content'].strip()
chatgpt = ChatGPT()
設定FastAPI
py
# main.py
app=FastAPI()
@app.get('/')
async def hello():
return '首頁看一下!'
導入對話到路由!
py
# main.py
@app.post('/callback')
async def callback(request: Request):
signature = request.headers["X-Line-Signature"]
body = await request.body()
try:
handler.handle(body.decode(), signature)
except InvalidSignatureError:
raise HTTPException(status_code=400, detail="Missing Parameters")
return "OK"
送到LineBot上
py
# main.py
@handler.add(MessageEvent, message=TextMessage)
def handling_message(event):
if isinstance(event.message, TextMessage):
user_message = event.message.text
# 放入chatgpt回應內容
reply_msg = chatgpt.get_response(user_message)
#
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_msg))
py
# main.py
if __name__=='__main__':
uvicorn.run()