第四节:使用Chainlit构建生产级聊天应用


文档摘要

第四节:使用 Chainlit 构建生产级聊天应用 概述 本节课重点讲解如何使用 Chainlit 和 Microsoft Foundry Local 构建生产级聊天应用。您将学习如何创建现代化的 AI 对话网页界面、实现流式响应,以及部署具有完善错误处理和用户体验设计的强大聊天应用。 您将构建: Chainlit 聊天应用:具有流式响应的现代化网页界面 WebGPU 演示:基于浏览器的推理,注重隐私保护 开放 WebUI 集成:与 Foundry Local 集成的专业聊天界面 生产模式:错误处理、监控和部署策略 学习目标 使用 Chainlit 构建生产级聊天应用 实现流式响应以提升用户体验 掌握 Foundry Local SDK 的集成模式 应用正确的错误处理和优雅降级方法

第四节:使用 Chainlit 构建生产级聊天应用

概述

本节课重点讲解如何使用 Chainlit 和 Microsoft Foundry Local 构建生产级聊天应用。您将学习如何创建现代化的 AI 对话网页界面、实现流式响应,以及部署具有完善错误处理和用户体验设计的强大聊天应用。

您将构建:

  • Chainlit 聊天应用:具有流式响应的现代化网页界面
  • WebGPU 演示:基于浏览器的推理,注重隐私保护
  • 开放 WebUI 集成:与 Foundry Local 集成的专业聊天界面
  • 生产模式:错误处理、监控和部署策略

学习目标

  • 使用 Chainlit 构建生产级聊天应用
  • 实现流式响应以提升用户体验
  • 掌握 Foundry Local SDK 的集成模式
  • 应用正确的错误处理和优雅降级方法
  • 为不同环境部署和配置聊天应用
  • 理解现代化网页界面模式以支持对话式 AI

前置条件

  • Foundry Local:已安装并运行(安装指南
  • Python:版本 3.10 或更高,支持虚拟环境
  • 模型:至少加载一个模型(foundry model run phi-4-mini
  • 浏览器:支持 WebGPU 的现代浏览器(Chrome/Edge)
  • Docker:用于开放 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(取决于网络)
隐私 数据不离开设备 ⚠️ 数据发送至云端
成本 硬件后免费 按令牌付费
离线 ✅ 无需互联网即可运行 ❌ 需要互联网
模型规模 ⚠️ 受硬件限制 ✅ 可访问最大模型
扩展性 ⚠️ 依赖硬件 ✅ 无限扩展

混合策略模式

本地优先,云端备选:

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 Notebook

Notebook 支持概述

示例 04 包含一个全面的 Jupyter Notebook(chainlit_app.ipynb),提供以下功能:

  • ** 教学内容**:逐步学习材料
  • ** 交互式探索**:运行并实验代码单元
  • ** 可视化演示**:图表、图解和输出可视化
  • ️ 开发工具:测试和调试功能

创建您自己的 Notebook

第一步:设置 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"

第二步:创建新 Notebook

使用 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

Notebook 结构最佳实践

单元组织

# 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 执行的过程。

第一步:检查 WebGPU 支持

浏览器要求:

  • Chrome/Edge 113+,启用 WebGPU
  • 检查:chrome://gpu → 确认“WebGPU”状态
  • 编程检查:if (!('gpu' in navigator)) { /* no WebGPU */ }

第二步:创建 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:5173

第六部分:开放 WebUI 集成

概述

开放 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

第二步: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)。

第三步:配置

  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
    • 重启开放 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,注重隐私保护
  • 开放 WebUI 设置:专业聊天界面部署
  • 生产模式:错误处理、监控和扩展

示例 04 应用展示了最佳实践,帮助您构建强大的聊天界面,利用 Microsoft Foundry Local 的本地 AI 模型,同时提供卓越的用户体验。

参考资料

免责声明
本文档使用AI翻译服务 Co-op Translator 进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。原始语言的文档应被视为权威来源。对于关键信息,建议使用专业人工翻译。我们对因使用此翻译而产生的任何误解或误读不承担责任。


作者与出处
原作者: microsoft
来源:microsoft
许可证:MIT
整理: 灏天文库整理
由灏天文库结构化整理,提供目录导航、全文检索与在线阅读,便于系统化学习
发布者: 作者: microsoft 转发
评论区 (0)
U