CopilotKit简介
CopilotKit是2026年最流行的开源AI助手集成框架,GitHub星标超过15k。只需10行代码即可在React/Next.js应用中嵌入完整的AI聊天、文档处理、数据分析功能。对比从零开发AI功能,CopilotKit节省80%开发时间。
一、安装
npm install @copilotkit/react-core @copilotkit/react-ui
# 如果使用Next.js
npm install @copilotkit/nextjs
二、5步集成AI助手
第1步:配置Provider
// app/layout.tsx
import { CopilotKit } from "@copilotkit/react-core";
export default function RootLayout({ children }) {
return (
{children}
);
}
第2步:添加聊天UI
// app/page.tsx
import { CopilotPopup } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";
export default function Home() {
return (
我的应用
);
}
第3步:定义AI可执行的操作
useCopilotAction({
name: "searchProducts",
description: "搜索商品",
parameters: [{ name: "query", type: "string" }],
handler: async ({ query }) => {
const results = await fetch(`/api/search?q=${query}`);
return results.json();
}
});
第4步:共享应用上下文
useCopilotReadable({
description: "当前页面商品列表",
value: products
});
第5步:添加AI聊天建议
useCopilotChatSuggestions([
"帮我搜索红色连衣裙",
"对比这两个商品的价格"
]);
三、进阶功能
- 自定义UI:支持Popup、Sidebar、Textarea三种模式
- 多模型支持:OpenAI/Anthropic/DeepSeek/Ollama均可接入
- RAG集成:上传文档让AI基于私有数据回答
- Agent模式:支持多步骤任务自动执行
四、部署注意事项
生产环境建议使用后端API代理,不要在前端暴露API Key。也可配合 Dify 或 n8n工作流 构建更复杂的AI应用。