## 1\. 🤖 AI 模型基礎與 API 串接 ### 1.1. 🧠 常見深度學習模型架構 | 領域 | 模型類型 | 主要應用場景 | | :--- | :--- | :--- | | **表格型** | **MLP (多層感知器)** | 典型分類與回歸問題 | | **自我監督** | **AE (自編碼器)** | 特徵擷取/降維、異常偵測 | | **CV (電腦視覺)** | **CNN (卷積神經網路)** | 圖像分類、物件偵測 | | **生成** | **GAN (生成對抗網路)** | 數據擴增、仿真影像 | | **NLP (自然語言)** | **RNN (循環神經網路)**、**Transformer** | 情感分析、股價預測、機器翻譯、文字摘要 | > **LLM 模型 vs. 傳統模型**:LLM 模型(如 **GPT-4**、**Gemini**)主要通過 **提示 (Prompts)**(即 **提示工程 (Prompt Engineering)**)驅動,可以**無需訓練**即產生結果。 ### 1.2. 💻 LLM API 串接實作(Gemini 與 ChatGPT) 在程式中應用 LLM,需先安裝對應的 SDK,並配置 API 金鑰。 * **API Key 隱藏**:為了保護帳戶安全,強烈建議將 **API KEY** 隱藏在 **環境變數**(如 Replit Secrets)或 **Colab Secrets** 中。 #### Gemini API 實作(以 `gemini-1.5-flash` 為例) ```python import google.generativeai as genai from google.colab import userdata # 1. 從 Colab Secrets 獲取並配置 API Key GEMINI_API_KEY = userdata.get('GEMINI_API_KEY') genai.configure(api_key=GEMINI_API_KEY) # 2. 呼叫模型並生成內容 model = genai.GenerativeModel("gemini-1.5-flash") response = model.generate_content("你好,請問你是誰?") print(response.text) ``` #### ChatGPT API 實作(以 `gpt-4o-mini` 為例) ```python import openai from openai import OpenAI from google.colab import userdata # 1. 取得 API Key OPENAI_API_KEY = userdata.get('OPENAI_API_KEY') # 2. 建立 Client 並設定系統角色 client = OpenAI(api_key = OPENAI_API_KEY) completion = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "請問你是誰?"} ] ) print(completion.choices[0].message.content) ``` ## 2\. 💬 串接 Linebot 實作聊天機器人 將 LLM 整合到 **LINE** 等訊息應用程式中,是實踐 AI 模型的常見應用場景。 ### 2.1. 🔑 Line Bot 開發的核心概念 * **Line Bot 應用流程**:使用者透過對話模擬人類互動,常見應用包括網路客服、預訂服務、智能助理等。 * **Webhook 機制**:這是實現自定義 Line Bot 訊息的核心架構。當用戶發送訊息時,LINE 平台會向您設定的 **Webhook 伺服器** (通常是 Flask/Replit 服務) 發送事件訊息,等待 **HTTP 狀態碼 200** 的回覆。 * **關鍵密鑰**:開發前需在 LINE Developers 平台獲取並記錄 **Channel secret** (用於簽章驗證) 和 **Channel access token** (用於回覆訊息)。 ### 2.2. 🛠️ 環境配置與重要設定 1. **部署環境**:使用 **Replit** 建立一個 **Flask 伺服器**,提供一個公開的 URL 作為 Webhook 服務器。 2. **套件安裝**:需安裝 **`line-bot-sdk`** 處理 LINE 訊息事件。 3. **Webhook URL 設定**:將 Replit 產生的伺服器網址貼到 LINE Developers 的 Webhook 設定頁面。 4. **關閉自動回覆**:必須在 LINE Official Account Manager 中**關閉 (Disabled)** **自動回覆訊息 (Auto-reply messages)**,以確保訊息能被您的程式碼接管。 ### 2.3. 💻 實戰:Flask Webhook 程式碼 使用 **Flask** 建立 Webhook 入口,並使用 **`LineBotApi`** 與 **`WebhookHandler`** 處理邏輯。 ```python from flask import Flask, request, abort from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage # 1. 從環境變數中取得金鑰 # LINE_TOKEN = os.environ.get('LINE_TOKEN') # LINE_SECRET = os.environ.get('LINE_SECRET') line_bot_api = LineBotApi(LINE_TOKEN) handler = WebhookHandler(LINE_SECRET) app = Flask(__name__) # 2. Webhook 訊息接收點 @app.route("/callback", methods=['POST']) def callback(): signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) app.logger.info("Request body: " + body) try: handler.handle(body, signature) except InvalidSignatureError: abort(400) # 簽章無效 return 'OK' # 3. 處理文本訊息事件(這裡應整合 LLM 呼叫) @handler.add(MessageEvent, message=TextMessage) def handle_message(event): user_text = event.message.text # ... (整合 LLM 呼叫邏輯) ... reply_text = f"LLM 回覆給您的內容: {user_text}" line_bot_api.reply_message( event.reply_token, TextSendMessage(text=reply_text) # 將 LLM 結果回傳 ) ``` ## 3\. 🖼️ 結合 Streamlit、Gradio 快速打造互動界面 除了通訊軟體,也可以利用專門的 Python 函式庫快速建立 Web 介面。 ### 3.1. 🚀 Gradio:專注於模型展示的快速介面 * **特色**:Gradio 是最快 demo **機器學習模型**的工具,只需定義**函數 (fn)**、**輸入 (inputs)** 和 **輸出 (outputs)** 即可建立網頁介面。 * **優勢功能**:內建對 **串流 (Streaming)** 模式的優化支援,能讓 LLM 回應逐字輸出,提供類似 **ChatGPT** 的互動體驗。 #### Gradio 串流對話實作 ```python # Gradio 實作:將 LLM 整合為串流對話介面 import gradio as gr def get_response(message, history, system_prompt, stream, temperature): # 這裡實作呼叫 OpenAI/Gemini API,並將 stream 參數設為 True # response = client.chat.completions.create(..., stream=stream) if stream: reply = '' for chunk in response: # 逐塊獲取並回傳 (yield) 內容 reply += chunk.choices[0].delta.content or '' yield reply # 使用 yield 實現串流 else: # 非串流模式,直接返回完整回應 yield response.choices[0].message.content # 建立 ChatInterface,並增加 System Prompt, Stream, Temperature 參數控制 demo = gr.ChatInterface( get_response, additional_inputs=[ gr.Textbox("You are helpful AI.", label="System Prompt"), gr.Checkbox(label='Stream', value=True), gr.Slider(0, 2, value=0.8, label="Temperature") ] ) demo.queue().launch() ``` * **關鍵機制**:在 Gradio 中,如果 **LLM 函式** (例如 `get_response`) 使用 Python 的 `yield` 關鍵字,Gradio 會自動以**串流 (Streaming)** 方式將內容即時傳輸到前端。 ### 3.2. 🖼️ Streamlit:快速建立數據應用的網頁框架 * **特色**:Streamlit 讓資料科學家和工程師可以使用純 **Python** 程式碼來建立互動式網頁應用。 #### Streamlit 整合 LLM 實作概念 ```python # Streamlit 實作:建立一個單純的問答介面 import streamlit as st import google.generativeai as genai # 配置 LLM 模型... (省略配置步驟) def generate_response(prompt): # ... (呼叫 LLM 產生回應) return response.text st.title("LLM Streamlit Demo") user_input = st.text_input("輸入你的訊息:", "") if st.button("送出"): if user_input: st.text(f"你: {user_input}") chatgpt_response = generate_response(user_input) st.text(f"LLM 回應: {chatgpt_response}") # 在 Colab 中運行 Streamlit # !streamlit run app.py &>/content/logs.txt & npx localtunnel --port 8501 ```