尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

CopilotKit 集成 Agno 构建投资分析 Agent:从 Next.js 前端到 AG-UI 后端的完整实战指南

CopilotKit 集成 Agno 构建投资分析 Agent:从 Next.js 前端到 AG-UI 后端的完整实战指南 CopilotKit 集成 Agno 构建投资分析 Agent从 Next.js 前端到 AG-UI 后端的完整实战指南【免费下载链接】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本指南基于仓库中的 examples/integrations/agno 起步模板完整讲解如何用 Agno 定义具备金融工具与前端工具的智能体再通过 CopilotKit 的 AG-UI 兼容层接入现代 Next.js 前端。读完本文你将掌握环境准备与一键启动流程、Agno 后端在 AG-UI 协议下的暴露方式、前端工具Frontend Actions与后端工具的协作机制以及将同一 Agent 挂载为 Slack/Teams Intelligence Channel 的进阶用法。模板总览一个可扩展的投资分析 Agent 起步工程该模板是一个将 Agno 与 CopilotKit 打通的完整示例工程核心能力是一个投资分析师智能体它能够研究股票、分析市场数据并提供投资见解。工程采用前后端分离但统一编排的结构前端基于 Next.js 16 React 19 的 UI使用copilotkit/react-core的 v2 API 接入聊天侧边栏、线程抽屉与前端工具后端基于 Agnoagno1.7.8 OpenAI YFinance 的 Python Agent通过 AG-UI 协议对外提供服务桥接层copilotkit/runtimev2 中的HttpAgent将前端与 Agno 后端连接ag-ui/client则负责按 AG-UI 协议与 Python 端通信。从 package.json 可以看到工程依赖了copilotkit/react-core1.70.0、copilotkit/runtime1.70.0、copilotkit/channels0.9.0、ag-ui/client0.0.58、next16.0.7与react^19.2.0Python 侧依赖在 agent/pyproject.toml 中声明包括agno、yfinance、fastapi、uvicorn与ag-ui-protocol。整个工程把前端交互层 协议桥接层 Python 智能体层的经典三层结构完整落到了代码里是一个可以直接扩展的起步模板。环境准备与前置依赖在开始之前请确保你的机器满足以下条件依赖版本要求用途Node.js20运行 Next.js 前端与 CopilotKit runtimePython3.12运行 Agno Agentuv最新稳定版Python 包管理器安装 Agent 依赖OpenAI API Key有效 Key驱动 Agno 智能体的 LLM 推理包管理器方面模板默认使用 npm同时也兼容 pnpm、yarn 与 bun后续所有命令都可用你偏好的管理器等价替换。快速开始安装、配置与启动第一步安装依赖在模板根目录执行安装命令# 使用 npm默认 npm install # 使用 pnpm pnpm install # 使用 yarn yarn install # 使用 bun bun install注意安装 Node 依赖时postinstall钩子会自动触发install:agent脚本进而通过 scripts/setup-agent.sh在 agent 目录执行uv sync安装 Agent 的 Python 依赖。也就是说一条命令同时完成了前端与后端的依赖准备。第二步配置 OpenAI API Key两种方式任选其一。方式一直接导出环境变量export OPENAI_API_KEYyour-openai-api-key-here方式二写入.env文件模板在 agent/main.py 中通过dotenv.load_dotenv()自动加载echo OPENAI_API_KEYyour-openai-api-key-here .env第三步启动开发服务器# 使用 npm默认 npm run dev # 使用 pnpm pnpm dev # 使用 yarn yarn dev # 使用 bun bun run dev该命令会通过concurrently同时拉起 UI 与 Agent 两个服务见 package.json 中的dev脚本其中 UI 由next dev启动Agent 由 scripts/run-agent.sh 在 agent 目录执行uv run python main.py启动。后端 Agent 剖析Agno YFinance 前端工具智能体定义与工具注册核心的 Agent 定义在 agent/src/agent.py 中仅 20 余行代码就组装出了一个完整的投资分析智能体from agno.agent.agent import Agent from agno.models.openai import OpenAIChat from agno.tools.yfinance import YFinanceTools from .tools.backend import get_weather from .tools.frontend import add_proverb, set_theme_color agent Agent( modelOpenAIChat(idgpt-4o), tools[ # Example of backend tools, defined and handled in your agno agent YFinanceTools(), get_weather, # Example of frontend tools, handled in the frontend Next.js app add_proverb, set_theme_color, ], descriptionYou are an demonstrative agent for Agno and CopilotKits integration., instructionsFormat your response using markdown and use tables to display data where possible., )这段代码体现了模板的核心设计思路——工具被明确划分为两类后端工具Backend ToolsYFinanceTools()与get_weather由 Agno Agent 在 Python 侧定义并执行。YFinanceTools()来自 Agno 的工具库用于拉取股票行情与市场数据get_weather定义在 agent/src/tools/backend.py是一个标准的 Agno 工具返回模拟天气数据tool def get_weather(location: str): Get the weather for the current location. Args: location (str): The location to get the weather for. Returns: str: The weather for the current location. return fThe weather in {location} is: 70 degrees and Sunny.前端工具Frontend Toolsadd_proverb与set_theme_color声明在 agent/src/tools/frontend.py。它们用tool(external_executionTrue)标记——这是关键区别Agno 只负责在需要时调用这个工具真正的执行发生在前端tool(external_executionTrue) def set_theme_color(theme_color: str): Change the theme color of the chat. Args: background: str: The background color to change to. tool(external_executionTrue) def add_proverb(proverb: str): Add a proverb to the chat. Args: proverb: str: The proverb to add to the chat. 以 AG-UI 协议暴露 Agent 服务Agent 的服务化入口在 agent/main.py它利用 Agno 的AgentOS与AGUI接口把 Agent 包装成标准的 AG-UI 服务端from pathlib import Path import dotenv from agno.os import AgentOS from agno.os.interfaces.agui import AGUI from src.agent import agent dotenv.load_dotenv(Path(__file__).resolve().parent.parent / .env) dotenv.load_dotenv() # Build AgentOS and extract the app for serving agent_os AgentOS(agents[agent], interfaces[AGUI(agentagent)]) app agent_os.get_app() app.get(/health) async def health(): return {status: ok} if __name__ __main__: agent_os.serve(appmain:app, port8000, reloadTrue)几个值得注意的实现细节默认端口 8000前端HttpAgent默认连接http://localhost:8000/agui见 src/agent.ts与这里的port8000严格对应这也是故障排查时首先要核对的点AG-UI 接口AGUI(agentagent)将 Agno Agent 转换为符合 AG-UI 协议的接口前端通过ag-ui/client的HttpAgent即可与之对话健康检查/health端点返回{status: ok}可用来确认 Agent 服务是否存活。前端接入HttpAgent、路由与前端工具运行时路由Agent 的 HTTP 出口前端通过 src/app/api/copilotkit/[[...slug]]/route.ts 这个 Next.js 路由基于 Hono/Vercel 适配暴露 CopilotKit 运行时import { CopilotRuntime, CopilotKitIntelligence, createCopilotEndpoint, InMemoryAgentRunner, } from copilotkit/runtime/v2; import { createDefaultAgent } from /agent; import { handle } from hono/vercel; const runtime new CopilotRuntime({ agents: { default: createDefaultAgent(), }, // --- copilotkit:intelligence (remove this block to opt out) --- ...(process.env.CPK_INTELLIGENCE_API_KEY ? { intelligence: new CopilotKitIntelligence({ apiKey: process.env.CPK_INTELLIGENCE_API_KEY, ...(process.env.INTELLIGENCE_API_URL ? { apiUrl: process.env.INTELLIGENCE_API_URL } : {}), ...(process.env.INTELLIGENCE_GATEWAY_WS_URL ? { wsUrl: process.env.INTELLIGENCE_GATEWAY_WS_URL } : {}), }), identifyUser: () ({ id: demo-user, name: Demo User }), } : { runner: new InMemoryAgentRunner() }), // --- /copilotkit:intelligence --- }); const app createCopilotEndpoint({ runtime, basePath: /api/copilotkit, }); export const GET handle(app); export const POST handle(app); export const PATCH handle(app); export const DELETE handle(app);这里有几个值得展开的关键点Agent 注册Agno 只注册了一个 Agent键名为default。createDefaultAgent()返回ag-ui/client的HttpAgent其 URL 由AGENT_URL环境变量控制默认http://localhost:8000并拼接/agui路径Intelligence 可选接入当设置了CPK_INTELLIGENCE_API_KEY时运行时自动启用CopilotKitIntelligence线程历史与跨会话记忆未设置时则回退到InMemoryAgentRunner。identifyUser目前是demo-user的演示桩代码注释明确提示多用户部署前必须替换为基于真实认证的用户身份否则所有用户将共享同一份线程历史统一端点GET/POST/PATCH/DELETE 全部经由handle(app)转发到同一个/api/copilotkit端点。前端页面Sidebar、Suggestions 与主题色联动主界面在 src/app/page.tsx它演示了 CopilotKit v2 API 的几个核心能力CopilotSidebar默认展开的聊天侧边栏通过labels自定义欢迎语 Hi, there! Youre chatting with an Agno agent.与弹窗标题CopilotThreadsDrawerSDK 自带的线程抽屉配合CopilotChatConfigurationProvider无threadId的受控模式管理活跃线程useConfigureSuggestions预置四条引导建议分别演示生成式 UI查旧金山天气、前端工具把主题改为绿色、默认工具渲染查苹果股价与写入 Agent 状态添加一句关于 AI 的谚语useFrontendTool这是与 Python 侧set_theme_color对应的关键实现——前端用 zod 声明参数并用 handler 实际执行useFrontendTool({ name: set_theme_color, parameters: z.object({ theme_color: z .string() .describe(The theme color to set. Make sure to pick nice colors.), }), handler: async ({ theme_color }) { setThemeColor(theme_color); return Changing theme color to ${theme_color}; }, });这段代码与 agent/src/tools/frontend.py 中tool(external_executionTrue)的set_theme_color声明一一对应Agno 端只声明工具的签名与意图真正改变界面主题色的是前端这个 handler。themeColor状态通过 CSS 变量--copilot-kit-primary-color驱动整个主界面换色。共享状态读取与写入 Agent 状态页面中YourMainContent通过useAgent读取并写入 Agent 状态如proverbs数组实现前端工具改写的内容反哺给 Agent 上下文的闭环const { agent } useAgent({ agentId: default }); const state (agent.state as AgentState | undefined) ?? { proverbs: [] }; const setState (next: AgentState) agent.setState(next);常用脚本一览模板在 package.json 中预置了以下脚本均可搭配你偏好的包管理器使用脚本说明dev同时启动 UI 与 Agent 两个开发服务dev:ui仅启动 Next.js UI 服务dev:agent仅启动 Agno Agent 服务build构建 Next.js 应用生产start启动生产服务器install:agent安装 Agent 的 Python 依赖uv syncchannel保持一个 Intelligence Channel 常驻见下一节typecheck:channel使用独立的tsconfig.channel.json对 Channel 宿主做类型检查进阶把同一 Agent 挂载为 Slack/Teams Channel模板的一大亮点是同一个 Agent 既能服务 Web 聊天也能作为 Intelligence ChannelSlack、Teams 等常驻。Channel 宿主的工作机制channel-host.mts 是 Channel 的宿主进程只负责进程生命周期在每个起步模板中逐字节相同channels.mts 才是声明 Channel 的地方——添加命令、reactions 或onMention处理器都要改这个文件Channel 宿主不持有任何 provider 凭证、不暴露任何 provider 端点——Provider 边界完全由 Intelligence 掌握因此同一个文件对所有 provider 通用。启动前需要CPK_INTELLIGENCE_API_KEY并通过copilotkit init或copilotkit channels add在.copilotkit/channels.json中声明一个 Channel该 CLI 同时会把凭证写入.env。然后执行npm run channel宿主从.copilotkit/channels.json读取要挂载的 Channel若声明了多个用INTELLIGENCE_CHANNEL_NAME环境变量指定其中一个。日志含义的准确解读宿主启动完成后见 channel-host.mts日志会按每个 Channel 如实报告状态Channel name is online.—— 会话已建立并可以收发消息Channel name is declared but no provider is attached yet.—— 这是正常的等待状态不是故障。可运行copilotkit channels status查看还差哪些配置。需要特别留意上述两种消息都不能证明 provider 应用已被安装、可达或可被任何人私信。要验证 Channel 真正可用必须另行验证——先把机器人拉进会话再发一条消息测试。消息处理与 Agent 调用链channels.mts 中createDefaultChannel展示了 Channel 侧如何复用同一个 Agentexport function createDefaultChannel(channelName: string) { const channel createChannel({ identifyUser: platform, name: channelName, agent: (threadId) { const agent createDefaultAgent(); agent.threadId threadId; return agent; }, }); channel.onMessage(async ({ thread, message }) { try { await thread.runAgent({ prompt: message.contentParts?.length ? message.contentParts : message.text, }); } catch (err) { console.error([channel] agent run failed, err); await thread .post(Sorry — I hit an error handling that. Please try again.) .catch((postErr: unknown) console.error([channel] failed to post agent error, postErr), ); } }); return channel; }值得注意的实现细节使用onMessage而非onMention是因为onMessage才能让 Channel 同时适用于 1:1 平台与多人平台非提及的消息只会派发给消息处理器identifyUser: platform表示用户身份由平台方提供Channel 的历史记录不包含正在处理中的这条消息因此必须把当前消息作为prompt显式传入否则 Agent 会在零消息状态下运行出错时会在线程中回帖Sorry — I hit an error handling that. Please try again.保证用户侧有明确反馈。可选增强启用 CopilotKit Intelligence线程历史与记忆如果希望 Agent 具备持久化线程历史与跨会话记忆可以按以下步骤启用需要 Docker Desktop 运行中以及 CopilotKit Intelligence 项目的本地检出。启动本地 Intelligence 技术栈在模板目录下执行docker compose -f docker-compose.intelligence.yml up -d --wait首次运行会从源码构建 Intelligence 镜像可能耗时数分钟。该 Compose 文件docker-compose.intelligence.yml默认从兄弟目录../../../Intelligence构建可通过INTELLIGENCE_REPO环境变量指向你的检出位置。它会启动三个服务服务镜像端口说明postgrespgvector/pgvector:0.8.2-pg165483向量数据库持久化线程与记忆redisredis:7-alpine6390缓存与实时消息intelligencecpki/intelligence-composite:local4202API/ 4402GatewayIntelligence 复合服务验证服务健康docker compose -f docker-compose.intelligence.yml ps三个服务都应显示healthypostgres 通过pg_isready探活redis 通过redis-cli pingintelligence 通过curl健康检查与nc端口探测组合判定。配置环境变量在.env中添加COPILOTKIT_LICENSE_TOKENyour-license-token-here CPK_INTELLIGENCE_API_KEYyour-project-api-key-here INTELLIGENCE_API_URLhttp://localhost:4202 INTELLIGENCE_GATEWAY_WS_URLws://localhost:4402之后照常npm run dev启动即可。只要设置了CPK_INTELLIGENCE_API_KEY线程历史与记忆功能会自动激活对应 route.ts 中CopilotKitIntelligence的条件启用逻辑。停止与重置# 停止但不删除数据 docker compose -f docker-compose.intelligence.yml down # 完全重置删除 postgres 与 redis 数据卷 docker compose -f docker-compose.intelligence.yml down -v故障排查Agent 连接问题如果前端提示 Im having trouble connecting to my tools依次检查Agno Agent 是否运行在 8000 端口可在浏览器或 curl 访问http://localhost:8000/health验证OpenAI API Key 是否配置正确.env中的OPENAI_API_KEY两个服务是否都已成功启动npm run dev时 concurrently 是否同时拉起 ui 与 agent。Python 依赖问题若遇到 Python 导入错误在 agent 目录手动重新同步依赖cd agent uv sync小结本模板把 CopilotKit 与 Agno 的集成拆解为一条清晰可见的链路Agno 定义 Agent 与工具含external_execution前端工具→ AgentOS/AGUI 以 AG-UI 协议暴露在 8000 端口 → CopilotKit Runtime 路由将前端HttpAgent接入同一协议 → 前端useFrontendTool/useAgent实现前端执行与状态读写 → 可选 Intelligence 栈与 Channel 宿主把同一 Agent 复用到 Slack/Teams 与持久化线程场景。无论你是想快速跑通一个投资分析 Agent还是想把现有 Agno Agent 接入 CopilotKit 的 Web 与渠道生态都可以以此为骨架替换agent/src/agent.py中的工具与src/app/page.tsx中的界面在数分钟内完成自己的智能体应用。【免费下载链接】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),仅供参考
返回列表