CopilotKit实战:用生成式UI打造智能Agent前端

前言

AI Agent的热度持续飙升,但很多开发者在构建Agent应用时都遇到了同一个难题:如何设计一个既灵活又用户友好的前端界面?

传统的聊天UI已经无法满足需求------我们需要的是一种能根据任务动态生成UI组件的能力。比如:当用户问"帮我分析这份销售数据"时,Agent不仅要给出文字回复,还要能实时生成数据可视化图表、交互式表格,甚至是一个可操作的控制面板。

这就是 生成式UI(Generative UI) 的核心价值。而今天我们要深入研究的 CopilotKit,正是目前GitHub上最火的生成式UI框架,今天更是冲上了GitHub趋势榜第一名。

什么是CopilotKit?

CopilotKit 是一个开源的 前端Agent开发框架,官方定位为:

"The Frontend Stack for Agents & Generative UI"

简单来说,它为你提供了构建AI Agent应用所需的所有前端基础设施,包括:

• 🤖 Agent运行时:管理AI对话状态、工具调用、上下文记忆

• 🎨 生成式UI组件:根据Agent回复动态渲染交互组件

• 🔄 实时流式传输:支持打字机效果、流式输出

• 🔌 多平台支持:React、Angular、Next.js、移动端、Slack等

核心特性一览

特性 说明

AG-UI Protocol 开源的Agent UI通信协议,支持跨框架互操作

Generative UI 根据AI输出动态生成React组件

Tool Calling 内置工具调用框架,支持函数定义、参数验证

Streaming 完整的流式传输支持,包括文字和UI组件

Multi-model 支持OpenAI、Anthropic、Google等主流LLM

环境准备

在开始之前,请确保你的开发环境满足以下条件:

系统要求

Node.js >= 18.0.0

npm >= 9.0.0 或 yarn >= 1.22.0

安装方式

方式一:通过Create Next App快速创建

bash 复制代码
npx create-next-app@latest my-copilot-app --typescript
cd my-copilot-app
npm install copilotkit @copilotkit/react-core @copilotkit/react-ui

方式二:手动添加到现有项目

bash 复制代码
# 核心包
npm install @copilotkit/react-core @copilotkit/react-ui

可选:Agent运行时(如果使用自定义后端)

bash 复制代码
npm install @copilotkit/runtime

项目结构建议

my-copilot-app/

├── app/

│ ├── page.tsx # 主页面

│ └── layout.tsx # 布局文件

├── components/

│ └── CopilotChat.tsx # 自定义聊天组件

├── lib/

│ └── copilot.ts # CopilotKit配置

└── package.json

实战:从零构建AI Agent聊天应用

第一步:初始化CopilotKit

在 lib/copilot.ts 中配置CopilotKit:

TypeScript 复制代码
// lib/copilot.ts
import { CopilotKit } from "@copilotkit/react-core";

export function CopilotProvider({ children }: { children: React.ReactNode }) {
  return (
    <CopilotKit
      // 使用OpenAI作为默认模型
      runtimeURL="https://runtime.copilotkit.ai"
      defaultModel="gpt-4o"
      // 可选:自定义API密钥(生产环境建议使用环境变量)
      // apiKey={process.env.OPENAI_API_KEY}
    >
      {children}
    </CopilotKit>
  );
}

第二步:定义Agent工具

工具是Agent能力的核心。让我们定义一个天气查询工具:

TypeScript 复制代码
// lib/tools.ts
import { tool } from "@copilotkit/react-core";
import { z } from "zod";

export const weatherTools = [
  tool({
    name: "get_weather",
    description: "查询指定城市的天气信息",
    parameters: z.object({
      city: z.string().describe("城市名称,如'北京'、'Shanghai'"),
      unit: z.enum(["celsius", "fahrenheit"]).default("celsius"),
    }),
    execute: async ({ city, unit }) => {
      // 实际应用中调用天气API
      // 这里用模拟数据演示
      const mockWeather = {
        city,
        temperature: unit === "celsius" ? 25 : 77,
        condition: "晴朗",
        humidity: "65%",
        wind: "东北风 3级",
      };
      return mockWeather;
    },
  }),
  tool({
    name: "search_web",
    description: "搜索互联网获取最新信息",
    parameters: z.object({
      query: z.string().describe("搜索关键词"),
    }),
    execute: async ({ query }) => {
      // 实际调用搜索API
      return { results: [`关于"${query}"的搜索结果...`] };
    },
  }),
];

第三步:创建生成式UI组件

这是CopilotKit的杀手级功能------根据AI回复动态生成UI:

TypeScript 复制代码
// components/WeatherCard.tsx
import { CopilotKit } from "@copilotkit/react-core";

interface WeatherData {
  city: string;
  temperature: number;
  condition: string;
  humidity: string;
  wind: string;
}

export function WeatherCard({ data }: { data: WeatherData }) {
  return (
    <div className="weather-card">
      <h3>🌤️ {data.city} 天气</h3>
      <div className="temp">{data.temperature}°{data.temperature === 25 ? 'C' : 'F'}</div>
      <p>{data.condition}</p >
      <div className="details">
        <span>湿度: {data.humidity}</span>
        <span>风向: {data.wind}</span>
      </div>
    </div>
  );
}

// 注册为生成式UI组件
CopilotKit.registerComponent({
  name: "weather-card",
  component: WeatherCard,
  schema: {
    city: { type: "string" },
    temperature: { type: "number" },
    condition: { type: "string" },
    humidity: { type: "string" },
    wind: { type: "string" },
  },
});

第四步:组装聊天界面

TypeScript 复制代码
// app/page.tsx
"use client";

import { CopilotKit } from "@copilotKit/react-core";
import { CopilotPopup } from "@copilotKit/react-ui";
import { weatherTools } from "@/lib/tools";
import { WeatherCard } from "@/components/WeatherCard";

export default function Home() {
  return (
    <main className="home-container">
      <h1>🚀 AI Agent 助手</h1>
      <p>点击右下角按钮开始对话</p >
      
      <CopilotKit
        tools={weatherTools}
        // 自定义UI组件映射
        components={{
          "weather-card": WeatherCard,
        }}
      >
        <CopilotPopup
          defaultOpen={false}
          labels={{
            title: "智能助手",
            placeholder: "问我任何问题...",
          }}
        />
      </CopilotKit>
    </main>
  );
}

第五步:运行项目

npm run dev

访问 http://localhost:3000,点击右下角的聊天按钮,开始与你的AI Agent对话!

使用指南:进阶技巧

  1. 自定义Agent行为

<CopilotKit

instructions={`

你是一个专业的数据分析助手。

当用户询问数据时,优先使用数据可视化工具。

保持回答简洁明了,多用表格和图表。

`}

model="xxx"

/>

  1. 流式UI更新

// 在工具执行中返回流式更新

execute: async function* ({ query }) {

yield { status: "loading", message: "正在搜索..." };

// 模拟耗时操作

await new Promise(r => setTimeout(r, 1000));

yield { status: "partial", results: "结果1", "结果2" };

await new Promise(r => setTimeout(r, 500));

yield { status: "complete", results: "结果1", "结果2", "结果3" };

}

对比:CopilotKit vs 其他方案

特性 CopilotKit Vercel AI SDK LangChain UI

生成式UI ✅ 原生支持 ⚠️ 需手动实现 ❌ 不支持

AG-UI协议 ✅ 开源标准 ❌ ❌

框架支持 React/Angular/Next React/Next React

学习曲线 中等 较低 较高

社区规模 33,203⭐ 45,000+⭐ 88,000+⭐

文档质量 ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ⭐⭐⭐

关键要点总结

  1. CopilotKit 是构建AI Agent前端的首选框架,尤其适合需要动态UI的场景

  2. 生成式UI是其核心竞争力,让Agent能根据任务实时渲染交互组件

  3. AG-UI协议是开源标准,未来可能成为Agent UI的通用协议

  4. 工具定义使用Zod,类型安全且易于验证

  5. 支持流式更新,用户体验更接近原生应用

结语

CopilotKit 的出现,标志着AI Agent开发从"能对话"向"能交互"的重要转变。随着生成式UI的普及,未来的AI应用将不再是简单的聊天窗口,而是能够根据任务需求动态生成复杂界面的智能助手。

相关推荐
郭老二1 小时前
【经验】CSDN-AI数字营销试用测评3
人工智能
程序员老油条1 小时前
用 AI 生成复杂 SQL:LangChain4j + 本地模型实践
数据库·人工智能·sql
zhangfeng11331 小时前
想做自媒体数字人访谈视频,在百度 AI Studio 上安装 OpenAvatarChat,显存要求
人工智能·音视频·transformer·自媒体
烟雨江南7851 小时前
水泥回转窑烧成车间大功率冷却风机强粉尘低频共振噪底:基于“灵声智库”端侧自适应谱减降噪与信创工控芯片离线 ASR 安全控制系统
人工智能·安全·webrtc·语音识别·ai质检
DogDaoDao1 小时前
【第 04 篇】列表与元组 —— 序列类型核心详解
人工智能·python·深度学习·神经网络·机器学习·conda·numpy
米核AI易山1 小时前
扣子工作流错误处理:用条件分支打造不崩的自动化流水线
人工智能·深度学习·自动化·coze·扣子工作流·米核ai易山
继续商行1 小时前
Go/Rust 系统编程与并发原语深度剖析
人工智能
码语智行1 小时前
Codex 新手安装教程(完全小白版)
java·人工智能
平原20181 小时前
2026 主流 AI 视频 API 渠道价格对比:Seedance 2.0 哪家最便宜
大数据·人工智能