ag-ui-copilotkit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AG-UI + CopilotKit Development

AG-UI + CopilotKit 开发

Build agentic UIs with bidirectional communication between AI agents and React frontends.
构建AI Agent与React前端双向通信的Agent化UI。

Architecture Overview

架构概述

┌─────────────────────┐     AG-UI Protocol      ┌─────────────────────┐
│   Next.js Frontend  │ ◄──────────────────────►│  FastAPI Backend    │
│   (CopilotKit)      │   SSE Event Stream      │  (Pydantic AI)      │
│                     │                          │                     │
│ • useCoAgent        │   Events:               │ • Agent + tools     │
│ • useCopilotAction  │   - TextMessageStart    │ • to_ag_ui()        │
│ • useCopilotReadable│   - ToolCallStart       │ • StateDeps         │
│ • useCoAgentState   │   - StateSnapshot       │ • StateSnapshot     │
│   Render            │   - StateDelta          │ • StateDelta        │
└─────────────────────┘                          └─────────────────────┘
┌─────────────────────┐     AG-UI Protocol      ┌─────────────────────┐
│   Next.js Frontend  │ ◄──────────────────────►│  FastAPI Backend    │
│   (CopilotKit)      │   SSE Event Stream      │  (Pydantic AI)      │
│                     │                          │                     │
│ • useCoAgent        │   事件:               │ • Agent + tools     │
│ • useCopilotAction  │   - TextMessageStart    │ • to_ag_ui()        │
│ • useCopilotReadable│   - ToolCallStart       │ • StateDeps         │
│ • useCoAgentState   │   - StateSnapshot       │ • StateSnapshot     │
│   Render            │   - StateDelta          │ • StateDelta        │
└─────────────────────┘                          └─────────────────────┘

Quick Start

快速开始

Backend (Python with Pydantic AI)

后端(基于Python与Pydantic AI)

python
from pydantic_ai import Agent
from ag_ui.core import EventType, StateSnapshotEvent

agent = Agent('openai:gpt-4o-mini')
app = agent.to_ag_ui()  # Creates FastAPI app

@agent.tool_plain
async def my_tool(param: str) -> StateSnapshotEvent:
    return StateSnapshotEvent(
        type=EventType.STATE_SNAPSHOT,
        snapshot={"result": param}
    )
python
from pydantic_ai import Agent
from ag_ui.core import EventType, StateSnapshotEvent

agent = Agent('openai:gpt-4o-mini')
app = agent.to_ag_ui()  # Creates FastAPI app

@agent.tool_plain
async def my_tool(param: str) -> StateSnapshotEvent:
    return StateSnapshotEvent(
        type=EventType.STATE_SNAPSHOT,
        snapshot={"result": param}
    )

Frontend (React with CopilotKit)

前端(基于React与CopilotKit)

tsx
// layout.tsx - Wrap app with CopilotKit
<CopilotKit runtimeUrl="/api/copilotkit" agent="myAgent">
  {children}
</CopilotKit>

// page.tsx - Use hooks
const { state, setState } = useCoAgent({
  name: "myAgent",
  initialState: { /* ... */ }
});

useCopilotAction({
  name: "my_action",
  parameters: [{ name: "param", type: "string" }],
  renderAndWaitForResponse: ({ args, respond, status }) => (
    <MyComponent onAccept={() => respond("accepted")} />
  )
});
tsx
// layout.tsx - Wrap app with CopilotKit
<CopilotKit runtimeUrl="/api/copilotkit" agent="myAgent">
  {children}
</CopilotKit>

// page.tsx - Use hooks
const { state, setState } = useCoAgent({
  name: "myAgent",
  initialState: { /* ... */ }
});

useCopilotAction({
  name: "my_action",
  parameters: [{ name: "param", type: "string" }],
  renderAndWaitForResponse: ({ args, respond, status }) => (
    <MyComponent onAccept={() => respond("accepted")} />
  )
});

Core Patterns

核心模式

1. Shared State

1. 共享状态

Backend sends state updates; frontend renders and can modify.
Backend: Return
StateSnapshotEvent
or
StateDeltaEvent
from tools
Frontend: Use
useCoAgent
to receive and manage state
后端发送状态更新;前端进行渲染并可修改状态。
后端: 从工具返回
StateSnapshotEvent
StateDeltaEvent

前端: 使用
useCoAgent
接收并管理状态

2. Human-in-the-Loop

2. 人机协同工作流

Agent proposes actions; user approves/rejects via UI.
Backend: Define tools that the frontend will render
Frontend: Use
useCopilotAction
with
renderAndWaitForResponse
Agent提出操作;用户通过UI批准/拒绝。
后端: 定义将由前端渲染的工具
前端: 使用带有
renderAndWaitForResponse
useCopilotAction

3. Tool-Based Generative UI

3. 基于工具的生成式UI

Agent calls tools; frontend renders custom components for tool output.
Backend: Tools return structured data
Frontend:
useCopilotAction
renders components based on tool parameters
Agent调用工具;前端为工具输出渲染自定义组件。
后端: 工具返回结构化数据
前端:
useCopilotAction
根据工具参数渲染组件

4. Predictive State Updates

4. 预测性状态更新

Stream partial state while agent is processing.
Backend: Return
CustomEvent
with
PredictState
configuration
Frontend: UI updates optimistically as agent generates
在Agent处理过程中流式传输部分状态。
后端: 返回带有
PredictState
配置的
CustomEvent

前端: 随着Agent生成内容,UI进行乐观更新

Detailed References

详细参考

  • Backend patterns: See references/backend-pydantic-ai.md
  • Frontend patterns: See references/frontend-copilotkit.md
  • State management: See references/state-patterns.md
  • 后端模式:查看references/backend-pydantic-ai.md
  • 前端模式:查看references/frontend-copilotkit.md
  • 状态管理:查看references/state-patterns.md

Common Pitfalls

常见陷阱

  1. Missing CORS: Backend must allow frontend origin
  2. State sync: Always use
    useCoAgent
    name matching backend agent name
  3. Tool names: Must match between
    useCopilotAction
    and backend tools
  4. SSE handling: CopilotKit runtime must proxy to backend correctly
<!-- cross-ref:start -->
  1. 缺少CORS配置:后端必须允许前端源访问
  2. 状态同步问题
    useCoAgent
    的名称必须与后端Agent名称匹配
  3. 工具名称不一致
    useCopilotAction
    与后端工具的名称必须一致
  4. SSE处理问题:CopilotKit运行时必须正确代理到后端
<!-- cross-ref:start -->

See also (related skills — AG-UI family)

另请参阅(相关技能 — AG-UI系列)

If your issue relates to:
  • AG-UI protocol with Pydantic AI (Python backend) — check
    ag-ui-pydantic
    if appropriate.
<!-- cross-ref:end -->
如果你的问题涉及:
  • 结合Pydantic AI(Python后端)的AG-UI协议 — 如有需要,请查看
    ag-ui-pydantic
<!-- cross-ref:end -->