2025-05-29 前端 → gateway → AI 的整個流程,以及 Header / Body 的對應關係
太棒了 😄 我幫你畫一個 圖示化箭頭流程圖,用文字表示前端、Gateway、AI 之間的資料流向,包括 Header、Body 和 API Key 的位置,方便你快速理解整個流程。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| [ 前端 / Postman ] │ │ POST http://localhost:4000/api/chat │ Header: │ Content-Type: application/json │ Body: │ { │ "provider": "openai", │ "messages": [{ "role":"user","content":"hello" }] │ } ▼ ─────────────────────────────── │ MCP Gateway │ │ (gateway.mjs / Express) │ │ │ │ 1️⃣ 解析 Body → provider & messages │ 2️⃣ 檢查 .env API Key │ 3️⃣ 如果無 key → 回 mock │ 4️⃣ 如果有 key → 呼叫 AI API ─────────────────────────────── │ │ POST https://api.openai.com/v1/chat/completions │ (或 DeepSeek API) │ Header: │ Authorization: Bearer <API_KEY> │ Content-Type: application/json │ Body: │ { model: "gpt-3.5-turbo", messages: [...] } ▼ ─────────────────────────────── │ AI Provider │ │ (OpenAI / DeepSeek) │ │ │ │ 回傳 JSON Response │ │ { choices: [...], ... } │ ─────────────────────────────── │ │ Gateway 整理成統一格式 ▼ [ 前端 / Postman ] │ │ Response JSON: │ { │ "provider": "openai", │ "text": "AI 回覆文字", │ "raw": { ...完整 AI 回覆... } │ }
|
🔑 讀圖重點
前端 Header / Body
- Header:告訴 Gateway 內容是 JSON
- Body:告訴 Gateway 要用哪個 AI、訊息內容
Gateway 的工作
- 解析前端請求
- 決定要 mock 還是呼叫真正 AI
- 呼叫外部 API 時帶上 Authorization 與 Body
Gateway 統一回傳
AI Provider
- 接收 Gateway 封裝好的 request
- 回傳結果給 Gateway