本節課程專注於使用 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.endpoint和manager.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)# 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範例 04 包含一個全面的 Jupyter 筆記本(chainlit_app.ipynb),提供:
- 📚 教育內容:逐步學習材料
- 🔬 互動探索:運行並試驗代碼單元
- 📊 視覺演示:圖表、圖解和輸出可視化
- 🛠️ 開發工具:測試和調試功能
# 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"使用 VS Code:
- 在 Module08 目錄中打開 VS Code
- 創建一個
.ipynb擴展名的新文件 - 選擇 "Foundry Local" 核心環境
- 開始添加內容單元
使用 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}")# 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'}")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 允許直接在瀏覽器中運行 AI 模型,實現最大隱私和零安裝體驗。本範例展示了使用 ONNX Runtime Web 和 WebGPU 執行的演示。
瀏覽器要求:
- Chrome/Edge 113+,啟用 WebGPU
- 檢查:
chrome://gpu→ 確認 "WebGPU" 狀態 - 程式檢查:
if (!('gpu' in navigator)) { /* no 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);
}
})();# 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:5173Open WebUI 提供了一個專業的 ChatGPT 式介面,連接到 Foundry Local 的 OpenAI 兼容 API。
# 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# 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 上訪問主機。
- **打開瀏覽器:**導航至
http://localhost:3000 - **初始設置:**創建管理員帳戶
- 模型配置:
- 設置 → 模型 → OpenAI API
- 基本 URL:
http://host.docker.internal:51211/v1 - API 密鑰:
foundry-local-key(任意值均可)
- **測試連接:**模型應出現在下拉選單中
常見問題:
-
連接被拒:
# Check Foundry Local status foundry service ps netstat -ano | findstr :51211
-
模型未顯示:
- 驗證模型是否已載入:
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 模型,提供卓越的用戶體驗。
- 範例 04:Chainlit 應用程式:完整應用程式及文檔
- Chainlit 教育筆記本:互動學習材料
- Foundry Local 文檔:完整平台文檔
- Chainlit 文檔:官方框架文檔
- Open WebUI 整合指南:官方教程
免責聲明:
本文件已使用 AI 翻譯服務 Co-op Translator 進行翻譯。儘管我們致力於提供準確的翻譯,請注意自動翻譯可能包含錯誤或不準確之處。原始文件的母語版本應被視為權威來源。對於關鍵資訊,建議使用專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。