VIBE CODING 氛圍編程 | PART 4

技術與實作

打造你的第一個 AI 聊天助手

Flask 後端 OpenAI API Google Gemini 環境變數

🎯 本單元學習目標

實際動手建立一個可以運作的 AI 聊天應用程式!

🐍

Python Flask

學習使用 Flask 框架建立後端 API

🔌

API 整合

連接 OpenAI 或 Google Gemini API

🔐

環境變數

安全管理 API Key

💬

聊天介面

建立現代化的前端對話介面

📥 從 GitHub 下載專案

專案已上傳至 GitHub,你可以直接下載使用:

專案網址:
https://github.com/ChatGPT3a01/my_first_ai_app

方法一:下載 ZIP(推薦新手)

  1. 開啟上方 GitHub 網址
  2. 點擊綠色「Code」按鈕
  3. 選擇「Download ZIP」
  4. 解壓縮到你想要的資料夾

方法二:使用 Git Clone

# 開啟命令提示字元,切換到目標資料夾
cd D:\你的資料夾

# 複製專案
git clone https://github.com/ChatGPT3a01/my_first_ai_app.git

# 進入專案資料夾
cd my_first_ai_app

📁 專案結構

my_first_ai_app/
├── app.py # Flask 後端程式
├── requirements.txt # Python 套件清單
├── .env.example # 環境變數範例
├── .env # 環境變數(需自建)
├── .gitignore # Git 忽略檔案
├── 啟動.bat # Windows 快速啟動
└── templates/
    └── index.html # 前端網頁

核心檔案說明

  • app.py - 處理 API 請求與 AI 回應
  • .env - 儲存 API Key(不上傳 Git)
  • templates/ - 前端介面

🔐 環境變數設定

API Key 不應該直接寫在程式碼中,而是透過 .env 檔案管理

.env.example 範例

# AI Provider 選擇
# 設定為 openai 或 google
AI_PROVIDER=openai

# OpenAI API Key
OPENAI_API_KEY=sk-your-key-here

# Google Gemini API Key
GOOGLE_API_KEY=your-key-here

安全提醒

  • .env 檔案必須加入 .gitignore
  • 永遠不要將 API Key 上傳到 GitHub
  • 只提供 .env.example 作為範例

🔑 如何取得 API Key

OpenAI API Key

  1. 前往 platform.openai.com/api-keys
  2. 登入或註冊帳號
  3. 點擊「Create new secret key」
  4. 複製 API Key 貼到 .env 檔案

Google Gemini API Key

  1. 前往 aistudio.google.com/app/apikey
  2. 登入 Google 帳號
  3. 點擊「Create API Key」
  4. 複製 API Key 貼到 .env 檔案

🐍 Flask 後端核心程式碼

from flask import Flask, request, jsonify, render_template
from dotenv import load_dotenv
import os

load_dotenv()  # 載入環境變數

app = Flask(__name__)

# 讀取 AI 提供者設定
AI_PROVIDER = os.getenv('AI_PROVIDER', 'openai')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/chat', methods=['POST'])
def chat():
    user_message = request.json.get('message')

    if AI_PROVIDER == 'openai':
        response = call_openai(user_message)
    else:
        response = call_google(user_message)

    return jsonify({'response': response})

🤖 OpenAI API 呼叫

from openai import OpenAI

client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

def call_openai(message):
    """呼叫 OpenAI API"""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "你是一個友善的 AI 助手"},
            {"role": "user", "content": message}
        ],
        max_tokens=1000
    )
    return response.choices[0].message.content

說明:使用 gpt-4o-mini 模型,成本較低且速度快

🌐 Google Gemini API 呼叫

import google.generativeai as genai

genai.configure(api_key=os.getenv('GOOGLE_API_KEY'))
model = genai.GenerativeModel('gemini-1.5-flash')

def call_google(message):
    """呼叫 Google Gemini API"""
    response = model.generate_content(message)
    return response.text

優點:Google Gemini 有免費額度,適合學習和測試使用

💬 前端聊天介面

關鍵功能

  • 現代化的聊天氣泡設計
  • 即時回應與載入動畫
  • 支援 Enter 鍵送出訊息
  • 錯誤處理機制
  • 響應式設計
<script>
async function sendMessage() {
  const response = await fetch('/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: userInput
    })
  });
  const data = await response.json();
  displayMessage(data.response);
}
</script>

🚀 啟動應用程式

Windows 快速啟動

  1. 複製 .env.example 為 .env
  2. 編輯 .env 填入 API Key
  3. 雙擊執行「啟動.bat」
  4. 開啟瀏覽器訪問 http://127.0.0.1:5000

手動安裝

# 建立虛擬環境
python -m venv venv

# 啟動虛擬環境
venv\Scripts\activate

# 安裝套件
pip install -r requirements.txt

# 啟動應用
python app.py

✨ 完成效果

💬

即時對話

輸入訊息,AI 即時回應

🔄

雙 API 支援

OpenAI 或 Google 二選一

📱

響應式設計

手機、平板、電腦都能用

🔐

安全設計

API Key 安全管理

GitHub 專案:https://github.com/ChatGPT3a01/my_first_ai_app

Part 4 重點回顧

專案架構

Flask 後端 + HTML 前端 + 環境變數管理

API 整合

OpenAI 和 Google Gemini 雙支援

安全性

.env 檔案管理敏感資訊

實作成果

完整可運作的 AI 聊天助手

下一單元:總結與展望