
CopilotKit 与 LlamaIndex 集成指南基于 AG-UI 协议的 Python Agent 快速上手【免费下载链接】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/llamaindex/agent这一官方 Starter 包展开讲解如何用 LlamaIndex 构建一个符合 AG-UI 协议的 Python Agent并将其接入 CopilotKit 前端Next.js。读完本文你将掌握从零启动后端 Agent、配置前端工具Frontend Tools与后端工具Backend Tools、通过共享状态与生成式 UI 驱动前端实时更新的完整实战流程。这个 Starter 是什么agent 包 README 开宗明义这是一个用 LlamaIndex 和 CopilotKit 构建 AG-UI Agents 的快速上手示例后端使用 Python 实现前端则是一个配套的 Next.js 应用。AG-UIAgentic UI是 CopilotKit 项目主打的 Agent 与前端界面之间的开放协议本示例正是围绕该协议打通LlamaIndex 编排 LLM 与工具和CopilotKit 提供聊天侧边栏、共享状态、生成式 UI这两端的能力。整个示例分为两个可独立启动的部分后端位于examples/integrations/llamaindex/agent是一个基于 FastAPI LlamaIndex Workflow 的 Python 包前端位于 examples/integrations/llamaindex是一个 Next.js 16 应用通过 CopilotRuntime 连接后端 Agent。演示页本身是一个箴言Proverbs应用你可以让助手往列表中添加箴言、查询天气或直接把整个页面的主题色改掉——这三个能力恰好对应了 CopilotKit 的三大核心特性前端工具、共享状态与生成式 UI。快速启动1. 启动后端 Agent进入examples/integrations/llamaindex/agent目录按以下三步操作对应 README 中的 Running the Backendexport OPENAI_API_KEY... uv sync uv run devOPENAI_API_KEYAgent 内部使用 OpenAI 的gpt-4.1模型见 agent.py必须提供有效密钥uv sync使用 uv 按pyproject.toml与uv.lock创建 Python 虚拟环境并安装依赖uv run dev执行pyproject.toml中声明的脚本入口dev main:main实际启动 Uvicorn 服务。启动成功后FastAPI 服务监听在http://127.0.0.1:9000并提供两个端点/health健康检查以及由 Agent 路由挂载的 AG-UI 交互端点前端实际调用的是/run路径见下文前端分析。2. 启动前端回到上一级目录即examples/integrations/llamaindex安装依赖并启动开发服务器cd .. npm install npm run devpackage.json中的postinstall钩子会自动执行npm run install:agent即再次cd agent uv sync因此npm install这一步会同时准备好前后端依赖。而npm run dev通过concurrently同时拉起两个进程dev:agentcd agent uv run dev即后端 Agentdev:uinext dev --turbopack即 Next.js 前端。访问 Next.js 提供的地址即可在右侧打开的 Copilot 侧边栏中与 Agent 对话。后端实现深度解析后端的核心代码只有两个文件FastAPI 入口 main.py 与 Agent 定义 src/agent.py。FastAPI 入口与 AG-UI 路由挂载main.py 的结构非常简洁import uvicorn from dotenv import load_dotenv from fastapi import FastAPI from src.agent import agentic_chat_router app FastAPI() app.get(/health) async def health(): return {status: ok} app.include_router(agentic_chat_router) def main(): load_dotenv() uvicorn.run(main:app, host127.0.0.1, port9000, reloadTrue) if __name__ __main__: main()关键点agentic_chat_router由src/agent.py导出是一个 FastAPI 路由对象通过app.include_router(...)一次性挂载全部 AG-UI 交互端点main()中load_dotenv()会读取根目录.env文件因此除export外也可以把OPENAI_API_KEY写进.envuvicorn.run(main:app, host127.0.0.1, port9000, reloadTrue)固定监听 9000 端口并开启热重载这正是前端agent.ts中默认指向的地址。用 get_ag_ui_workflow_router 构建 Agentsrc/agent.py 通过llama_index.protocols.ag_ui提供的get_ag_ui_workflow_router将LlamaIndex Workflow包装成一个符合 AG-UI 协议的 HTTP 服务from llama_index.core.workflow import Context from llama_index.llms.openai import OpenAI from llama_index.protocols.ag_ui.events import StateSnapshotWorkflowEvent from llama_index.protocols.ag_ui.router import get_ag_ui_workflow_router agentic_chat_router get_ag_ui_workflow_router( llmOpenAI(modelgpt-4.1), frontend_tools[change_theme_color, add_proverb], backend_tools[get_weather], system_promptYou are a helpful assistant that can add proverbs to a list, get the weather for a given location, and change the background color of the chat/app background., initial_state{ proverbs: [ CopilotKit may be new, but its the best thing since sliced bread., ], }, )各参数含义如下参数值作用llmOpenAI(modelgpt-4.1)驱动 Workflow 的 LLMllama-index-llms-openai包提供 OpenAI 客户端封装frontend_tools[change_theme_color, add_proverb]声明在浏览器端执行的工具后端只负责把调用意图发给前端backend_tools[get_weather]声明在后端服务端执行的工具调用与返回都在 Python 进程中完成system_prompt见上规定 Agent 的能力边界与行为initial_state{proverbs: [...]}Agent 的初始共享状态会通过 AG-UI 的StateSnapshotWorkflowEvent事件同步给前端需要注意的是这个 starter 的initial_state仅作为后端侧的初始快照。前端 page.tsx 在useEffect中会检查agent.state.proverbs若为空则主动写入一条初始箴言从而保证前后端状态最终一致。三种工具的分工与源码注解agent.py 中定义了三类具有代表性的工具函数源码注释直接说明了它们的设计意图1. 前端工具change_theme_color同步函数def change_theme_color( theme_color: Annotated[str, The hex color value. i.e. #123456], ) - str: Change the background color of the chat. Can be any hex color value. return fChanging background to {theme_color}2. 前端工具add_proverb异步函数async def add_proverb( proverb: Annotated[str, The proverb to add. Make it witty, short and concise.], ) - str: Add a proverb to the list of proverbs. return fAdded proverb: {proverb}3. 后端工具get_weatherasync def get_weather( location: Annotated[str, The location to get the weather for.], ) - str: Get the weather for a given location. return fThe weather in {location} is sunny and 70 degrees.源码注释揭示了这套机制的精髓前两个工具有一个客户端版本真正被调用来修改背景色/添加箴言这些工具函数只需要返回一个响应字符串让它看起来像是执行了——即后端把工具调用意图转发给前端由前端useFrontendTool注册的 handler 真正执行并修改 UI 状态后端收到的返回值只用于拼装对话流get_weather是在后端服务器上执行代码的后端工具当前是桩实现注释明确说明它完全可以去调用一个天气 API——你只需要把函数体替换成真实的 HTTP 调用即可无需改动任何框架代码。三处Annotated[str, ...]参数描述会作为工具 Schema 的一部分交给 LLM帮助模型正确生成参数。工具的签名、docstring 与描述共同构成 AG-UI 协议下的工具契约。Python 包结构与依赖pyproject.toml 使用 hatchling 构建其依赖设计反映了该 Starter 的技术选型[project] name agent version 0.1.0 requires-python 3.9, 3.14 dependencies [ llama-index-core0.14,0.15, llama-index-llms-openai0.5.0,0.6.0, llama-index-protocols-ag-ui0.2.2, jsonpatch1.33, uvicorn0.27.0, fastapi0.100.0, python-dotenv1.0.0, ] [project.scripts] dev main:main各依赖在示例中扮演的角色llama-index-core提供llama_index.core.workflow.Context等 Workflow 编排能力是 Agent 运行时的基础llama-index-llms-openai提供OpenAI(modelgpt-4.1)客户端llama-index-protocols-ag-uiAG-UI 协议的关键桥梁导出get_ag_ui_workflow_router与StateSnapshotWorkflowEvent负责把 LlamaIndex Workflow 翻译成前端可消费的协议事件jsonpatch用于对 Agent 状态做增量补丁前端在agent.setState时通过 JSON Patch 语义同步差异uvicornfastapi承载 HTTP 服务python-dotenvload_dotenv()读取.env。[project.scripts]中的dev main:main正是uv run dev实际执行的入口指向main.py里的main()函数。构建配置include [main.py, src/]说明发布时只打包入口与源码目录。前端如何消费这个 AG-UI Agent虽然关联文档聚焦后端但要真正跑通Running the Frontend需要理解前端与后端的连接方式。前端的关键代码只有三个文件。1. Agent 连接配置src/agent.ts 使用ag-ui/llamaindex包创建前端侧的 Agent 客户端import { LlamaIndexAgent } from ag-ui/llamaindex; export function createDefaultAgent(): LlamaIndexAgent { return new LlamaIndexAgent({ url: (process.env.AGENT_URL || http://127.0.0.1:9000).replace(/\/$/, ) /run, }); }默认情况下它把请求发往后端 9000 端口的/run路径即get_ag_ui_workflow_router挂载的运行端点并支持通过AGENT_URL环境变量覆盖方便切换远程或容器化的后端。2. CopilotRuntime 端点route.ts 用 Hono 的 Vercel handler 暴露/api/copilotkit端点并将createDefaultAgent()注册为默认 Agent。它同时演示了可选的 Intelligence 集成当设置CPK_INTELLIGENCE_API_KEY时启用CopilotKitIntelligence提供持久化线程历史与跨会话记忆否则回退到InMemoryAgentRunner。3. 三大演示能力的前端对应page.tsx 通过useFrontendTool注册与后端声明同名同参的前端工具后端工具agent.py前端注册page.tsx真实效果change_theme_coloruseFrontendTool(change_theme_color)handler 调用setThemeColor把--copilot-kit-primary-color与页面背景色实时改为主题色add_proverbuseFrontendTool(add_proverb)handler 通过agent.setState追加箴言更新共享状态proverbs页面列表实时重渲染get_weatheruseFrontendTool(get_weather)带render回调在对话流中渲染WeatherCard生成式 UI 组件这里体现了前后端工具的完整闭环后端声明契约名称 Zod/Annotated 参数 Schema→ LLM 决定调用 → 后端把调用意图转发给前端 → 前端 handler 执行并更新 UI/状态 → 返回值回传后端继续对话。get_weather的前端注册还设置了available: false表示它不作为可主动调用的普通工具暴露给用户而是由 Agent 在合适的时机触发生成式 UI 渲染。常见问题排查关联文档所在的根目录 README 提供了两条实用的排障指引Agent 连接问题如果对话中出现 Im having trouble connecting to my tools依次检查LlamaIndex Agent 是否运行在 9000 端口、OPENAI_API_KEY是否设置正确、前后端两个服务器是否都已成功启动Python 依赖问题遇到导入错误时回到examples/integrations/llamaindex/agent目录重新执行uv sync确保虚拟环境与uv.lock保持一致。扩展方向这个 Starter 的设计使其极易扩展把get_weather的桩实现替换为真实 API 调用源码注释已明确建议即可获得真实的工具调用能力在frontend_tools与backend_tools列表中追加你自己的函数后端无需改动框架代码即可自动暴露新工具在initial_state中增加任意字段前端通过useAgent读取agent.state即可实现更复杂的共享状态场景按照examples/integrations/llamaindex/README.md的说明配置CPK_INTELLIGENCE_API_KEY后可启用持久化线程历史与跨会话记忆无需改动 Agent 代码。【免费下载链接】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),仅供参考