YAOTU INSIGHTS

CopilotKit + AG2 最小 Agentic Chat 实战:CopilotChat、流式响应与 Suggestion 建议卡片的完整接入指南

CopilotKit + AG2 最小 Agentic Chat 实战:CopilotChat、流式响应与 Suggestion 建议卡片的完整接入指南
CopilotKit AG2 最小 Agentic Chat 实战CopilotChat、流式响应与 Suggestion 建议卡片的完整接入指南【免费下载链接】CopilotKitThe Frontend Stack for Agents Generative UI. React, Angular, Mobile, Slack, and more. Makers of the AG-UI Protocol项目地址: https://gitcode.com/GitHub_Trending/co/CopilotKit导读本文基于 CopilotKit 仓库中 AG2 集成展示showcase里最精简的 Agentic Chat 演示拆解一个纯文本 Agent 聊天从零到可用的完整链路前端如何用CopilotKitProvider CopilotChat渲染聊天界面如何通过useConfigureSuggestions注册可点击的建议卡片以及 Next.js 的/api/copilotkit路由如何经由 AG-UI 协议把请求代理到独立的 Python 后端 Agent。读完本文你将掌握 CopilotKit v2 最小化聊天集成的四个核心动作——配置 Provider、渲染聊天组件、注册静态建议、接通 runtime 路由——并能理解底层 AG-UI 流式响应在前后端之间的传递方式。一、这个 Demo 展示了什么在 CopilotKit 的 AG2 集成 showcase 中agentic-chat 演示 被定位为最简 CopilotKit 界面一个由 LangGraphPython风格 Agent 提供能力的朴素对话窗口。按 manifest.yaml 中的登记信息该 demo 的 id 为agentic-chat、路由为/demos/agentic-chat核心高亮文件包括src/agents/agent.py —— 后端 Agent 定义src/app/demos/agentic-chat/page.tsx —— 前端页面src/app/api/copilotkit/route.ts —— runtime 代理路由。它集中呈现三个能力点自然对话在熟悉的聊天界面中与 Copilot 对话流式响应Assistant 消息通过 AG-UI 协议逐 token 流入界面建议卡片Suggestion Chips一个静态起始建议以快捷操作 chip 的形式渲染在输入框下方。注README 中backed by a LangGraph (Python) agent是沿用整个 showcase 体系的通用表述在 AG2 这个具体集成里后端实际是 AG2autogen的ConversableAgent通过AGUIStream以 AG-UI 协议暴露能力这一点在源码中有明确体现详见下文第五节。二、如何与这个聊天交互Demo 页面加载后你可以直接点击输入框下方的建议卡片或者输入自己的提示词。README 给出了三类示例Write a short sonnet about AI写一首关于 AI 的短十四行诗Explain the difference between an LLM and an agent解释 LLM 与 Agent 的区别Give me three ideas for a weekend project给出三个周末项目创意这些交互行为被 tests/e2e/agentic-chat.spec.ts 用 Playwright 完整覆盖形成可验证的契约页面加载即出现输入框与三条起始建议测试断言输入框placeholder 为Type a message可见且Write a sonnet、Tell me a joke、Is 17 prime?三个按钮在 15 秒内可见agentic-chat.spec.ts发送普通消息能得到 Assistant 响应填入Say hello in one word.并回车断言[data-testidcopilot-assistant-message]元素出现L23-L33点击建议卡片同样能触发响应点击Tell me a joke按钮后断言出现 assistant 消息L35-L43多轮对话保持上下文先让 Agent 记住我叫 Alice等建议卡片重新出现即上一轮流式结束后再追问名字第二条响应应包含AliceL45-L66。测试注释点明了这个 demo 的边界这里是原生聊天端到端可用的契约更丰富的能力属于专门的 demofrontend-tools、tool-rendering 等。三、前端接线Provider、Chat 组件与建议注册3.1 页面骨架page.tsx完整页面只有 24 行核心结构如下page.tsxuse client; import React from react; import { CopilotKit, CopilotChat } from copilotkit/react-core/v2; import { useAgenticChatSuggestions } from ./suggestions; export default function AgenticChatDemo() { return ( CopilotKit runtimeUrl/api/copilotkit agentagentic_chat Chat / /CopilotKit ); } function Chat() { useAgenticChatSuggestions(); return CopilotChat agentIdagentic_chat /; }拆解来看ProviderCopilotKit把页面挂接到 CopilotKit runtime。两个关键属性runtimeUrl/api/copilotkit指向 Next.js 中代理 Agent 的路由agentagentic_chat选中langgraph.json中定义的 LangGraph Agent在 AG2 集成中这一名称被注册到共享的后端 Agent见第五节。聊天界面CopilotChat渲染包含输入框、消息列表与流式输出的完整聊天 UI并通过agentIdagentic_chat显式绑定到同一 Agent。建议useConfigureSuggestions注册一条静态建议渲染为聊天输入框下方可点击的 chip。3.2 建议注册suggestions.ts建议逻辑被独立成 hooksuggestions.tsuse client; import { useConfigureSuggestions } from copilotkit/react-core/v2; export function useAgenticChatSuggestions() { useConfigureSuggestions({ suggestions: [ { title: Write a sonnet, message: Write a short sonnet about AI. }, { title: Tell me a joke, message: Tell me a one-line joke. }, { title: Is 17 prime?, message: Walk me through whether 17 is prime. }, ], available: always, }); }这里available: always表示建议在对话开始前和开始后都保持可见点击建议卡片会把message作为用户消息发出。注意页面渲染的三条卡片标题是Write a sonnet / Tell me a joke / Is 17 prime?与 E2E 测试断言完全对应。3.3 底层实现useConfigureSuggestions 如何工作useConfigureSuggestions的实现位于 packages/react-core/src/v2/hooks/use-configure-suggestions.tsx配置归一化hook 内部对传入配置做归一化与序列化缓存——当config为空、或config.available disabled时直接返回空配置静态建议会被normalizeStaticSuggestions补齐为内部StaticSuggestionsConfigL53-L88Agent 归属解析通过consumerAgentId默认*表示对所有 Agent 生效与CopilotChatConfiguration中的agentId决定建议归属于哪个 Agent从而只在目标聊天中展示L93-L107。建议配置的类型定义在 packages/core/src/types.tsSuggestion{ title, message, isLoading, className? }L105-L112SuggestionAvailabilitybefore-first-message | after-first-message | always | disabledL114-L118StaticSuggestionsConfig{ suggestions, available?, consumerAgentId? }其中available默认before-first-messageconsumerAgentId默认*L152-L167DynamicSuggestionsConfig通过instructions让 LLM 动态生成建议可配置minSuggestions默认 1、maxSuggestions默认 3、available默认after-first-message与providerAgentId/consumerAgentIdL120-L150。也就是说本 demo 使用的是其中最简单的一种静态建议 全时段可见。CopilotChat组件的类型签名位于 packages/react-core/src/v2/components/chat/CopilotChat.tsx除agentId、threadId外还支持labels、自定义chatView、attachments、onError与throttleMs等扩展能力L51-L96。组件内部通过useAgent({ agentId, throttleMs })建立与 Agent 的连接并从useSuggestions读取当前 Agent 的建议列表L138-L144。四、runtime 路由Next.js 如何代理到 Python Agent前端 Provider 的runtimeUrl/api/copilotkit对应 Next.js 路由 src/app/api/copilotkit/route.ts。该路由的核心逻辑import { CopilotRuntime, createCopilotRuntimeHandler } from copilotkit/runtime/v2; import { HttpAgent } from ag-ui/client; // The agent backend runs as a separate process on port 8000. // This runtime proxies CopilotKit requests to it via AG-UI protocol. const AGENT_URL process.env.AGENT_URL || http://localhost:8000; function createAgent(path /) { return new HttpAgent({ url: ${AGENT_URL}${path} }); }关键点后端 Agent 是独立进程运行在 8000 端口的 Python FastAPI 服务前端通过 AG-UI 协议转发请求route.tsagentic_chat名称被注册到共享 AgentsharedAgentNames数组中包含agentic_chat它以及human_in_the_loop、tool-rendering等十几个前端变体 demo都指向同一个默认HttpAgent根路径/因为 AG2 的AGUIStream只包装一个ConversableAgent多数前端差异化 demo 复用同一个后端L35-L56单路由模式挂载通过createCopilotRuntimeHandler({ runtime, basePath: /api/copilotkit, mode: single-route })生成处理函数POST 请求进入 CopilotKit runtime 后转发给注册的 AgentL110-L135错误不泄内幕catch 分支只把errorId返回给客户端完整错误message stack写入服务端日志L136-L156GET 作为健康探针GET/api/copilotkit会去探测${AGENT_URL}/health返回agent_status与OPENAI_API_KEY是否已设置等环境信息L159-L183。路由头部注释还记录了一个生产经验无条件的逐请求日志在 d6 探针扇出下会打满 Railway 每秒 500 条的日志上限导致容器被杀因此逐请求日志被SHOWCASE_ROUTE_DEBUG开关默认关闭门控L17-L23。五、后端 AgentAG2 ConversableAgent 与 AG-UI 流式出口5.1 Agent 定义后端 Agent 定义在 src/agents/agent.py使用 AG2autogen的ConversableAgentfrom autogen import ConversableAgent, LLMConfig from autogen.ag_ui import AGUIStream agent ConversableAgent( nameassistant, system_message( You are a helpful sales assistant. You can look up current weather for any city using the get_weather tool, query financial data with query_data, manage the sales pipeline with manage_sales_todos and get_sales_todos, schedule meetings with schedule_meeting, search flights and display rich A2UI cards with search_flights, and generate dynamic A2UI dashboards with generate_a2ui. When asked about the weather, always use the tool rather than guessing. Be concise and friendly in your responses. ), llm_configLLMConfig({model: gpt-4o-mini, stream: True}), human_input_modeNEVER, max_consecutive_auto_reply15, functions[get_weather, query_data, manage_sales_todos, get_sales_todos, schedule_meeting, search_flights, generate_a2ui], ) # AG-UI stream wrapper stream AGUIStream(agent)值得注意的实现细节llm_config{model: gpt-4o-mini, stream: True}开启流式生成这是前端逐 token 渲染的根基max_consecutive_auto_reply15在human_input_modeNEVER下给自动工具调用循环设上限防止无限工具调用打爆日志与健康探针L239-L244工具返回 JSON 字符串而非 dictautogen 对 dict 返回值会str()成 Python repr单引号前端JSON.parse无法解析因此所有工具统一json.dumps(...)返回L55-L68 等处的注释AGUIStream(agent)是 AG-UI 协议包装器把 Agent 的流式输出转成 AG-UI 事件流REASONING_MESSAGE、RUN_STARTED 等前端据此渲染 token 级增量。5.2 FastAPI 挂载与共享 Agent 路由FastAPI 服务入口是 src/agent_server.py默认 Agent 的 AG-UI 端点以 catch-all 挂载在根路径app.mount(/, default_stream.build_asgi())L196多个中间件依次包裹CORS、HeaderForwarding转发x-*头、RequestUserMessage按请求捕获最新用户消息到 ContextVar、Health 与 CVDIAG 后端埋点L120-L153需要独立状态槽的 demo 以命名子应用先挂载/shared-state-read-write、/subagents等最后才挂根路径避免 catch-all 遮蔽L156-L196。这也解释了 route.ts 中多数名称代理到同一后端进程的设计agentic_chat与它的兄弟 demo 共用根路径的ConversableAgent状态不隔离需要隔离状态的 demo 走独立挂载路径。5.3 依赖与版本约束后端依赖见 requirements.txtag2[openai,ag-ui]0.9.0,1.0.0、ag-ui-protocol0.1.10、fastapi、uvicorn、openai等。文件头部注释明确说明上限1.0.0是因为 AG2 1.0.0 把顶层模块autogen重命名为ag2并移除了autogen/ag_ui稳定适配器、AGUIStream的dispatch()签名从context改为variables直接升级会引发导入错误与运行时 TypeErrorrequirements.txt。前端依赖见 package.jsoncopilotkit/react-core、copilotkit/runtime均为1.68.2另有ag-ui/client0.0.57HttpAgent 的来源。六、如何本地运行6.1 一键启动前后端并行package.json 的dev脚本用concurrently同时拉起两个进程concurrently next dev --turbopack PYTHONPATH. python -m uvicorn agent_server:app --host 0.0.0.0 --port 8000 --reload前端 Next.js 开发服务器默认跑在 3000 端口Python 后端跑在 8000 端口路由里AGENT_URL默认值http://localhost:8000与之对应PYTHONPATH.保证agent_server及其agents.*、_shared、tools等模块能被正确导入。6.2 依赖准备环境变量src/agent_server.py在导入任何 Agent 模块之前先load_dotenv()顺序关键因为agent.py在模块级构造openai.AsyncOpenAI()与LLMConfig会在导入时读取OPENAI_API_KEY因此需要提供包含OPENAI_API_KEY的.env文件agent_server.pyPython 依赖pip install -r requirements.txtNode 依赖npm install/pnpm install仓库为 pnpm workspace。6.3 端到端验证仓库提供 Playwright 测试npm run test:e2e即可运行只跑本 demo 可过滤到 agentic-chat.spec.ts。四个测试用例分别覆盖页面加载与三条建议可见、输入消息得到流式响应、点击建议卡片得到响应、多轮对话上下文保持Alice 用例。七、小结与延伸Agentic Chat 是理解 CopilotKit 集成最小闭环的最佳入口其完整链路可以概括为前端CopilotKitProvider 声明runtimeUrl与默认agent→CopilotChat渲染完整聊天界面 →useConfigureSuggestions注册建议卡片runtimeNext.js 路由/api/copilotkit用CopilotRuntimeHttpAgent把请求经 AG-UI 协议代理到独立 Python 进程后端AG2ConversableAgent以streamTrue生成、AGUIStream包装为 AG-UI 事件流流式响应原路返回前端逐 token 渲染。在此骨架之上仓库还提供了更丰富的 AG2 集成能力登记在 manifest.yamltool-rendering工具渲染为 UI 组件、human-in-the-loopuseHumanInTheLoop与useFrontendTool异步审批、共享状态ContextVariables 读写、子 Agent、生成式 UIA2UI 固定/动态 schema、Open Gen UI 沙箱、语音输入、多模态附件等。如果你想深入某一层推荐按顺序阅读前端 Chat 组件源码CopilotChat.tsx建议 hook 源码use-configure-suggestions.tsx 与类型定义 types.tsruntime 代理路由api/copilotkit/route.ts后端 Agent 与服务器agent.py、agent_server.py端到端契约agentic-chat.spec.ts从 Agentic Chat 起步把对话、建议、流式这三件事跑通后其余能力都可以在此基础上逐步叠加。【免费下载链接】CopilotKitThe Frontend Stack for Agents Generative UI. React, Angular, Mobile, Slack, and more. Makers of the AG-UI Protocol项目地址: https://gitcode.com/GitHub_Trending/co/CopilotKit创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考