> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# 用CopilotKit 为智能体添加 UI
- URL: https://www.hubwiz.com/blog/add-ui-to-agents-using-copilotkit/
- Published: 2026-04-23T03:12:15.000Z
- Updated: 2026-10-13T16:14:13.000Z
- Description: 智能体框架在推理、编排和工具执行方面变得越来越强大。但大多数框架仍然作为孤立系统运行。
- Author: admin
- Tags: AGENT, COPILOTKIT, #Import 2026-10-14 14:41

[AG2（前身为 AutoGen）](https://github.com/ag2ai/ag2?ref=hubwiz.com)改变了这一点。它提供了一个共享运行时，具有定义角色、工具和对话模式的专业智能体可以在其中作为一个协调团队跨模型甚至跨框架协作。

但仅有编排并不等同于交付交互式体验。每个应用最终都需要构建自定义协议和 UI 连接来观察运行、显示工具进度并在执行期间捕获用户操作。

[AG-UI（Agent-User Interaction Protocol）](https://github.com/ag-ui-protocol/ag-ui?ref=hubwiz.com)定义了这个交互契约。它标准化了智能体活动的流式传输方式，使任何前端都能实时保持同步。

如今，AG2 与 AG-UI 和 CopilotKit 集成，将智能体编排带入实际应用。

![AG2 与 AG-UI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1jr4ocefy35i6j8fbdqg.png)

你可以参考[文档](https://docs.copilotkit.ai/ag2/quickstart?ref=hubwiz.com)并尝试交互式 [AG-UI Dojo](https://dojo.ag-ui.com/ag2/feature/agentic%5Fchat?ref=hubwiz.com) 来自行探索。

让我们分解这些层如何组合在一起、端到端集成流程以及这为智能体构建者解锁了什么。

## 1、AG2：智能体团队的运行时

AG2（前身为 AutoGen）是一个围绕多智能体协作构建的开源编程框架。你定义专业智能体，连接工具并运行结构化对话来完成任务。

AG2 不使用单一的整体循环，而是将智能体视为通过共享上下文协作的可组合参与者。

![ag2](https://www.hubwiz.com/blog/content/images/2026/04/sp7m6eo02xojqpa8311l.png)

其核心是 [ConversableAgent](https://docs.ag2.ai/latest/docs/api-reference/autogen/ConversableAgent/?ref=hubwiz.com)，这是定义智能体角色、推理模型和工具访问权限同时处理消息交换的原语。

```
from autogen import ConversableAgent, LLMConfig
from dotenv import load_dotenv
import os
load_dotenv()

# Create LLM configuration first
llm_config = LLMConfig({
  "api_type": "openai",
  "model": "gpt-5-mini",
  "api_key": os.getenv("OPENAI_API_KEY"),
})

# Create the agent
lesson_planner = ConversableAgent(
    name="planner_agent",
    system_message="You are a lesson planner for a fourth grade class.",
    description="Creates lesson plans.",
    llm_config=llm_config,
)

```

智能体可以使用内置模式（如顺序流、群组对话、嵌套调用和人机交互检查点）组织成协调工作流。

在实践中，你可以将规划器、执行器和审查器建模为不同的智能体：每个智能体都有自己的角色和工具，让 AG2 管理它们在多个回合中如何交互。

```
auto_selection = AutoPattern(
    agents=[teacher, lesson_planner, lesson_reviewer],
    initial_agent=lesson_planner,
    group_manager_args={"llm_config": llm_config},
)

response = run_group_chat(
    pattern=auto_selection,
    messages="Introduce students to the solar system.",
    max_rounds=20,
)

response.process()

```

这允许后端行为通过不同地组装智能体来演进，而不是为每个新工作流重写控制逻辑。

AG-UI 集成目前包装单个 `ConversableAgent`。多智能体模式（群组聊天、委托、嵌套流）仍在 AG2 内部运行，但通过统一的交互界面暴露。

分阶段或多智能体 UX 可以使用上下文变量来建模。该模式在集成部分有介绍。

在[文档](https://docs.ag2.ai/latest/docs/user-guide/basic-concepts/overview/?ref=hubwiz.com)中阅读涉及的所有基本概念，并查看[示例仓库](https://github.com/ag2ai/build-with-ag2?ref=hubwiz.com)，其中包含许多示例。

## 2、差距：没有应用契约的编排

即使多智能体逻辑是可移植的，它也不会自动变成应用可移植的。

在生产应用中，UI 需要一个稳定的运行时契约来支持：

- 流式传输消息和部分结果。
- 工具生命周期（开始 → 进度 → 完成/失败）。
- 运行仍在执行时的状态快照和更新。
- 可以引导或中断运行的人机交互操作

AG2 在内部管理委托、共享上下文和编排。但它没有定义该执行如何暴露给前端的标准事件/状态接口。

没有这个契约，每个 AG2 应用最终都会发明自己的 WebSocket/SSE 负载格式和 UI 映射规则。集成变成了紧耦合的胶水代码，而不是可重用的交互层。

这就是 AG-UI 协议的用武之地。

## 3、AG-UI：执行和交互层

[AG-UI（Agent–User Interaction Protocol）](https://github.com/ag-ui-protocol/ag-ui?ref=hubwiz.com)是一种基于事件的协议，标准化了智能体运行时和应用之间的实时交互流。

在运行期间，后端发出结构化事件类型的流。前端消费该流并可以发回兼容的交互事件。

这很重要，因为 AG2 已经在内部管理多智能体协调。AG-UI 定义的是该协调如何在应用边界变得可观察和可交互。

AG-UI 不是让每个应用发明自定义负载格式，而是定义了一小组自描述的 JSON 事件类型。

每个事件包含清晰的 `type` 和结构化负载。例如：

- `TEXT_MESSAGE_CONTENT`：事件流式传输 LLM token
- `TOOL_CALL_START/END`：传达函数调用进度
- `STATE_DELTA`：携带 JSON Patch 增量来同步状态

在实践中，AG-UI 标准化了：

- 消息流式传输
- 工具生命周期事件（开始 → 进度 → 完成/失败）
- 状态快照和增量更新
- 用户交互事件（点击、表单提交、确认）

由于流是标准且有序的，前端可以可靠地解释后端正在做什么并实时渲染进度。

结果是解耦。后端不需要知道 UI 如何渲染进度，UI 也不需要理解内部编排逻辑。

![ag-ui](https://www.hubwiz.com/blog/content/images/2026/04/m4p991we879xt9tfv8hh.png)

这里，AG-UI 使用基于 HTTP 的 Server-Sent Events（SSE）作为其主要传输方式。AG2 集成为每次运行提供 `text/event-stream` 响应。

在 AG2 中，此协议通过 `AGUIStream` 实现，它包装 `ConversableAgent` 并将其暴露为流式传输 AG-UI 事件的 ASGI 端点。

在 [AG-UI 文档](https://docs.ag-ui.com/concepts/events?ref=hubwiz.com)中探索完整的事件规范，在 [AG2 用户指南](https://docs.ag2.ai/latest/docs/user-guide/ag-ui/?ref=hubwiz.com)中查看实现细节，包括何时采用此集成的最佳实践。

## 4、CopilotKit 如何将 AG2 连接到 AG-UI

在后端，AG2 通过使用 `AGUIStream` 的 AG-UI 兼容端点暴露智能体运行。该端点为运行的生命周期流式传输标准化的 AG-UI 事件。

[CopilotKit](https://copilotkit.ai/?ref=hubwiz.com) 充当该客户端和 UI 运行时。它连接到 AG-UI 端点（通过 [@ag-ui/client](https://docs.ag-ui.com/sdk/js/client/overview?ref=hubwiz.com)），订阅事件流，在你的应用内渲染智能体活动，并将用户操作转发回同一执行循环。

![智能体交互流程](https://www.hubwiz.com/blog/content/images/2026/04/oo3wdunpaqiqxqsnnivb.png)

连接方式很直接：

- 你的后端运行 AG2 智能体工作流
- `AGUIStream` 包装智能体并将执行转换为 AG-UI 事件
- 这些事件通过 SSE 上的 AG-UI 端点暴露
- CopilotKit 连接并订阅实时事件流
- 智能体消息、工具进度和状态更新在 UI 中渲染
- 用户交互通过 AG-UI 发送回同一个 AG2 运行

同一端点可以被任何其他 AG-UI 兼容的客户端消费。从高层来看，完整的交互循环如下所示：

```
AG2 Runtime (multi-agent orchestration)
│
│ executes ConversableAgents
│ manages delegation + shared state
│ invokes tools
▼
AG2 ↔ AG-UI Integration Layer (AGUIStream)
│
│ wraps ConversableAgent
│ maps AG2 activity → standardized AG-UI events
│ handles SSE transport
▼
AG-UI Endpoint (event + state stream)
│
│ agent ↔ application synchronization
│ TEXT_MESSAGE_CONTENT
│ TOOL_CALL_START / END
│ STATE_DELTA / STATE_SNAPSHOT
│ USER_INTERACTION
▼
CopilotKit (AG-UI client runtime)
│
├─ subscribes to live stream
├─ renders messages + tool lifecycle
├─ synchronizes state updates
└─ forwards user actions → AG2 via AG-UI
▼
Application UI

```

后端仍然是纯 AG2。CopilotKit 只是消费 AG-UI 流并将其渲染为产品 UI。

## 5、集成流程：AG2 → AG-UI → CopilotKit

我们已经看到了概念流程。现在让我们看看实际实现。

你可以在 [build-with-ag2 仓库](https://github.com/ag2ai/build-with-ag2/tree/main/ag-ui?ref=hubwiz.com)中查看 AG-UI 集成示例，其中包含两种模式：`weather/` 目录展示了带工具的单智能体聊天，`factory/` 目录演示了使用 `ContextVariables` 的多阶段管道。

对于完整的 CopilotKit + AG2 集成及完整 UI 实现，请探索 [ag2-samples 仓库](https://github.com/ag2ai/ag2-samples?ref=hubwiz.com)。

集成以 `AGUIStream` 为中心，它包装 `ConversableAgent` 并将其暴露为基于 SSE 的 AG-UI 端点。

像平常一样定义你的智能体，然后将流挂载到 FastAPI 上。唯一重要的细节是在 LLM 配置中启用流式传输。

```
from autogen import ConversableAgent, LLMConfig
from autogen.ag_ui import AGUIStream
from fastapi import FastAPI

agent = ConversableAgent(
    name="weather_agent",
    system_message="You are a helpful weather assistant. Use the get_weather tool to look up current conditions for any city.",
    llm_config=LLMConfig({
        "model": "gpt-5-mini",
        "stream": True
    }),
    functions=[get_weather],
)

# wrap the agent and mount it as an ASGI endpoint
stream = AGUIStream(agent)  

app = FastAPI()  
app.mount("/chat", stream.build_asgi())

```

这就是整个后端桥接。

`AGUIStream` 自动映射：

- Token 流式传输 → `TEXT_MESSAGE_*`
- 工具执行 → `TOOL_CALL_START`、`TOOL_CALL_RESULT`
- 上下文更新 → `STATE_SNAPSHOT` / `STATE_DELTA`
- 运行生命周期 → `RUN_STARTED`、`RUN_FINISHED`、`RUN_ERROR`

端点提供 Server-Sent Events（SSE）。当客户端发送带有 `Accept: text/event-stream` 的 `RunAgentInput` 负载时，响应变为实时事件流。

以下是返回内容的简化示例：

```
data: {"type":"RUN_STARTED", ...}
data: {"type":"TEXT_MESSAGE_CONTENT","delta":"The"}
data: {"type":"TEXT_MESSAGE_CONTENT","delta":" weather"}
data: {"type":"TOOL_CALL_START", ...}
data: {"type":"TOOL_CALL_RESULT", ...}
data: {"type":"RUN_FINISHED", ...}

```

前端不需要理解 AG2 内部机制。它只对事件类型做出反应。在最低层面上，消费 AG-UI 只是打开一个 SSE 流：

```
const response = await fetch("/chat", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "text/event-stream"
  },
  body: JSON.stringify(runAgentInput)
});

```

但在实践中，你不需要手动解析 SSE。

CopilotKit 原生理解 AG-UI。你保持相同的后端（`AGUIStream`），只需将 CopilotKit 指向该端点。通过 Next.js API 路由代理 AG-UI 流量。

```
import {
  CopilotRuntime,
  ExperimentalEmptyAdapter,
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { HttpAgent } from "@ag-ui/client";
import { NextRequest } from "next/server";

// You can use any service adapter here for multi-agent support
// Use ExperimentalEmptyAdapter since AG2 handles the LLM directly
const serviceAdapter = new ExperimentalEmptyAdapter();

const runtime = new CopilotRuntime({
  agents: {
    weather_agent: new HttpAgent({
      url: "http://localhost:8000/chat"
    })
  }
});

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter,
    endpoint: "/api/copilotkit",
  });

  return handleRequest(req);
};

```

最后，用 CopilotKit 包装你的应用并渲染聊天。CopilotKit 订阅 AG-UI 流并实时渲染消息、工具进度和状态更新。

```
import { CopilotKit } from "@copilotkit/react-core";
import { CopilotChat } from "@copilotkit/react-ui";

<CopilotKit runtimeUrl="/api/copilotkit" agent="weather_agent">
  <CopilotChat />
</CopilotKit>

```

这就是完整的循环。[build-with-ag2 仓库](https://github.com/ag2ai/build-with-ag2/tree/main/ag-ui/weather?ref=hubwiz.com)中的 `weather` 示例展示了这个最小流式设置。

## 6、多智能体编排

当前的 AG-UI 集成包装单个 `ConversableAgent`。多智能体工作流（群组聊天、委托、嵌套对话）仍在 AG2 内部运行，但通过一个交互界面暴露。

要建模分阶段或多智能体 UX，请使用带有 [ContextVariables](https://docs.ag2.ai/latest/docs/user-guide/advanced-concepts/orchestration/group-chat/context-variables/?ref=hubwiz.com#the-hospital-er-analogy) 的编排器智能体。它是智能体用来在对话中协调、跟踪进度和做出决策的共享状态。

当工具更新 `context_variables` 时，`AGUIStream` 会自动发出 `STATE_SNAPSHOT` 事件。

前端可以消费该快照来：

- 高亮显示哪个智能体处于活动状态
- 显示管道进度
- 渲染特定阶段的 UI

以下是该模式：

```
from autogen import ConversableAgent
from autogen.ag_ui import AGUIStream

def submit_plan(plan: str, context): # context injected automatically
    """Submit the plan and move to draft stage."""
    context["active_agent"] = "drafter"
    context["stage"] = "drafting"
    context["plan"] = plan
    return {"status": "plan submitted"}

def submit_draft(draft: str, context):
    """Submit the draft and move to review stage."""
    context["active_agent"] = "reviewer"
    context["stage"] = "reviewing"
    context["draft"] = draft
    return {"status": "draft submitted"}

def submit_review(approved: bool, context):
    """Submit review and finalize."""
    context["stage"] = "complete" if approved else "revising"
    return {"status": "review complete"}

orchestrator = ConversableAgent(
    name="orchestrator",
    system_message="You coordinate a multi-stage workflow.",
    llm_config=llm_config,
    functions=[submit_plan, submit_draft, submit_review],
)

stream = AGUIStream(orchestrator)

```

每次更新 `context` 的工具调用都会触发 `STATE_SNAPSHOT`。前端从快照中读取 `active_agent` 和 `stage` 并相应地更新 UI。

[factory 示例](https://github.com/ag2ai/build-with-ag2/tree/main/ag-ui/factory?ref=hubwiz.com)以三面板 UI 展示了此模式：智能体管道、文档预览和对话日志。

原生多智能体支持正在积极开发中。此编排器模式是当前的变通方案。

## 7、结束语

通过此集成，你可以保持 AG2 的优势领域，同时仍然交付真实的 UI 而无需协议胶水。你可以：

✅ 构建 AG2 智能体团队并使用一个包装器（`AGUIStream`）将它们暴露为 AG-UI 端点。

✅ 将这些端点连接到 CopilotKit（或任何 AG-UI 客户端），无需自定义 WebSocket 或轮询基础设施。

✅ 跨产品重用 AG2 智能体逻辑，同时保持单一前端契约（AG-UI），而不是为每个应用发明新的负载格式

✅ 使用 CopilotKit 组件实时流式传输智能体运行、工具进度和状态，让用户看到系统正在做什么，而不是等待单一的最终响应。

---

原文链接: [Give Your AG2 Agents a UI with AG-UI and CopilotKit](https://dev.to/copilotkit/give-your-ag2-agents-a-ui-with-ag-ui-and-copilotkit-3kl5?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处

> **这是「Agent / MCP」专题的一部分。**完整地图见：[Agent / MCP / 自动化完全指南](https://www.hubwiz.com/blog/agent-stack/)