C:\AI_Projects\local-ai-chat
~/AI_Projects/local-ai-chat
我們將所有程式碼(HTML、CSS、JS)整合在單一檔案中,方便管理與部署。
網頁由四個主要區塊組成:
<div class="chat-header">
本地 AI 對話平台
</div>
顯示平台名稱與品牌識別
<select id="model-select">
<option value="llama3">Llama 3</option>
<option value="mistral">Mistral</option>
</select>
讓使用者切換不同 AI 模型
<div class="chat-messages">
<!-- 對話記錄在這裡 -->
</div>
顯示使用者與 AI 的對話
<input type="text" id="chat-input">
<button id="send-button">發送</button>
使用者輸入問題的地方
body {
background: linear-gradient(
135deg,
#667eea 0%,
#764ba2 100%
);
}
.chat-container {
border-radius: 20px;
box-shadow: 0 20px 60px
rgba(0,0,0,0.3);
}
/* 使用者訊息 - 右側藍紫色 */
.message.user .message-content {
background: linear-gradient(...);
color: white;
}
/* AI 訊息 - 左側白色 */
.message.assistant .message-content {
background: white;
border: 1px solid #e0e0e0;
}
http://localhost:11434/api/generate
// 呼叫 Ollama API
const response = await fetch('http://localhost:11434/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'llama3', // 使用的模型
prompt: '你好', // 使用者輸入
stream: false // 不使用串流(等完整回應)
})
});
const data = await response.json();
console.log(data.response); // AI 的回答
在輸入框輸入問題,按下「發送」
使用者訊息顯示在右側,顯示載入動畫
將問題傳送給 Ollama,等待 AI 處理
AI 回答顯示在左側,自動捲動
async function sendMessage() {
const message = chatInput.value.trim();
if (!message) return;
addMessage('user', message); // 步驟 2
chatInput.value = '';
loadingIndicator.classList.add('active');
const response = await fetch(...); // 步驟 3
const data = await response.json();
addMessage('assistant', data.response); // 步驟 4
}
良好的錯誤處理讓使用者知道問題出在哪裡:
try {
const response = await fetch(OLLAMA_API, { ... });
if (!response.ok) {
throw new Error(`API 錯誤: ${response.status}`);
}
const data = await response.json();
addMessage('assistant', data.response);
} catch (error) {
showError(`發生錯誤: ${error.message}
請確認:
1. Ollama 已經啟動
2. 已下載選擇的模型
3. 瀏覽器可以連接 localhost:11434`);
}
檢查系統匣圖示,或瀏覽器開啟 http://localhost:11434
cd C:\AI_Projects\local-ai-chat
python -m http.server 8080
http://localhost:8080/index.html
你好,請用繁體中文自我介紹
確認 AI 能正常回應中文
請用 Python 寫一個計算質數的函數
確認程式碼格式正確顯示
選擇不同模型(如 Mistral),觀察回答風格差異
關閉 Ollama 後發送訊息,確認錯誤提示正常顯示
| 功能 | 說明 | 難度 |
|---|---|---|
| 對話記錄儲存 | 使用 localStorage 保存對話,下次開啟可繼續 | 簡單 |
| 串流回應 | 設定 stream: true,讓文字逐字顯示 |
中等 |
| 匯出對話 | 將對話記錄匯出為 TXT 或 JSON 檔案 | 簡單 |
| 語音輸入 | 使用 Web Speech API 實現語音轉文字 | 中等 |
| 系統提示詞 | 加入可編輯的 System Prompt 設定 AI 角色 | 簡單 |
恭喜!你已經建立了一個完整的網頁版 AI 對話平台。
fetch() 非同步 API 呼叫在 Part 4,我們將深入了解系統架構與模型選擇策略,學會如何根據需求選擇最適合的模型。