在前一篇測試中我們已利用架設在 render.com 的仿 GCF 函式執行平台 serverless 當作 LINE Bot 的後端回應伺服器, 順利實作了一個 Echo bot, 它會傳回我們所說的話. 本篇旨在測試如何進一步讓後端回應程式串接 OpenAI, 變成一個 AI 聊天機器人.
本系列之前的測試文章參考 :
關於 OpenAI API 用法參考 :
為了能串接 OpenAI API, 我們已在前一篇測試中修改 requirements.txt 檔安裝 openai 套件, 因此在函式模組中可以直接匯入 openai 套件來使用.
1. 設定環境變數 :
由於在佈署 serverless 服務時忘了在 .env 檔案中添加 OpenAI API 的金鑰, 這可在儀錶板的 Environment 頁面的 Secret File 項目中按 Edit 鈕編輯即可 :
按右邊的檢視鈕 :
在彈出視窗中貼上要添加的 OPENAI_API_KEY , 按 Done 鈕存檔 :
按右邊的按鈕選擇 "Save, rebuild, and deploy" :
修改環境變數必須這樣才能確保有載入容器內.
2. 撰寫後端回應程式串接 GPT 模型 :
在前一篇測試中, Render 上的後端回應程式 linebot_echo.py 僅僅是取得使用者詢問後便傳回去, 如果要與 GPT 模型聊天, 就必須將詢問傳給 GPT, 取得模型回應後再傳回給使用者. 在 serverless 平台按 "新增函式" :
輸入如下程式碼 :
# linebot_gpt.py
from flask import abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import os
from openai import OpenAI
def main(request, **kwargs):
# 取得主程式傳入的 LINE 與 OpenAI 金鑰權杖
config=kwargs.get('config', {})
secret=config.get('LINE_CHANNEL_SECRET')
token=config.get('LINE_CHANNEL_ACCESS_TOKEN')
openai_api_key=config.get('OPENAI_API_KEY', os.getenv('OPENAI_API_KEY'))
# 檢查必要參數
if not secret or not token or not openai_api_key:
return {'error': 'Missing LINE or OpenAI credentials'}
# 初始化 LINE API 與 Webhook Handler
line_bot_api=LineBotApi(token)
handler=WebhookHandler(secret)
client=OpenAI(api_key=openai_api_key)
# 註冊 MessageEvent + TextMessage 處理器
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
user_text=event.message.text # 取得 LINE Bot 使用者詢問
# 呼叫 OpenAI GPT 生成回應
response=client.chat.completions.create(
model='gpt-3.5-turbo', # GPT 模型
messages=[{'role': 'user', 'content': user_text}],
max_tokens=300
)
reply_text=response.choices[0].message.content
# 回傳給 LINE Bot 使用者
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=reply_text)
)
# 取得簽章與 request body
signature=request.headers.get("X-Line-Signature", "")
body=request.get_data(as_text=True)
# 驗證簽章是否正確
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400, "Invalid signature")
return {"status": "ok"}
存檔後在函式列表頁上, 將滑鼠移到 linebot_gpt 模組的 "執行" 連結處, 按滑鼠右鍵點選 "複製連結網址" 即可取得此回應程式的 web hook 網址 :
# https://serverless-fdof.onrender.com/function/linebot_gpt
此網址無法直接執行, 必須經過驗證是從 LINE 伺服器發出的才會回應.
然後登入 Line 開發者控制台將聊天機器人的 Webhook URL 改成這個網址經 Verify 成功即可, 作法參考前一篇測試 :
這樣便能與 GPT 模型聊天了 :









沒有留言 :
張貼留言