OpenGenerativeUI 学习教程
OpenGenerativeUI 学习教程
一、环境准备
1.1 前置知识
学习本教程前,建议具备以下基础:
| 知识领域 | 要求程度 | 说明 |
|---|---|---|
| React | 熟练 | 组件开发、Hooks 使用 |
| TypeScript | 了解 | 基本类型定义 |
| Next.js | 了解 | 路由、API 路由 |
| Python | 基础 | Agent 开发(可选) |
| LLM 基础 | 了解 | Prompt 工程、API 调用 |
1.2 环境要求
| 依赖 | 版本要求 | 说明 |
|---|---|---|
| Node.js | 18+ | JavaScript 运行时 |
| Python | 3.10+ | Agent 后端 |
| pnpm | 8+ | 包管理器 |
| Git | 最新版 | 版本控制 |
1.3 API Key 准备
# OpenAI API Key(必需)
export OPENAI_API_KEY=sk-xxxxxxxx
# 或在 apps/agent/.env 中配置
二、快速开始
2.1 安装步骤
# Step 1: 克隆仓库
git clone https://github.com/CopilotKit/OpenGenerativeUI.git
cd OpenGenerativeUI
# Step 2: 安装依赖 + 创建环境变量模板
make setup
# Step 3: 配置 API Key
# 编辑 apps/agent/.env 文件
# OPENAI_API_KEY=your-api-key-here
# Step 4: 启动服务
make dev
2.2 访问应用
启动成功后,可以访问:
| 服务 | 地址 | 说明 |
|---|---|---|
| 前端应用 | http://localhost:3000 | Next.js Web 界面 |
| Agent 服务 | http://localhost:8123 | LangGraph Agent API |
2.3 Hello World 示例
在浏览器中打开 http://localhost:3000,在聊天框中输入:
帮我可视化二分搜索算法
Agent 将生成一个交互式的二分搜索可视化组件。
三、核心概念
3.1 概念图谱
┌─────────────────────────────────────────────────────────────────────────┐
│ OpenGenerativeUI 核心概念 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ │
│ │ Prompt │ │
│ │ (用户输入) │ │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Agent │ │
│ │ (LangGraph)│ │
│ └──────┬──────┘ │
│ │ │
│ ┌────────────────┼────────────────┐ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Text │ │ Tool │ │ Generative│ │
│ │ Response │ │ Call │ │ UI │ │
│ └───────────┘ └───────────┘ └───────────┘ │
│ │ │
│ ▼ │
│ ┌───────────┐ │
│ │ Sandbox │ │
│ │ Iframe │ │
│ └───────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
3.2 核心概念详解
3.2.1 Generative UI(生成式 UI)
定义:AI Agent 生成的不只是文字,而是完全交互式的可视化组件。
传统 AI 响应:
┌─────────────────────────────────────────┐
│ 二分搜索是一种在有序数组中查找元素... │
│ 时间复杂度是 O(log n)... │
└─────────────────────────────────────────┘
生成式 UI 响应:
┌─────────────────────────────────────────┐
│ [交互式可视化] │
│ ┌───┬───┬───┬───┬───┬───┬───┬───┐ │
│ │ 1 │ 3 │ 5 │ 7 │ 9 │11 │13 │15 │ │
│ └───┴───┴───┴───┴───┴───┴───┴───┘ │
│ ↑ │
│ [查找 7] [下一步] [重置] │
└─────────────────────────────────────────┘
3.2.2 CopilotKit
定义:React AI 框架,用于构建 AI Copilot 和生成式 UI 应用。
核心能力: - AI 聊天界面 - Agent 控制 - 生成式 UI - 上下文感知
3.2.3 LangGraph
定义:Agent 编排框架,用于构建有状态的 AI Agent。
核心能力: - 工作流编排 - 状态管理 - 工具调用 - 错误处理
3.2.4 Sandbox Iframe
定义:沙箱化的 iframe,用于安全渲染 AI 生成的 HTML/SVG。
特性: - 安全隔离 - 自动主题适配 - 响应式尺寸 - 渐进式加载
3.3 术语表
| 术语 | 英文 | 说明 |
|---|---|---|
| 生成式 UI | Generative UI | AI 动态生成的交互式界面 |
| Agent | AI Agent | 自主决策和执行的 AI 实体 |
| 前端工具 | Frontend Tool | Agent 可调用的前端操作 |
| 人机协作 | Human-in-the-Loop | 需要人工确认的 AI 流程 |
| 沙箱 | Sandbox | 安全隔离的执行环境 |
| 组件 | Component | React UI 组件 |
| Hook | React Hook | React 状态管理函数 |
四、CopilotKit 核心 Hooks
4.1 useComponent(生成式 UI)
用途:动态生成可视化组件
import { useComponent } from "@copilotkit/react-core";
function App() {
const widgetRenderer = useComponent({
name: "renderWidget",
description: "渲染可视化组件",
render: ({ html, title }) => {
return (
<div className="widget-container">
{title && <h3 className="widget-title">{title}</h3>}
<iframe
srcDoc={html}
sandbox="allow-scripts"
className="w-full border-0 rounded-lg"
/>
</div>
);
},
});
return (
<div>
{/* CopilotKit Chat UI */}
<CopilotChat />
</div>
);
}
应用场景: - 图表生成 - 算法可视化 - 交互式组件
4.2 useFrontendTool(前端工具)
用途:Agent 直接操作前端 UI
import { useFrontendTool } from "@copilotkit/react-core";
function App() {
const [theme, setTheme] = useState<"light" | "dark">("light");
// 注册前端工具
useFrontendTool({
name: "toggleTheme",
description: "切换应用主题",
parameters: z.object({
theme: z.enum(["light", "dark"]),
}),
handler: ({ theme }) => {
setTheme(theme);
document.documentElement.classList.toggle("dark", theme === "dark");
return { success: true, theme };
},
});
return (
<div className={theme}>
{/* 应用内容 */}
</div>
);
}
应用场景: - 主题切换 - 表单填充 - UI 状态更新 - 导航控制
4.3 useHumanInTheLoop(人机协作)
用途:需要人工确认的流程
import { useHumanInTheLoop } from "@copilotkit/react-core";
function App() {
const meetingScheduler = useHumanInTheLoop({
name: "scheduleMeeting",
description: "安排会议需要用户确认",
render: ({ proposal, onConfirm, onReject, onModify }) => (
<div className="meeting-card p-4 border rounded-lg">
<h3 className="text-lg font-bold">{proposal.title}</h3>
<p className="text-gray-600">时间:{proposal.time}</p>
<p className="text-gray-600">参与者:{proposal.attendees.join(", ")}</p>
<div className="flex gap-2 mt-4">
<button
onClick={() => onConfirm()}
className="px-4 py-2 bg-green-500 text-white rounded"
>
确认
</button>
<button
onClick={() => onModify({ time: "明天 10:00" })}
className="px-4 py-2 bg-yellow-500 text-white rounded"
>
修改时间
</button>
<button
onClick={() => onReject()}
className="px-4 py-2 bg-red-500 text-white rounded"
>
拒绝
</button>
</div>
</div>
),
});
return <CopilotChat />;
}
应用场景: - 会议调度 - 审批流程 - 敏感操作确认 - 多选项决策
4.4 useDefaultRenderTool(工具状态渲染)
用途:显示工具执行状态
import { useDefaultRenderTool } from "@copilotkit/react-core";
function App() {
useDefaultRenderTool({
render: ({ toolName, status, result, error }) => {
if (status === "loading") {
return <div className="animate-pulse">执行 {toolName}...</div>;
}
if (status === "error") {
return (
<div className="text-red-500">
错误:{error?.message}
</div>
);
}
return (
<div className="text-green-500">
✓ {toolName} 执行成功
</div>
);
},
});
return <CopilotChat />;
}
应用场景: - 加载状态显示 - 错误处理 - 执行结果反馈
五、项目结构详解
5.1 目录结构
OpenGenerativeUI/
├── apps/
│ ├── app/ # Next.js 前端
│ │ ├── src/
│ │ │ ├── app/ # Next.js App Router
│ │ │ ├── components/ # React 组件
│ │ │ │ ├── chat.tsx # 聊天组件
│ │ │ │ └── widgets/ # 生成式组件
│ │ │ ├── hooks/ # 自定义 Hooks
│ │ │ └── lib/ # 工具函数
│ │ ├── public/ # 静态资源
│ │ └── package.json
│ │
│ └── agent/ # LangGraph Python Agent
│ ├── src/
│ │ ├── agent/ # Agent 定义
│ │ │ ├── graph.py # LangGraph 工作流
│ │ │ └── tools.py # Agent 工具
│ │ └── main.py # 入口文件
│ ├── .env # 环境变量
│ └── requirements.txt # Python 依赖
│
├── packages/ # 共享包
│
├── Makefile # 构建命令
├── turbo.json # Turborepo 配置
├── pnpm-workspace.yaml # pnpm 工作区
└── package.json
5.2 关键文件说明
5.2.1 前端关键文件
| 文件 | 说明 |
|---|---|
apps/app/src/app/page.tsx |
主页面 |
apps/app/src/components/chat.tsx |
CopilotKit 聊天组件 |
apps/app/src/hooks/useWidget.ts |
Widget 渲染 Hook |
apps/app/src/app/api/copilotkit/route.ts |
CopilotKit API 路由 |
5.2.2 Agent 关键文件
| 文件 | 说明 |
|---|---|
apps/agent/src/agent/graph.py |
LangGraph 工作流定义 |
apps/agent/src/agent/tools.py |
Agent 工具定义 |
apps/agent/src/main.py |
Agent 服务入口 |
apps/agent/.env |
环境变量配置 |
六、自定义开发
6.1 添加新的生成式组件
Step 1: 定义组件
// apps/app/src/components/widgets/BarChart.tsx
interface BarChartProps {
data: { label: string; value: number }[];
title?: string;
}
export function BarChart({ data, title }: BarChartProps) {
const maxValue = Math.max(...data.map(d => d.value));
return (
<div className="bar-chart p-4">
{title && <h3 className="text-lg font-bold mb-4">{title}</h3>}
<div className="flex items-end gap-2 h-64">
{data.map((item, index) => (
<div key={index} className="flex flex-col items-center">
<div
className="bg-blue-500 w-8 rounded-t"
style={{ height: `${(item.value / maxValue) * 100}%` }}
/>
<span className="text-xs mt-2">{item.label}</span>
</div>
))}
</div>
</div>
);
}
Step 2: 注册到 useComponent
// apps/app/src/hooks/useCharts.ts
import { useComponent } from "@copilotkit/react-core";
import { BarChart } from "../components/widgets/BarChart";
export function useCharts() {
useComponent({
name: "renderBarChart",
description: "渲染柱状图",
render: ({ data, title }) => (
<BarChart data={data} title={title} />
),
});
}
Step 3: 在 App 中使用
// apps/app/src/app/page.tsx
import { useCharts } from "../hooks/useCharts";
export default function Home() {
useCharts(); // 注册组件
return (
<CopilotKit>
<CopilotChat />
</CopilotKit>
);
}
6.2 添加 Agent 工具
Step 1: 定义工具
# apps/agent/src/agent/tools.py
from langchain_core.tools import tool
@tool
def generate_chart_data(chart_type: str, data_description: str) -> dict:
"""
根据描述生成图表数据
Args:
chart_type: 图表类型 (bar, line, pie)
data_description: 数据描述
Returns:
图表数据对象
"""
# 这里可以调用数据生成逻辑
return {
"type": chart_type,
"data": [
{"label": "A", "value": 100},
{"label": "B", "value": 200},
{"label": "C", "value": 150},
]
}
Step 2: 注册到 Agent
# apps/agent/src/agent/graph.py
from langgraph.prebuilt import create_react_agent
from .tools import generate_chart_data
tools = [generate_chart_data]
agent = create_react_agent(
model="openai:gpt-4",
tools=tools,
)
6.3 自定义渲染逻辑
Step 1: 自定义 Widget 渲染器
// apps/app/src/components/WidgetRenderer.tsx
import { useComponent } from "@copilotkit/react-core";
export function WidgetRenderer() {
useComponent({
name: "widgetRenderer",
render: ({ html, type, metadata }) => {
// 根据类型选择渲染方式
switch (type) {
case "chart":
return <ChartWidget html={html} />;
case "diagram":
return <DiagramWidget html={html} />;
case "3d":
return <ThreeDWidget html={html} />;
default:
return <DefaultWidget html={html} />;
}
},
});
return null;
}
function DefaultWidget({ html }: { html: string }) {
return (
<div className="widget-wrapper">
<iframe
srcDoc={html}
sandbox="allow-scripts"
className="w-full border-0"
/>
</div>
);
}
七、实战案例
7.1 案例1:算法可视化
目标:实现排序算法可视化
用户输入:
帮我可视化快速排序算法
Agent 响应: 生成一个交互式的快速排序可视化组件:
// 生成的 HTML/SVG 内容
<div class="sorting-visualizer">
<div class="bars">
<div class="bar" style="height: 60%"></div>
<div class="bar pivot" style="height: 40%"></div>
<div class="bar" style="height: 80%"></div>
<!-- ... -->
</div>
<div class="controls">
<button onclick="step()">下一步</button>
<button onclick="reset()">重置</button>
</div>
<div class="info">
<p>当前步骤:分区操作</p>
<p>比较次数:5</p>
</div>
</div>
7.2 案例2:数据仪表盘
目标:生成销售数据仪表盘
用户输入:
根据这份数据生成销售仪表盘:
Q1: 100万, Q2: 150万, Q3: 120万, Q4: 180万
Agent 响应: 生成一个包含多种图表的仪表盘:
// 生成的仪表盘组件
<div class="dashboard">
<div class="kpi-cards">
<div class="card">总销售额:550万</div>
<div class="card">同比增长:25%</div>
</div>
<div class="charts">
<div class="chart bar-chart">...</div>
<div class="chart trend-line">...</div>
</div>
</div>
7.3 案例3:人机协作流程
目标:实现会议调度
用户输入:
帮我安排明天下午的产品评审会议
Agent 响应: 生成确认卡片,等待用户确认:
// 使用 useHumanInTheLoop
<MeetingCard
proposal={{
title: "产品评审会议",
time: "明天 14:00-15:00",
attendees: ["张三", "李四", "王五"],
location: "3号会议室"
}}
onConfirm={() => bookMeeting()}
onReject={() => cancelMeeting()}
/>
八、最佳实践
8.1 组件设计原则
┌─────────────────────────────────────────────────────────────────────────┐
│ 组件设计原则 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ 1. 单一职责 │
│ 每个组件只做一件事 │
│ │
│ 2. 可组合性 │
│ 小组件组合成大组件 │
│ │
│ 3. 响应式设计 │
│ 适配不同屏幕尺寸 │
│ │
│ 4. 主题兼容 │
│ 支持 Light/Dark 主题 │
│ │
│ 5. 性能优化 │
│ 懒加载、虚拟滚动 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
8.2 Agent 设计原则
┌─────────────────────────────────────────────────────────────────────────┐
│ Agent 设计原则 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ 1. 明确的决策逻辑 │
│ 清晰定义何时返回文本/调用工具/渲染组件 │
│ │
│ 2. 错误处理 │
│ 优雅处理生成失败的情况 │
│ │
│ 3. 状态管理 │
│ 使用 LangGraph 管理对话状态 │
│ │
│ 4. 安全考虑 │
│ 验证生成的 HTML/SVG 内容 │
│ │
│ 5. 用户体验 │
│ 提供加载状态、进度反馈 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
8.3 性能优化建议
| 优化点 | 建议 |
|---|---|
| 懒加载 | 大型组件延迟加载 |
| 缓存 | 缓存常用组件模板 |
| 流式渲染 | 使用流式输出提升体验 |
| 代码分割 | 按需加载 JS 代码 |
| 图片优化 | 压缩图片、使用 WebP |
九、常见问题
9.1 安装问题
Q: make setup 失败?
# 确保 pnpm 已安装
npm install -g pnpm
# 清理后重试
rm -rf node_modules
make setup
Q: Python 依赖安装失败?
# 使用虚拟环境
cd apps/agent
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
9.2 运行问题
Q: Agent 启动失败?
# 检查 API Key 配置
cat apps/agent/.env
# 确保 OPENAI_API_KEY 已配置
Q: 前端无法连接 Agent?
# 检查 Agent 是否运行
curl http://localhost:8123/health
# 检查端口是否被占用
lsof -i :8123
9.3 开发问题
Q: 生成的组件不显示?
// 检查 useComponent 是否正确注册
// 确保在 CopilotKit 组件内部使用
<CopilotKit>
<MyComponent /> {/* useComponent 在这里 */}
</CopilotKit>
Q: 如何调试 Agent?
# 启用详细日志
import logging
logging.basicConfig(level=logging.DEBUG)
十、学习路线图
10.1 入门阶段(第1-2周)
Week 1: 基础认知
├── Day 1-2: 了解生成式 UI 概念
├── Day 3-4: 完成环境搭建
└── Day 5-7: 运行示例,体验功能
Week 2: 核心概念
├── Day 1-2: 学习 CopilotKit 基础
├── Day 3-4: 学习 useComponent Hook
└── Day 5-7: 学习其他 Hooks
10.2 进阶阶段(第3-4周)
Week 3: 自定义开发
├── Day 1-2: 添加自定义组件
├── Day 3-4: 添加 Agent 工具
└── Day 5-7: 实现完整功能
Week 4: 项目实践
├── Day 1-2: 设计项目需求
├── Day 3-4: 开发核心功能
└── Day 5-7: 优化和部署
10.3 能力检查清单
入门能力: - [ ] 理解生成式 UI 概念 - [ ] 成功运行 OpenGenerativeUI - [ ] 理解 CopilotKit 核心 Hooks - [ ] 能使用预置组件
进阶能力: - [ ] 能添加自定义组件 - [ ] 能添加 Agent 工具 - [ ] 能设计人机协作流程 - [ ] 能优化渲染性能
高级能力: - [ ] 能设计复杂 Agent 工作流 - [ ] 能集成多种可视化库 - [ ] 能处理边缘情况 - [ ] 能部署生产环境