Skip to content

Latest commit

 

History

History
559 lines (427 loc) · 16.6 KB

File metadata and controls

559 lines (427 loc) · 16.6 KB

第四節:使用 Chainlit 建立生產級聊天應用程式

概覽

本節課程專注於使用 Chainlit 和 Microsoft Foundry Local 建立生產級聊天應用程式。您將學習如何為 AI 對話創建現代化的網頁介面、實現流式回應,以及部署具有完善錯誤處理和用戶體驗設計的穩健聊天應用程式。

您將建立的內容:

  • Chainlit 聊天應用程式:具有流式回應的現代化網頁介面
  • WebGPU 演示:基於瀏覽器的推理,注重隱私的應用程式
  • Open WebUI 整合:與 Foundry Local 配合的專業聊天介面
  • 生產模式:錯誤處理、監控和部署策略

學習目標

  • 使用 Chainlit 建立生產級聊天應用程式
  • 實現流式回應以提升用戶體驗
  • 掌握 Foundry Local SDK 的整合模式
  • 應用正確的錯誤處理和優雅降級策略
  • 部署並配置聊天應用程式以適應不同環境
  • 理解對話式 AI 的現代網頁介面模式

先決條件

  • Foundry Local:已安裝並運行 (安裝指南)
  • Python:版本 3.10 或以上,具備虛擬環境功能
  • 模型:至少載入一個模型(foundry model run phi-4-mini
  • 瀏覽器:支持 WebGPU 的現代網頁瀏覽器(Chrome/Edge)
  • Docker:用於 Open WebUI 整合(可選)

第一部分:理解現代聊天應用程式

架構概覽

User Browser ←→ Chainlit UI ←→ Python Backend ←→ Foundry Local ←→ AI Model
      ↓              ↓              ↓              ↓            ↓
   Web UI      Event Handlers   OpenAI Client   HTTP API    Local GPU

核心技術

Foundry Local SDK 模式:

  • FoundryLocalManager(alias):自動化服務管理
  • manager.endpointmanager.api_key:連接詳情
  • manager.get_model_info(alias).id:模型識別

Chainlit 框架:

  • @cl.on_chat_start:初始化聊天會話
  • @cl.on_message:處理用戶發送的消息
  • cl.Message().stream_token():實時流式回應
  • 自動化 UI 生成和 WebSocket 管理

第二部分:本地與雲端的決策矩陣

性能特徵

方面 本地(Foundry) 雲端(Azure OpenAI)
延遲 🚀 50-200ms(無網絡) ⏱️ 200-2000ms(取決於網絡)
隱私 🔒 數據不離開設備 ⚠️ 數據發送至雲端
成本 💰 硬件後免費 💸 按 token 計費
離線 ✅ 無需網絡即可運行 ❌ 需要網絡
模型大小 ⚠️ 受硬件限制 ✅ 可使用最大模型
擴展性 ⚠️ 依賴硬件 ✅ 無限擴展

混合策略模式

本地優先,雲端備援:

async def hybrid_completion(prompt: str, complexity_threshold: int = 100):
    if len(prompt.split()) < complexity_threshold:
        return await local_completion(prompt)  # Fast, private
    else:
        return await cloud_completion(prompt)   # Complex reasoning

基於任務的路由:

async def smart_routing(prompt: str, task_type: str):
    routing_rules = {
        "code_generation": "local",     # Privacy-sensitive
        "creative_writing": "cloud",    # Benefits from larger models
        "data_analysis": "local",       # Fast iteration needed
        "research": "cloud"             # Requires broad knowledge
    }
    
    if routing_rules.get(task_type) == "local":
        return await foundry_completion(prompt)
    else:
        return await azure_completion(prompt)

第三部分:範例 04 - Chainlit 聊天應用程式

快速開始

# Navigate to Module08 directory  
cd Module08

# Start your preferred model
foundry model run phi-4-mini

# Run the Chainlit application (avoiding port conflicts)
chainlit run samples\04\app.py -w --port 8080

應用程式會自動在 http://localhost:8080 打開,提供現代化聊天介面。

核心實現

範例 04 展示了生產級模式:

自動化服務發現:

import chainlit as cl
from openai import OpenAI
from foundry_local import FoundryLocalManager

# Global variables for client and model
client = None
model_name = None

async def initialize_client():
    global client, model_name
    alias = os.environ.get("MODEL", "phi-4-mini")
    
    try:
        # Use FoundryLocalManager for proper service management
        manager = FoundryLocalManager(alias)
        model_info = manager.get_model_info(alias)
        
        client = OpenAI(
            base_url=manager.endpoint,
            api_key=manager.api_key or "not-required"
        )
        model_name = model_info.id if model_info else alias
        return True
    except Exception as e:
        # Fallback to manual configuration
        base_url = os.environ.get("BASE_URL", "http://localhost:51211")
        client = OpenAI(base_url=f"{base_url}/v1", api_key="not-required")
        model_name = alias
        return True

流式聊天處理:

@cl.on_message
async def main(message: cl.Message):
    # Create streaming response
    msg = cl.Message(content="")
    await msg.send()
    
    stream = client.chat.completions.create(
        model=model_name,
        messages=[
            {"role": "system", "content": "You are a helpful AI assistant."},
            {"role": "user", "content": message.content}
        ],
        stream=True
    )
    
    # Stream tokens in real-time
    for chunk in stream:
        if chunk.choices[0].delta.content:
            await msg.stream_token(chunk.choices[0].delta.content)
    
    await msg.update()

配置選項

環境變數:

變數 描述 預設值 範例
MODEL 使用的模型別名 phi-4-mini qwen2.5-7b
BASE_URL Foundry Local 端點 自動檢測 http://localhost:51211
API_KEY API 密鑰(本地可選) "" your-api-key

進階使用:

# Use different model
set MODEL=qwen2.5-7b
chainlit run samples\04\app.py -w --port 8080

# Use different ports (avoid 51211 which is used by Foundry Local)
chainlit run samples\04\app.py -w --port 3000
chainlit run samples\04\app.py -w --port 5000

第四部分:創建和使用 Jupyter 筆記本

筆記本支持概覽

範例 04 包含一個全面的 Jupyter 筆記本(chainlit_app.ipynb),提供:

  • 📚 教育內容:逐步學習材料
  • 🔬 互動探索:運行並試驗代碼單元
  • 📊 視覺演示:圖表、圖解和輸出可視化
  • 🛠️ 開發工具:測試和調試功能

創建自己的筆記本

步驟 1:設置 Jupyter 環境

# Ensure you're in the Module08 directory
cd Module08

# Activate your virtual environment
.venv\Scripts\activate

# Install Jupyter and dependencies
pip install jupyter notebook jupyterlab ipykernel
pip install -r requirements.txt

# Register the kernel for VS Code
python -m ipykernel install --user --name=foundry-local --display-name="Foundry Local"

步驟 2:創建新筆記本

使用 VS Code:

  1. 在 Module08 目錄中打開 VS Code
  2. 創建一個 .ipynb 擴展名的新文件
  3. 選擇 "Foundry Local" 核心環境
  4. 開始添加內容單元

使用 Jupyter Lab:

# Start Jupyter Lab
jupyter lab

# Navigate to samples/04/ and create new notebook
# Choose Python 3 kernel

筆記本結構最佳實踐

單元組織

# Cell 1: Imports and Setup
import os
import sys
import chainlit as cl
from openai import OpenAI
from foundry_local import FoundryLocalManager

print("✅ Libraries imported successfully")
# Cell 2: Configuration and Client Setup
class FoundryClientManager:
    def __init__(self, model_name="phi-4-mini"):
        self.model_name = model_name
        self.client = None
        
    def initialize_client(self):
        # Client initialization logic
        pass

# Initialize and test
client_manager = FoundryClientManager()
result = client_manager.initialize_client()
print(f"Client initialized: {result}")

互動範例和練習

練習 1:客戶端配置測試

# Test different configuration methods
configurations = [
    {"method": "foundry_sdk", "model": "phi-4-mini"},
    {"method": "manual", "base_url": "http://localhost:51211", "model": "qwen2.5-7b"},
]

for config in configurations:
    print(f"\n🧪 Testing {config['method']} configuration...")
    # Implementation here
    result = test_configuration(config)
    print(f"Result: {'✅ Success' if result['status'] == 'ok' else '❌ Failed'}")

練習 2:流式回應模擬

import asyncio

async def simulate_streaming_response(text, delay=0.1):
    """Simulate how streaming works in Chainlit."""
    print("🌊 Simulating streaming response...")
    
    for char in text:
        print(char, end='', flush=True)
        await asyncio.sleep(delay)
    
    print("\n✅ Streaming complete!")

# Test the simulation
sample_text = "This is how streaming responses work in Chainlit applications!"
await simulate_streaming_response(sample_text)

第五部分:WebGPU 瀏覽器推理演示

概覽

WebGPU 允許直接在瀏覽器中運行 AI 模型,實現最大隱私和零安裝體驗。本範例展示了使用 ONNX Runtime Web 和 WebGPU 執行的演示。

步驟 1:檢查 WebGPU 支持

瀏覽器要求:

  • Chrome/Edge 113+,啟用 WebGPU
  • 檢查:chrome://gpu → 確認 "WebGPU" 狀態
  • 程式檢查:if (!('gpu' in navigator)) { /* no WebGPU */ }

步驟 2:創建 WebGPU 演示

創建目錄:samples/04/webgpu-demo/

index.html:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebGPU + ONNX Runtime Demo</title>
    <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.webgpu.min.js"></script>
    <style>
        body { font-family: system-ui, sans-serif; margin: 2rem; }
        pre { background: #f5f5f5; padding: 1rem; overflow: auto; }
        .status { padding: 1rem; background: #e3f2fd; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>🚀 WebGPU + Foundry Local Integration</h1>
    <div id="status" class="status">Initializing...</div>
    <pre id="output"></pre>
    <script type="module" src="./main.js"></script>
</body>
</html>

main.js:

const statusEl = document.getElementById('status');
const outputEl = document.getElementById('output');

function log(msg) {
    outputEl.textContent += `${msg}\n`;
    console.log(msg);
}

(async () => {
    try {
        if (!('gpu' in navigator)) {
            statusEl.textContent = '❌ WebGPU not available';
            return;
        }
        
        statusEl.textContent = '🔍 WebGPU detected. Loading model...';
        
        // Use a small ONNX model for demo
        const modelUrl = 'https://huggingface.co/onnx/models/resolve/main/vision/classification/mnist-12/mnist-12.onnx';
        
        const session = await ort.InferenceSession.create(modelUrl, {
            executionProviders: ['webgpu']
        });
        
        log('✅ ONNX Runtime session created with WebGPU');
        log(`📊 Input names: ${session.inputNames.join(', ')}`);
        log(`📊 Output names: ${session.outputNames.join(', ')}`);
        
        // Create dummy input (MNIST expects 1x1x28x28)
        const inputData = new Float32Array(1 * 1 * 28 * 28).fill(0.1);
        const input = new ort.Tensor('float32', inputData, [1, 1, 28, 28]);
        
        const feeds = {};
        feeds[session.inputNames[0]] = input;
        
        const results = await session.run(feeds);
        const output = results[session.outputNames[0]];
        
        // Find prediction (argmax)
        let maxIdx = 0;
        for (let i = 1; i < output.data.length; i++) {
            if (output.data[i] > output.data[maxIdx]) maxIdx = i;
        }
        
        statusEl.textContent = '✅ WebGPU inference complete!';
        log(`🎯 Predicted class: ${maxIdx}`);
        log(`📈 Confidence scores: [${Array.from(output.data).map(x => x.toFixed(3)).join(', ')}]`);
        
    } catch (error) {
        statusEl.textContent = `❌ Error: ${error.message}`;
        log(`Error: ${error.message}`);
        console.error(error);
    }
})();

步驟 3:運行演示

# Create demo directory
mkdir samples\04\webgpu-demo
cd samples\04\webgpu-demo

# Save HTML and JS files, then serve
python -m http.server 5173

# Open browser to http://localhost:5173

第六部分:Open WebUI 整合

概覽

Open WebUI 提供了一個專業的 ChatGPT 式介面,連接到 Foundry Local 的 OpenAI 兼容 API。

步驟 1:先決條件

# Verify Foundry Local is running
foundry service status

# Start a model
foundry model run phi-4-mini

# Confirm API endpoint is accessible
curl http://localhost:51211/v1/models

步驟 2:Docker 設置(推薦)

# Pull Open WebUI image
docker pull ghcr.io/open-webui/open-webui:main

# Run with Foundry Local connection
docker run -d --name open-webui -p 3000:8080 ^
  -e OPENAI_API_BASE_URL=http://host.docker.internal:51211/v1 ^
  -e OPENAI_API_KEY=foundry-local-key ^
  -v open-webui-data:/app/backend/data ^
  ghcr.io/open-webui/open-webui:main

注意: host.docker.internal 允許 Docker 容器在 Windows 上訪問主機。

步驟 3:配置

  1. **打開瀏覽器:**導航至 http://localhost:3000
  2. **初始設置:**創建管理員帳戶
  3. 模型配置:
    • 設置 → 模型 → OpenAI API
    • 基本 URL:http://host.docker.internal:51211/v1
    • API 密鑰:foundry-local-key(任意值均可)
  4. **測試連接:**模型應出現在下拉選單中

故障排除

常見問題:

  1. 連接被拒:

    # Check Foundry Local status
    foundry service ps
    netstat -ano | findstr :51211
  2. 模型未顯示:

    • 驗證模型是否已載入:foundry model list
    • 檢查 API 回應:curl http://localhost:51211/v1/models
    • 重啟 Open WebUI 容器

第七部分:生產部署考量

環境配置

開發設置:

# Development with auto-reload and debugging
chainlit run samples\04\app.py -w --port 8080 --debug

生產部署:

# Production mode with optimizations
chainlit run samples\04\app.py --host 0.0.0.0 --port 8080 --no-cache

常見端口問題及解決方案

端口 51211 衝突預防:

# Check what's using Foundry Local port
netstat -ano | findstr :51211

# Use different port for Chainlit
chainlit run samples\04\app.py -w --port 8080

性能監控

健康檢查實現:

@cl.on_chat_start
async def health_check():
    try:
        # Test model availability
        response = client.chat.completions.create(
            model=model_name,
            messages=[{"role": "user", "content": "test"}],
            max_tokens=1
        )
        return {"status": "healthy", "model": model_name}
    except Exception as e:
        return {"status": "unhealthy", "error": str(e)}

總結

第四節課程涵蓋了使用 Chainlit 建立生產級對話式 AI 應用程式的內容。您學習了:

  • Chainlit 框架:現代化 UI 和聊天應用程式的流式支持
  • Foundry Local 整合:SDK 使用和配置模式
  • WebGPU 推理:基於瀏覽器的 AI,注重隱私
  • Open WebUI 設置:專業聊天介面的部署
  • 生產模式:錯誤處理、監控和擴展

範例 04 應用程式展示了最佳實踐,通過 Microsoft Foundry Local 利用本地 AI 模型,提供卓越的用戶體驗。

參考資料


免責聲明
本文件已使用 AI 翻譯服務 Co-op Translator 進行翻譯。儘管我們致力於提供準確的翻譯,請注意自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於關鍵資訊,建議使用專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。