mcpField
A
ag2-ag-ui

ag2-ag-ui

github.com/ag2aiAgent 工作流1267 次安装13 周前更新
代码仓库

关于 ag2-ag-ui

AG2 的 AG-UI 集成指引,供构建 Web 前端的开发者将 Agent 事件流呈现到界面。它说明 FastAPI 服务端及 CopilotKit 前端的接法,并列出支持的事件类型。

主要功能

  1. 01运行生命周期事件
  2. 02流式文本与推理事件
  3. 03工具调用生命周期
  4. 04共享状态快照
  5. 05子任务步骤事件

适用场景

  1. 01在 React 或 Next.js 中呈现 Agent 对话
  2. 02向界面流式显示文本和推理
  3. 03呈现后端工具调用结果
  4. 04同步共享状态与子任务进度

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ag2ai/ag2-skills --skill ag2-ag-ui

安装后在 Claude Code 中输入/ag2-ag-ui确认已加载。

详细介绍

AG-UI 集成

适用场景

  • 用户正在构建一个 Web UI(React / Next.js / 任何基于 HTTP+SSE 的方案),需要与 AG2 Agent 通信。
  • 用户希望使用标准协议,将流式文本、推理、工具调用渲染、共享状态同步或子任务步骤跟踪呈现在前端,而不是自定义 REST/WebSocket 契约。
  • 用户正在使用或考虑使用 CopilotKit(推荐的 React 客户端)。

如果是用途狭窄且契约由你全权掌控的自定义 API,请跳过 AG-UI,改为编写普通端点。

支持的 AG-UI 功能

功能状态
运行生命周期(RUN_STARTED / RUN_FINISHED / RUN_ERROR)✓
流式文本事件(TEXT_MESSAGE_START / _CONTENT / _END / _CHUNK)✓
推理事件(REASONING_START / _END、REASONING_MESSAGE_START / _CONTENT / _END)✓
后端工具生命周期(TOOL_CALL_START / _ARGS / _RESULT / _END)✓
前端工具分发(RunAgentInput.tools 中客户端工具对应的 TOOL_CALL_CHUNK)✓
共享状态快照(STATE_SNAPSHOT)✓
子任务步骤(在 TaskStarted / TaskCompleted 时发出 STEP_STARTED / STEP_FINISHED)✓
以 AG-UI 事件形式呈现人工输入检查点✗ — 没有人工输入事件系列;hitl_hook 会传递给 agent.ask

安装

pip install "ag2[ag-ui]"

必需。在交付代码前运行此安装命令。如果无法运行命令,请注明确切的 pip install 命令。

60 秒快速示例 — FastAPI 服务

from fastapi import FastAPI, Header
from fastapi.responses import StreamingResponse

from ag2 import Agent
from ag2.ag_ui import AGUIStream, RunAgentInput
from ag2.config import OpenAIConfig

agent = Agent(
    name="support_bot",
    prompt="You help users with billing questions.",
    config=OpenAIConfig(model="gpt-4o-mini"),
)

stream = AGUIStream(agent)
app = FastAPI()

@app.post("/chat")
async def run_agent(message: RunAgentInput, accept: str | None = Header(None)) -> StreamingResponse:
    return StreamingResponse(
        stream.dispatch(message, accept=accept),
        media_type=accept or "text/event-stream",
    )
uvicorn run_ag_ui:app --reload --port 8000

测试:

curl -N -X POST http://127.0.0.1:8000/chat \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"thread_id":"t1","run_id":"r1","messages":[{"id":"m1","role":"user","content":"Hello"}],"state":{},"context":[],"tools":[]}'

更简单的替代方案 — build_asgi()

如果不需要自定义身份验证 / 中间件,可直接挂载 ASGI 端点:

from ag2.ag_ui import AGUIStream
from fastapi import FastAPI

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

CopilotKit 前端(推荐用于 React / Next.js)

有两种启动方式:

# Option A — CopilotKit bootstrap
npx copilotkit@latest create -f ag2

# Option B — clone the reference starter
# https://github.com/ag2ai/ag2-copilotkit-starter

初始项目布局:

ag2-copilotkit-starter/
├── agent-py/     # Python backend (AG2 + AG-UI)
└── ui-react/     # React + CopilotKit frontend

后端默认在端口 8008 上提供 /chat。ui-react/app/api/copilotkit/route.ts 中的 Next.js 路由会将 UI 连接到后端:

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

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

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

封装你的应用:

import { CopilotKit } from "@copilotkit/react-core";
import "@copilotkit/react-ui/styles.css";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <CopilotKit agent="weather_agent" runtimeUrl="/api/copilotkit">
          {children}
        </CopilotKit>
      </body>
    </html>
  );
}

渲染聊天界面(<CopilotChat />),并在客户端组件中使用 useCopilotAction({...}),以渲染与后端工具调用关联的生成式 UI。

生产环境检查清单

  • CORS — 在 AG-UI 后端允许你的前端来源(POST、OPTIONS、身份验证标头)。
  • 身份验证 — 保护 /api/copilotkit(Next.js 路由)和后端 /chat。不要依赖仅存在于客户端的密钥。
  • SSE 缓冲 — 确认后端响应为 Content-Type: text/event-stream,且代理层(Nginx、CloudFront 等)不会缓冲 SSE。
  • 超时 / 重试 — 对长时间运行的工具工作流采用保守的设置;仅重试幂等请求。
  • 工具输入不可信 — 在调用特权工具前,于服务端进行验证和授权。使用请求 ID 记录工具执行情况。
  • 工具名称一致 — 前端 useCopilotAction 的 name 必须与后端 @tool 名称完全一致。

深入了解

常见陷阱

  • 缺少 ag-ui extra — 必须运行 pip install "ag2[ag-ui]";否则 from ag2.ag_ui import AGUIStream 会失败。
  • CORS 被阻止 — 开发环境中的前端无法访问后端。为 FastAPI 应用添加 CORSMiddleware,并设置开发环境的来源。
  • 没有流式输出 — 可能是代理或 Content-Type 问题。先使用原始 curl -N 测试,以便定位问题。
  • 工具 UI 未渲染 — React 端的工具名称(useCopilotAction({ name: "..." }))与后端 @tool 名称不完全一致。
  • 将端点置于不兼容 SSE 的代理之后 — 许多代理默认会缓冲事件流响应。请在该路由上禁用缓冲。
  • 尝试将 AGUIStream 与经典的 ConversableAgent 搭配使用 — 此处的说明介绍的是 ag2.Agent。经典 AG2 Agent 可以通过其他方式公开;请查阅 AG2 文档了解相关方法。

评论

支持 Markdown