CopilotKit 项目解读
项目信息
- 项目名称:CopilotKit
- 项目描述: CopilotKit 是一个全栈 Agent 应用开发 SDK,让开发者能在任何前端框架(React/Angular/Vue/React Native)和任何后端技术栈上,用统一的 AG-UI 协议构建 AI Agent 驱动的应用程序。
- 项目地址:https://github.com/copilotkit/copilotkit
- 官方文档:https://docs.copilotkit.ai/?ref=github_readme
- examples 地址:https://www.copilotkit.ai/examples
解决的核心痛点:
- Agent-UI 通信标准化:在 CopilotKit 之前,每个 AI Agent 框架都需要自定义前端适配层。CopilotKit 通过 AG-UI 协议(被 Google、LangChain、AWS、Microsoft、Mastra、PydanticAI 等采用)提供统一的事件驱动 SSE 通信标准。
- 全栈 Agent 开发碎片化:前端 UI、后端运行时、Agent 框架三者之间的集成复杂度高。CopilotKit 提供三层架构(前端 → 运行时 → Agent),"一次编写 Agent,多端部署"。
- 动态 UI 生成困难:传统的 Agent 应用只能返回文本。CopilotKit 提供 Generative UI(生成式 UI),允许 Agent 在运行时动态生成、更新 UI 组件。
目标用户画像:
- 前端开发者:使用 React/Angular/Vue 构建 AI 驱动的交互界面
- 全栈开发者:需要将 LangGraph/CrewAI/Mastra 等 Agent 框架接入 Web/移动应用
- 企业团队:构建 Human-in-the-Loop 的 Agent 工作流,支持 Slack/Teams 等多平台部署
1. 项目概览
1.1 项目定位与核心价值
一句话定位:CopilotKit 是一个全栈 Agent 应用开发 SDK,让开发者能在任何前端框架(React/Angular/Vue/React Native)和任何后端技术栈上,用统一的 AG-UI 协议构建 AI Agent 驱动的应用程序。
解决的核心痛点:
- Agent-UI 通信标准化:在 CopilotKit 之前,每个 AI Agent 框架都需要自定义前端适配层。CopilotKit 通过 AG-UI 协议(被 Google、LangChain、AWS、Microsoft、Mastra、PydanticAI 等采用)提供统一的事件驱动 SSE 通信标准。
- 全栈 Agent 开发碎片化:前端 UI、后端运行时、Agent 框架三者之间的集成复杂度高。CopilotKit 提供三层架构(前端 → 运行时 → Agent),"一次编写 Agent,多端部署"。
- 动态 UI 生成困难:传统的 Agent 应用只能返回文本。CopilotKit 提供 Generative UI(生成式 UI),允许 Agent 在运行时动态生成、更新 UI 组件。
目标用户画像:
- 前端开发者:使用 React/Angular/Vue 构建 AI 驱动的交互界面
- 全栈开发者:需要将 LangGraph/CrewAI/Mastra 等 Agent 框架接入 Web/移动应用
- 企业团队:构建 Human-in-the-Loop 的 Agent 工作流,支持 Slack/Teams 等多平台部署
1.2 目标场景与典型用例
| 场景 | 描述 | 核心能力 |
|---|---|---|
| Agent 驱动的 SaaS 应用 | 用户通过聊天界面与 AI Agent 交互,Agent 调用后端工具、动态生成 UI 组件 | Generative UI, Tool Calls, Shared State |
| Human-in-the-Loop 工作流 | Agent 在关键决策点暂停,请求用户确认或输入后继续执行 | Interrupt Actions, Tool Confirmation |
| 多 Agent 协作 | 一个应用中注册多个专业 Agent,根据用户意图自动路由 | Multi-Agent, Agent Registry |
| 跨平台 Agent 部署 | 同一个 Agent 逻辑部署到 Web、Mobile、Slack/Teams | AG-UI Protocol, Framework Adapters |
典型使用流程:
1. 初始化: npx copilotkit@latest init
2. 包裹 Provider: <CopilotKit runtimeUrl="..."> <App/> </CopilotKit>
3. 注册工具: useCopilotAction({ name: "search", handler: ... })
4. 配置 Agent: CopilotRuntime + BuiltInAgent({ model: "openai/gpt-4o" })
5. 用户交互: CopilotChat 组件 → Agent 流式响应 → 动态 UI 渲染1.3 技术栈与选型对比
| 层级 | 技术选型 | 说明 |
|---|---|---|
| 前端框架 | React 18/19, Angular, Vue, React Native | 多框架适配,Core 层框架无关 |
| UI 组件 | Tailwind CSS, Radix UI, Lucide React | 可定制的聊天 UI |
| 服务端 | Express, Hono | 双 HTTP 框架适配器 |
| 通信协议 | AG-UI (SSE), GraphQL, WebSocket (Phoenix) | SSE 用于流式,GraphQL 用于查询 |
| Agent 框架 | LangGraph, CrewAI, Mastra, PydanticAI... | 10+ Agent 框架集成 |
| AI SDK | Vercel AI SDK v6, OpenAI, Anthropic, Google | 多 LLM Provider |
| 构建系统 | Nx Monorepo, pnpm, tsdown, Vitest | 增量构建,任务编排 |
| 状态管理 | RxJS Observable, TanStack Pacer (Throttler) | 响应式事件流 |
核心架构决策:
- SSE vs WebSocket:选择 SSE 因为更简单、更易穿透防火墙、天然适配 HTTP/2
- Core 独立于框架:Headless Core + Framework Wrapper 模式,类似 TanStack/Radix
- GraphQL + SSE 混合:GraphQL 用于结构化查询,SSE 用于实时流
- Standard Schema:支持 Zod/Valibot/ArkType 多种 Schema 库
2. 整体架构设计
2.1 架构概述
CopilotKit 采用三层分层架构 + 事件驱动通信模式。从下到上依次为:
- Agent 层:负责 LLM 调用和推理逻辑。支持 BuiltInAgent(基于 Vercel AI SDK)、LangGraph、CrewAI、Mastra 等外部 Agent 框架。
- Runtime 层:服务端中间层,负责 Agent 生命周期管理、线程/会话状态持久化、请求路由、中间件拦截、LLM 适配器。
- Frontend 层:客户端聚合层。Core 包提供框架无关的编排引擎(Agent Registry、Tool Registry、Context Store、State Manager),Framework Wrapper(React/Angular/Vue)提供具体 UI 绑定。
三层之间通过 AG-UI Protocol(基于 SSE 的事件流)和 GraphQL(结构化查询)进行通信。
2.2 整体架构图
+===============================================================================+
| CopilotKit 三层架构 |
+===============================================================================+
+---------------------------------------+ +------------------------------------+
| FRONTEND LAYER | | FRONTEND LAYER |
| +-----------------------------+ | | +-----------------------------+ |
| | react-core / angular | | | | CopilotChat / Popup | |
| | / vue / react-native | | | | (Chat UI Components) | |
| +------------+----------------+ | | +-----------------------------+ |
| | | | |
| v | | +-----------------------------+ |
| +-----------------------------+ | | | useAgent / useCopilot* | |
| | CopilotKitCore | | | | (Public Hook API) | |
| | - AgentRegistry | | | +-----------------------------+ |
| | - ToolRegistry | | | |
| | - ContextStore | | | |
| | - StateManager | | | |
| | - SuggestionEngine | | | |
| | - ThreadStoreRegistry | | | |
| +------------+----------------+ | | |
+---------------|-----------------------+ +------------------------------------+
|
+-----------+-----------+
| AG-UI (SSE) + GraphQL |
+-----------+-----------+
|
+---------------|----------------------------------------------------------+
| v RUNTIME LAYER |
| +-----------------------------+ +-----------------------------+ |
| | Express / Hono Adapter | | GraphQL Yoga Server | |
| +------------+----------------+ +--------------+--------------+ |
| | | |
| v v |
| +-------------------------------------------------------------+ |
| | CopilotRuntime | |
| | - Agent Resolution & Cloning | |
| | - Request Middleware (beforeRequest / afterRequest) | |
| | - AgentRunner (InMemory / SQLite / Custom) | |
| | - LLM Adapters (OpenAI, Anthropic, Google, MCP) | |
| | - Thread & State Management | |
| +------------+------------------------------------------------+ |
+---------------|----------------------------------------------------------+
|
+-----------+-----------+
| Agent Protocol / SDK |
+-----------+-----------+
|
+---------------|----------------------------------------------------------+
| v AGENT LAYER |
| +------------------+ +------------------+ +--------------------------+ |
| | BuiltInAgent | | LangGraph | | CrewAI / Mastra / ... | |
| | (AI SDK v6) | | (Python/JS SDK) | | (Remote / Embedded) | |
| +------------------+ +------------------+ +--------------------------+ |
+---------------------------------------------------------------------------+分层职责说明
| 层 | 核心组件 | 职责 |
|---|---|---|
| Frontend | CopilotKitCore, Framework Wrappers | Agent/Tool/Context 管理,事件分发,UI 渲染 |
| Runtime | CopilotRuntime, AgentRunner, Middleware | Agent 路由、线程管理、LLM 适配、状态持久化 |
| Agent | BuiltInAgent, LangGraph, CrewAI... | LLM 调用、推理逻辑、工具执行 |
2.3 目录结构
CopilotKit/
├── packages/ # 【核心基建】Monorepo 核心包集合(20 packages)
│ ├── shared/ # 【核心基建】公共层:类型定义、常量、调试配置、遥测、Standard Schema 工具
│ ├── core/ # 【核心基建】前端核心:CopilotKitCore 编排引擎
│ │ # (Agent/Tool/Context/State 管理 + RxJS 事件总线)
│ ├── runtime/ # 【核心基建】服务端运行时:CopilotRuntime +
│ │ # BuiltInAgent + GraphQL Server + LLM 适配器
│ ├── react-core/ # 【核心基建】React 公共 API:Provider、Hooks、V2 系统
│ ├── react-ui/ # 【UI 视图】聊天 UI 组件集
│ ├── angular/ # 【业务模块】Angular 适配层
│ ├── vue/ # 【业务模块】Vue 适配层
│ ├── react-native/ # 【业务模块】React Native 适配层
│ ├── react-textarea/ # 【业务模块】AI 文本编辑组件
│ ├── runtime-client-gql/ # 【核心基建】GraphQL 通信客户端(urql-based)
│ ├── sdk-js/ # 【工具集】LangGraph/LangChain Agent 集成 JS SDK
│ ├── voice/ # 【业务模块】语音输入与转录
│ ├── web-inspector/ # 【工具集】开发调试控制台(Lit Web Component)
│ ├── a2ui-renderer/ # 【UI 视图】A2UI 协议渲染器
│ ├── sqlite-runner/ # 【核心基建】SQLite 持久化 AgentRunner 实现
│ ├── agentcore-runner/ # 【核心基建】AgentCore AgentRunner 实现
│ ├── tailwind-config/ # 【配置】Tailwind CSS 共享配置
│ ├── tsconfig/ # 【配置】基础 TypeScript 配置
│ ├── typescript-config/ # 【配置】TypeScript 配置集合
│ └── demo-agents/ # 【⚠️ 待分析】示例 Agent 实现
├── sdk-python/ # 【业务模块】Python SDK(CopilotKit Python 绑定)
├── examples/ # 【⚠️ 待分析】示例与集成项目
├── showcase/ # 【⚠️ 待分析】文档站点
├── skills/ # 【工具集】Claude Code 插件技能(12 skills)
├── scripts/ # 【工具集】构建/发布/QA/Dev 脚本
├── community/ # 【配置】社区内容
├── codemods/ # 【工具集】代码迁移转换
├── dev-docs/ # 【配置】内部架构文档
├── docs/ # 【废弃】旧文档(已迁移)
├── .github/ # 【配置】CI/CD 工作流
├── .changeset/ # 【配置】变更集管理
├── .claude/ # 【配置】Claude Code 项目配置
├── .claude-plugin/ # 【配置】Claude Code 插件元数据
├── .cursor/ # 【配置】Cursor IDE 规则
├── assets/ # 【配置】README 静态资源
├── README.md # 【配置】项目说明
├── CLAUDE.md # 【配置】Claude Code 项目指令
├── AGENTS.md # 【配置】AI Agent 项目指令
└── LICENSE # 【配置】MIT 许可证3. 模块依赖与调用关系
3.1 全局入口与核心路由
逻辑说明:前端应用通过 <CopilotKit> 组件初始化,内部创建 CopilotKitCore 实例。Core 通过 HTTP 获取 Runtime 可用 Agent 列表,为每个远程 Agent 创建 ProxiedCopilotRuntimeAgent 实例。用户发送消息时,Core 调用 runAgent() → HTTP POST 到 Runtime → Runtime 解析 Agent → AgentRunner 执行 → SSE 流式返回 AG-UI 事件。
调用拓扑 (plainText):
CopilotKit (React Provider)
|
+---> CopilotKitCore (core.ts)
|
+---> AgentRegistry (agent-registry.ts)
| |
| +---> fetchAgentInfo() ────> GET /api/copilotkit/info
| |
| +---> createProxiedAgent() ────> ProxiedCopilotRuntimeAgent
| |
| +---> connectAgent() ────> POST runtimeUrl (GraphQL)
| +---> runAgent() ────> POST runtimeUrl (HTTP/SSE)
|
+---> ContextStore (context-store.ts)
| +---> setContext()
| +---> getContext()
|
+---> RunHandler (run-handler.ts)
| +---> runAgent() ────> ProxiedAgent.run()
| +---> runTool() ────> FrontendTool.execute() [local]
|
+---> StateManager (state-manager.ts)
| +---> mergeState()
| +---> subscribeToState()
|
+---> SuggestionEngine (suggestion-engine.ts)
| +---> generateSuggestions()
|
+---> ThreadStoreRegistry (thread-store-registry.ts)
+---> getThreadStore() ────> ɵThreadStore
Runtime Server (copilot-runtime.ts)
|
+---> ExpressAdapter / HonoAdapter
|
+---> CopilotRuntime
|
+---> AgentResolver ────> resolveAgent(agentId)
| |
| +---> BuiltInAgent (local LLM, AI SDK)
| +---> LangGraphAgent (remote LangGraph Server)
| +---> RemoteAgent (CrewAI, Mastra, etc.)
|
+---> AgentRunner (InMemory / SQLite)
| +---> threadStore.get() / threadStore.set()
| +---> runAgent() → SSE stream
|
+---> Middleware Pipeline
| +---> beforeRequestMiddleware
| +---> afterRequestMiddleware
|
+---> LLM Adapters
+---> OpenAI SDK
+---> Anthropic SDK
+---> Google AI SDK
+---> MCP Clients3.2 核心业务实体与关联
实体定义:
- Agent:AI Agent 抽象,可以执行对话、调用工具、生成 UI
- Thread/ThreadStore:会话线程,存储消息历史和 Agent 状态
- Tool:工具定义(前端工具在浏览器执行,后端工具在服务端执行)
- Context:应用上下文数据,随每次 Agent 运行发送
- State:Agent 状态,前端和 Runtime 之间实时同步
- Message:对话消息(UserMessage, AssistantMessage, ToolMessage, SystemMessage)
- Suggestion:AI 生成的建议/提示
- Run:一次 Agent 执行过程(RunStarted → Steps → RunFinished)
实体引用拓扑:
[CopilotKitCore] 1 -----> N [Agent]
|
+-- 1 -----> N [ThreadStore] (per threadId)
| |
| +-- 1 -----> N [Message]
|
+-- 1 -----> N [Tool]
| |
| +-- FrontendTool:
| | handler runs in browser
| |
| +-- BackendTool:
| handler runs on server
|
+-- 1 -----> N [Context] (per category)
|
+-- 1 <-----> 1 [State]
|
+-- 1 -----> N [Run] (per execution)
[Runtime: CopilotRuntime] 1 -----> N [AgentRunner]
|
+-- InMemoryAgentRunner
+-- SQLiteAgentRunner
+-- CustomAgentRunner
[Agent] 1 -----> N [Provider] (LLM provider: OpenAI, Anthropic, Google)
[Agent] 1 -----> N [MCPClient] (MCP server connections)4. 核心模块详解
模块一:CopilotKitCore(前端编排引擎)
模块名称:@copilotkit/core — CopilotKitCore 设计说明:框架无关的前端编排引擎,是整个系统的"大脑"。采用注册表模式管理 Agent、Tool、Context,通过 RxJS Observable 处理异步事件流。使用 Throttler(TanStack Pacer)控制状态更新频率,避免高频渲染。ThreadStoreRegistry 支持多线程隔离,每个线程独立的 Agent 和 State。 内部结构图:
+------------------------------------------------------------------+
| CopilotKitCore |
| |
| +------------------+ +------------------+ +-----------+ |
| | AgentRegistry | | ContextStore | |RunHandler | |
| | | | | | | |
| | - agents: Map | | - context: Map | | - runAgent| |
| | - register() | | - set() | | - runTool | |
| | - unregister() | | - get() | | - connect | |
| | - fetchInfo() | | - remove() | | - abort | |
| +--------+---------+ +--------+---------+ +-----+-----+ |
| | | | |
| v v v |
| +----------------------------------------------------------------+|
| | Event Bus (RxJS Observable) ||
| | - agentChanges$ - contextChanges$ ||
| | - toolExecution$ - suggestionChanges$ ||
| | - stateChanges$ - errorEvents$ ||
| +----------------------------------------------------------------+|
| | | | |
| v v v |
| +------------------+ +------------------+ +-----------+ |
| | StateManager | |SuggestionEngine | |ThreadStore| |
| | | | | | Registry | |
| | - mergeState() | | - getSuggestions | | | |
| | - getState() | | (agentId) | | - get() | |
| | - subscribe() | | - isLoading | | - create()| |
| +------------------+ +------------------+ +-----------+ |
+------------------------------------------------------------------+模块二:CopilotRuntime(服务端运行时)
- 模块名称:
@copilotkit/runtime— CopilotRuntime - 设计说明:服务端核心运行时,采用适配器模式支持 Express 和 Hono 两种 HTTP 框架。使用策略模式处理不同的 Agent 类型(BuiltInAgent、LangGraphAgent、RemoteAgent)。通过 AgentRunner 抽象(模板方法模式)管理线程状态,支持内存和 SQLite 两种持久化策略。内置 GraphQL Yoga 服务端处理结构化查询。
- 内部结构图 (plainText):
+------------------------------------------------------------------+
| CopilotRuntime |
| |
| +------------------+ +------------------+ +-----------+ |
| | HTTP Adapters | | GraphQL Server | | WebSocket | |
| | | | | | (Phoenix)| |
| | - ExpressAdapter | | - GraphQL Yoga | | | |
| | - HonoAdapter | | - TypeGraphQL | | - Channel | |
| | - createRouter() | | - Resolvers | | - PubSub | |
| +--------+---------+ +--------+---------+ +-----+-----+ |
| | | | |
| v v v |
| +----------------------------------------------------------------+|
| | Middleware Pipeline ||
| | beforeRequest → Agent Resolution → afterRequest ||
| +----------------------------------------------------------------+|
| | |
| v |
| +------------------+ +------------------+ +-----------+ |
| | Agent Runner | | Agent Factory | | LLM | |
| | | | | | Adapters | |
| | - InMemory | | - BuiltInAgent | | - OpenAI | |
| | - SQLite | | - LangGraph | | - Anthropic |
| | - Custom | | - CrewAI | | - Google | |
| | - threadStore | | - Mastra | | - MCP | |
| +------------------+ +------------------+ +-----------+ |
+------------------------------------------------------------------+模块三:BuiltInAgent(内置 AI Agent)
- 模块名称:
@copilotkit/runtime— BuiltInAgent - 设计说明:CopilotKit 内置的默认 Agent 实现,基于 Vercel AI SDK v6 的
streamText函数。支持 OpenAI、Anthropic、Google 三大 LLM Provider,通过model参数自动选择。支持 MCP (Model Context Protocol) 客户端连接外部工具服务器。工具参数使用 Standard Schema(Zod、Valibot、ArkType 兼容),在序列化到 LLM 前转换为 JSON Schema。 - 内部结构图 (plainText):
+------------------------------------------------------------------+
| BuiltInAgent |
| |
| +------------------+ +------------------+ +-----------+ |
| | Model Resolver | | Tool Converter | | MCP | |
| | | | | | Manager | |
| | "openai/gpt-4o" | | StandardSchema | | | |
| | → createOpenAI | | → JSON Schema | | - HTTP | |
| | "anthropic/..." | | → ai.tool() | | - SSE | |
| | → createAnthro | | zod/valibot/ark | | - Stream | |
| +--------+---------+ +--------+---------+ +-----+-----+ |
| | | | |
| v v v |
| +----------------------------------------------------------------+|
| | AI SDK Core (streamText) ||
| | - LanguageModel - ToolSet - SystemPrompt - Messages ||
| | - maxTokens - temperature - toolChoice - stopSequences ||
| +----------------------------------------------------------------+|
| | |
| v |
| +---------------------------+ +---------------------------+ |
| | Stream Converter | | Event Emitter | |
| | - convertAISDKStream() | | - RunStarted | |
| | - convertTanStackStream | | - TextMessageChunk | |
| | - tool-call tracking | | - ToolCallStart/End | |
| +---------------------------+ | - StateSnapshot/Delta | |
+---------------------------+ |
+------------------------------------------------------------------+模块四:AG-UI 协议层
- 模块名称:AG-UI Protocol(
@ag-ui/core,@ag-ui/client,@ag-ui/encoder) - 设计说明:Agent-User Interaction Protocol 是 CopilotKit 的核心创新,定义了 Agent 与 UI 之间的标准化事件通信协议。所有 Agent 输出通过预定义的事件类型(Zod 校验)流式传递给前端。事件按生命周期组织:Run → Step → Message/Tool → State。Encoder 负责事件序列化。
- 内部结构图 (plainText):
+------------------------------------------------------------------+
| AG-UI Protocol Stack |
| |
| +----------------------------------------------------------------+|
| | EventType (Enum) ||
| | RUN_STARTED STEP_STARTED TEXT_MESSAGE_CHUNK ||
| | TOOL_CALL_START TOOL_CALL_ARGS TOOL_CALL_END ||
| | STATE_SNAPSHOT STATE_DELTA MESSAGES_SNAPSHOT ||
| | STEP_FINISHED RUN_FINISHED RUN_ERROR ||
| | CUSTOM_EVENT ACTIVITY_SNAPSHOT ACTIVITY_DELTA ||
| +----------------------------------------------------------------+|
| |
| +------------------+ +------------------+ +-----------+ |
| | @ag-ui/core | | @ag-ui/client | |@ag-ui/ | |
| | | | | | encoder | |
| | - EventType enum | | - AbstractAgent | | | |
| | - Zod schemas | | - HttpAgent | | - encode()| |
| | - Type defs | | - AgentSubscriber| | - decode()| |
| +------------------+ +------------------+ +-----------+ |
+------------------------------------------------------------------+模块五:前端框架适配层(React Core)
- 模块名称:
@copilotkit/react-core— React Provider & Hooks - 设计说明:React 框架适配层,提供
<CopilotKit>Provider 组件和useAgent、useCopilotAction等 Hook API。采用Context + Provider模式管理全局状态,通过 V2 Provider(CopilotKitProvider)处理线程、消息、工具注册。内部使用 Lit Web Component Bridge 集成 Web Inspector 调试工具。 - 内部结构图 (plainText):
+------------------------------------------------------------------+
| @copilotkit/react-core |
| |
| +----------------------------------------------------------------+|
| | <CopilotKit> Provider ||
| | - runtimeUrl - publicApiKey - threadId ||
| | - headers - credentials - debug ||
| | - showDevConsole - enableInspector - onError ||
| +----------------------------------------------------------------+|
| | |
| v |
| +------------------+ +------------------+ +-----------+ |
| | CopilotKitV2 | | CopilotContext | | Threads | |
| | Provider | | | | Provider | |
| | | | - agent sessions | | | |
| | - CopilotKitCore | | - chat components| | - threadId| |
| | - ThreadRegistry | | - auth state | | - switch | |
| +--------+---------+ +--------+---------+ +-----+-----+ |
| | | | |
| v v v |
| +----------------------------------------------------------------+|
| | Public Hook API ||
| | useAgent() useCopilotAction() useCopilotChat() ||
| | useCopilotReadable() useCopilotChatSuggestions() ||
| | useLangGraphInterrupt() useCoAgent() useCopilotKit() ||
| +----------------------------------------------------------------+|
+------------------------------------------------------------------+5. 关键数据流程
场景一:用户发送消息到 Agent 响应
最核心的流程,用户通过 CopilotChat 发送消息 → Core 创建 RunAgentInput → HTTP POST 到 Runtime → Agent 执行 LLM 调用 → SSE 流式返回事件 → 前端逐步渲染。
流转时序图 (Mermaid):
场景二:Human-in-the-Loop 中断流程
Agent 执行过程中暂停,等待用户确认或输入,然后继续执行。
流转时序图 (Mermaid):
6. 接口与契约规范
6.1 核心内部模块契约 (TypeScript)
/**
* CopilotKitCore 核心配置与运行契约
*/
/** Agent 注册参数 */
export interface CopilotKitCoreAddAgentParams {
agentId: string;
agent: AbstractAgent;
}
/** Agent 运行参数 */
export interface CopilotKitCoreRunAgentParams {
agent: AbstractAgent;
messages: Message[];
context?: Record<string, Context>;
state?: State;
threadId?: string;
runId?: string;
}
/** 工具执行参数 */
export interface CopilotKitCoreRunToolParams {
agentId: string;
toolCallId: string;
toolName: string;
args: unknown;
}
/** 工具执行结果 */
export interface CopilotKitCoreRunToolResult {
result: string;
error?: string;
}
/**
* Agent 生命周期订阅器
*/
export interface CopilotKitCoreSubscriber {
onRuntimeConnectionStatusChanged?: (event: {
copilotkit: CopilotKitCore;
status: CopilotKitCoreRuntimeConnectionStatus;
}) => void | Promise<void>;
onToolExecutionStart?: (event: {
copilotkit: CopilotKitCore;
toolCallId: string;
agentId: string;
toolName: string;
args: unknown;
}) => void | Promise<void>;
onToolExecutionEnd?: (event: {
copilotkit: CopilotKitCore;
toolCallId: string;
agentId: string;
toolName: string;
result: string;
error?: string;
}) => void | Promise<void>;
onAgentsChanged?: (event: {
copilotkit: CopilotKitCore;
agents: Readonly<Record<string, AbstractAgent>>;
}) => void | Promise<void>;
onContextChanged?: (event: {
copilotkit: CopilotKitCore;
context: Readonly<Record<string, Context>>;
}) => void | Promise<void>;
}
/**
* Runtime Agent 执行器
*/
export interface AgentRunner {
/** 执行 Agent 并返回 AG-UI 事件流 */
run(agent: AbstractAgent, input: RunAgentInput): Observable<BaseEvent>;
/** 获取线程状态 */
getThread(threadId: string): Promise<ThreadState | null>;
/** 保存线程状态 */
saveThread(threadId: string, state: ThreadState): Promise<void>;
}
/**
* BuiltInAgent 配置
*/
export interface BuiltInAgentConfig {
model: ModelSpecifier;
systemPrompt?: string;
tools?: ToolSet;
mcpServers?: MCPClientConfig[];
temperature?: number;
maxOutputTokens?: number;
toolChoice?: ToolChoice;
}6.2 对外 API 契约 (OpenSpec 格式)
# CopilotKit Runtime HTTP API
paths:
/copilotkit:
post:
summary: 执行 Agent 运行
description: |
发送 RunAgentInput 到 Runtime,Agent 处理后通过 SSE 流式返回 AG-UI 事件。
请求体包含消息历史、注册的工具、上下文、线程 ID 和状态。
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [agentId, messages, threadId]
properties:
agentId:
type: string
description: 目标 Agent 标识符
messages:
type: array
description: 对话消息历史
items:
$ref: '#/components/schemas/Message'
tools:
type: array
description: 注册的工具列表
items:
$ref: '#/components/schemas/Tool'
context:
type: array
description: 应用上下文
items:
$ref: '#/components/schemas/Context'
threadId:
type: string
description: 线程/会话 ID
state:
type: object
description: Agent 状态
runId:
type: string
description: 运行 ID
forwardedProps:
type: object
description: 转发属性
responses:
'200':
description: SSE 事件流
content:
text/event-stream:
schema:
type: string
description: AG-UI 事件流(SSE 格式)
'400':
description: 请求参数错误
'500':
description: Agent 执行错误
/copilotkit/info:
get:
summary: 获取 Runtime 信息
description: 返回可用 Agent 列表和 Runtime 元数据
responses:
'200':
description: Runtime 信息
content:
application/json:
schema:
type: object
properties:
agents:
type: array
items:
type: object
properties:
name:
type: string
description:
type: string
version:
type: string
components:
schemas:
Message:
type: object
properties:
id:
type: string
role:
type: string
enum: [user, assistant, system, tool]
content:
type: string
toolCalls:
type: array
items:
$ref: '#/components/schemas/ToolCall'包依赖关系图 (Package Dependency Graph)
@copilotkit/shared ←─────── (基础依赖,所有包依赖它)
^
|
+──── @copilotkit/core ←──── @copilotkit/react-core
| |
| +──── @copilotkit/react-ui
| +──── @copilotkit/angular
| +──── @copilotkit/vue
|
+──── @copilotkit/runtime
| |
| +──── @ag-ui/core (AG-UI 协议核心)
| +──── @ag-ui/client (AG-UI 客户端)
| +──── @ag-ui/encoder (AG-UI 编码器)
| +──── ai (Vercel AI SDK v6)
|
+──── @copilotkit/runtime-client-gql (GraphQL 客户端)
|
+──── @copilotkit/sdk-js (LangGraph/LangChain 集成)
|
+──── @copilotkit/sqlite-runner ←── @copilotkit/runtime
+──── @copilotkit/agentcore-runner ←── @copilotkit/runtime7. 快速开始
7.1 环境要求
- Node.js >= 18
- pnpm >= 8
- 一个 LLM Provider 的 API Key(OpenAI、Anthropic、或 Google)
7.2 安装与运行
# 新项目初始化
npx copilotkit@latest create -f react
# 现有项目添加
npx copilotkit@latest init
# 从源码构建
pnpm install
nx run-many --target=build --all7.3 典型用例
// 1. 包裹 Provider
import { CopilotKit } from "@copilotkit/react-core";
<CopilotKit runtimeUrl="/api/copilotkit">
<YourApp />
</CopilotKit>
// 2. 使用 Chat 组件
import { CopilotChat } from "@copilotkit/react-ui";
<CopilotChat
labels={{ title: "AI 助手", placeholder: "输入您的问题..." }}
/>
// 3. 配置 Runtime Agent
import { CopilotRuntime, BuiltInAgent } from "@copilotkit/runtime";
const runtime = new CopilotRuntime({
agents: {
default: new BuiltInAgent({
model: "openai/gpt-4o",
systemPrompt: "你是一个有用的助手",
}),
},
});7.4 一个完整的 AG-UI SSE 相应示例
每条 SSE 消息 = 一个 AG-UI 事件,遵循 SSE 规范 event: <type>\ndata: <json>\n\n :
| 类别 | 事件 | 说明 |
|---|---|---|
| Lifecycle | RUN_STARTED / RUN_FINISHED / RUN_ERROR | Run 的边界,必须配对 |
| STEP_STARTED / STEP_FINISHED | 可选的子任务边界,可成对出现多次 | |
| Text Message | TEXT_MESSAGE_START → _CONTENT (×N) → _END | 流式文字,delta 串起来才是完整文本 |
| TEXT_MESSAGE_CHUNK | 上面的简写版,client 自动展开为三段 | |
| Tool Call | TOOL_CALL_START → _ARGS (×N) → _END | 工具调用的参数也是流式的(JSON 片段) |
| TOOL_CALL_RESULT | 工具执行结果(一次性完整返回) | |
| State | STATE_SNAPSHOT | 完整状态快照(首次或重置时) |
| STATE_DELTA | JSON Patch 增量更新(RFC 6902) | |
| MESSAGES_SNAPSHOT | 完整消息历史快照 |
关键设计
- 生命周期嵌套 : Run → Step → Message/Tool ,外层未结束时内层不会发生新的 RUN_* 。
- id 关联 : messageId 把 START/CONTENT/END 串成一条消息; toolCallId 把工具调用三段串起来。
- delta 流式 : TEXT_MESSAGE_CONTENT.delta 和 TOOL_CALL_ARGS.delta 是增量片段,客户端必须按序拼接。
- Zod 校验 :所有事件通过 @ag-ui/core 的 Zod schema 校验,runtime 端会在 emit 前、client 端会在 dispatch 前各校验一次。
- SSE 友好 :每个事件一行 event: + data: ,天然适合 Server → Client 的流式推送。
用户问了一个问题 → Agent 思考 → 流式输出文字 → 调用工具 → 返回工具结果 → 继续输出 → Run 结束:
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache, no-transform
Connection: keep-alive
X-Accel-Buffering: no
# SSE 事件流(每个 event: + data: 一条 AG-UI 事件)
event: RUN_STARTED
data: {"type":"RUN_STARTED","threadId":"thr_abc123","runId":"run_xyz789","timestamp":1717823400000}
event: STEP_STARTED
data: {"type":"STEP_STARTED","stepName":"plan","runId":"run_xyz789"}
event: STEP_FINISHED
data: {"type":"STEP_FINISHED","stepName":"plan","runId":"run_xyz789"}
event: STEP_STARTED
data: {"type":"STEP_STARTED","stepName":"respond","runId":"run_xyz789"}
event: TEXT_MESSAGE_START
data: {"type":"TEXT_MESSAGE_START","messageId":"msg_001","role":"assistant"}
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_001","delta":"Let me "}
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_001","delta":"check the "}
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_001","delta":"weather for you."}
event: TEXT_MESSAGE_END
data: {"type":"TEXT_MESSAGE_END","messageId":"msg_001"}
event: TOOL_CALL_START
data: {"type":"TOOL_CALL_START","toolCallId":"tc_001","toolCallName":"get_weather","parentMessageId":"msg_001"}
event: TOOL_CALL_ARGS
data: {"type":"TOOL_CALL_ARGS","toolCallId":"tc_001","delta":"{\"city\":\""}
event: TOOL_CALL_ARGS
data: {"type":"TOOL_CALL_ARGS","toolCallId":"tc_001","delta":"Beijing\"}"}
event: TOOL_CALL_END
data: {"type":"TOOL_CALL_END","toolCallId":"tc_001"}
event: TOOL_CALL_RESULT
data: {"type":"TOOL_CALL_RESULT","messageId":"msg_002","toolCallId":"tc_001","content":"{\"temp_c\":22,\"condition\":\"sunny\"}","role":"tool"}
event: TEXT_MESSAGE_START
data: {"type":"TEXT_MESSAGE_START","messageId":"msg_003","role":"assistant"}
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_003","delta":"Beijing is "}
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","messageId":"msg_003","delta":"sunny, 22°C."}
event: TEXT_MESSAGE_END
data: {"type":"TEXT_MESSAGE_END","messageId":"msg_003"}
event: STATE_SNAPSHOT
data: {"type":"STATE_SNAPSHOT","snapshot":{"todos":[],"lastTool":"get_weather"}}
event: STEP_FINISHED
data: {"type":"STEP_FINISHED","stepName":"respond","runId":"run_xyz789"}
event: RUN_FINISHED
data: {"type":"RUN_FINISHED","threadId":"thr_abc123","runId":"run_xyz789"}
# 错误分支示例
event: RUN_STARTED
data: {"type":"RUN_STARTED","threadId":"thr_abc123","runId":"run_err_01"}
event: RUN_ERROR
data: {"type":"RUN_ERROR","message":"Rate limit exceeded","code":"RATE_LIMIT"}