使用 AG-UI 为您的 Microsoft Agent Framework (Python) 代理构建前端
太长不看
本指南将介绍如何使用 AG-UI 协议和 CopilotKit 为 Microsoft Agent Framework (Python) 代理构建前端。Microsoft Agent Framework (Python) 将为 AI 代理后端提供支持,CopilotKit 将为前端提供支持,而 AG-UI 则创建一个桥梁,使前端能够与后端通信。
在正式开始之前,我们先来看看我们将要涵盖的内容:
-
了解 Microsoft Agent Framework 吗?
-
使用 CLI 设置 Microsoft Agent Framework + AG-UI + CopilotKit 代理
-
将您的 Microsoft Agent Framework 代理与后端 AG-UI 协议集成
-
使用 CopilotKit 为您的 Microsoft Agent Framework + AG-UI 代理构建前端
以下是使用 Microsoft Agent Framework (Python) + AG-UI + CopilotKit 可以构建的内容预览。
什么是微软代理框架?
Microsoft Agent Framework (MAF) 是一个开源开发工具包 (SDK) 和运行时环境,用于在 Python 和 .NET 中构建和部署 AI 代理和多代理工作流。
MAF 被认为是微软先前代理相关项目的下一代,它融合了AutoGen(用于创新的多代理编排)和Semantic Kernel(用于企业级功能和生产就绪性)的优势。
该框架的核心目的是使开发人员能够创建涉及以下方面的复杂人工智能应用程序:
-
使用大型语言模型 (LLM) 进行推理、做出决策和使用工具的独立人工智能代理。
-
复杂的多智能体系统,其中多个智能体协作解决复杂的多步骤任务。
Python 实现提供了对开发者友好的体验,非常适合快速构建和测试代理系统。
如果您想深入了解 Microsoft Agent Framework 的工作原理及其设置,请查看此处的文档:Microsoft Agent Framework 文档。
先决条件
开始之前,你需要准备以下物品:
-
OpenAI或 Azure OpenAI 凭据(适用于 Microsoft Agent Framework 代理)
-
Python 3.12+
-
Node.js 20+
-
以下任何一种软件包管理器:
- pnpm(推荐)
- npm
- 纱
- 包子
使用 CLI 设置 Microsoft Agent Framework + AG-UI + CopilotKit 代理
在本节中,您将学习如何使用 CLI 命令设置全栈 Microsoft Agent Framework (Python) 代理,该命令使用 AG-UI 协议设置后端,使用 CopilotKit 设置前端。
我们开始吧。
步骤 1:运行 CLI 命令
如果您还没有 Microsoft Agent Framework 代理,可以通过在终端中运行以下 CLI 命令快速设置一个。
npx copilotkit@latest init -m microsoft-agent-framework-py
然后按照下面的示例给你的项目命名。
步骤 2:安装依赖项
项目创建成功后,请使用您首选的包管理器安装依赖项:
# Using pnpm (recommended)
pnpm install
# Using npm
npm install
# Using yarn
yarn install
# Using bun
bun install
步骤 3:设置您的代理凭据
安装依赖项后,请设置代理凭据。如果存在以下 Azure 环境变量,后端将自动使用 Azure;否则,将回退到 OpenAI。
要设置代理凭据,请在文件夹.env内创建一个文件,agent并使用以下配置之一:
OpenAI:
OPENAI_API_KEY=sk-...your-openai-key-here...
OPENAI_CHAT_MODEL_ID=gpt-4o-mini
Azure OpenAI:
AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-4o-mini
# If you are not relying on az login:
# AZURE_OPENAI_API_KEY=...
步骤 4:运行开发服务器
然后使用您首选的包管理器启动开发服务器:
# Using pnpm
pnpm dev
# Using npm
npm run dev
# Using yarn
yarn dev
# Using bun
bun run dev
开发服务器运行后,访问http://localhost:3000/,您应该可以看到您的 Microsoft Agent Framework (Python) + AG-UI + CopilotKit 代理正在运行。
恭喜!您已成功设置全栈式 Microsoft Agent Framework 代理。您的 AI 代理现在可以使用了!您可以尝试使用聊天中的建议来测试集成效果。
将您的 Microsoft Agent Framework 代理与后端 AG-UI 协议集成
在本节中,您将学习如何将 Microsoft Agent Framework 代理与 AG-UI 协议集成,以便将其暴露给前端。
让我们开始吧。
步骤 1:安装 Microsoft Agent Framework + AG-UI 包
首先,请使用以下命令安装 Microsoft Agent Framework + AG-UI 程序包以及其他必要的依赖项。
uv pip install agent-framework, agent-framework-ag-ui, azure-identity
步骤 2:定义代理状态
安装完所需的软件包后,使用 JSON 模式定义将在后端和前端 UI 之间同步的代理状态的结构,如下所示。
from __future__ import annotations
from textwrap import dedent
from typing import Annotated
# Import core agent framework components for building conversational AI agents
from agent_framework import ChatAgent, ChatClientProtocol, ai_function
# Import CopilotKit integration layer that bridges Agent Framework with the frontend
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field
# STATE_SCHEMA: Defines the structure of agent state
STATE_SCHEMA: dict[str, object] = {
"proverbs": {
"type": "array", # Proverbs is a list/array of items
"items": {"type": "string"}, # Each item in the array is a string
"description": "Ordered list of the user's saved proverbs.", # Human-readable description
}
}
// ...
之后,使用状态配置 JSON 模式告诉代理在需要更新状态时要调用哪个工具函数,如下所示。
from __future__ import annotations
from textwrap import dedent
from typing import Annotated
# Import core agent framework components for building conversational AI agents
from agent_framework import ChatAgent, ChatClientProtocol, ai_function
# Import CopilotKit integration layer that bridges Agent Framework with the frontend
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field
// ...
# PREDICT_STATE_CONFIG: Maps state fields to the tools that modify them.
# This tells your agent which tool function to call when the agent needs to update
# a particular piece of state, and which argument of that tool contains the new state value.
PREDICT_STATE_CONFIG: dict[str, dict[str, str]] = {
"proverbs": {
"tool": "update_proverbs", # The name of the tool function that updates proverbs
"tool_argument": "proverbs", # The parameter name in that tool that receives the new proverb list
}
}
// ...
步骤 3:定义您的代理工具
定义好代理状态后,使用@ai_function装饰器配置代理工具,将其标记为 AI 代理可以调用的工具,如下所示。工具名称和描述有助于代理了解何时以及如何使用这些工具。
from __future__ import annotations
from textwrap import dedent
from typing import Annotated
# Import core agent framework components for building conversational AI agents
from agent_framework import ChatAgent, ChatClientProtocol, ai_function
# Import CopilotKit integration layer that bridges Agent Framework with the frontend
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field
// ...
# @ai_function decorator: Marks this as a tool that the AI agent can call.
# The name and description help the LLM understand when and how to use this tool.
@ai_function(
name="update_proverbs",
description=(
"Replace the entire list of proverbs with the provided values. "
"Always include every proverb you want to keep."
),
)
def update_proverbs(
proverbs: Annotated[
list[str], # The function accepts a list of strings
Field(
description=(
# This description guides the LLM on how to use this parameter correctly.
# Emphasises that this should be the COMPLETE list, not a partial update.
"The complete source of truth for the user's proverbs. "
"Maintain ordering and include the full list on each call."
)
),
],
) -> str:
"""
Persist the provided set of proverbs.
Returns:
A confirmation message indicating how many proverbs are now tracked.
"""
return f"Proverbs updated. Tracking {len(proverbs)} item(s)."
# Weather tool: Demonstrates frontend UI integration through tool calls.
# When the agent calls this function, CopilotKit can render a weather card in the UI.
@ai_function(
name="get_weather",
description="Share a quick weather update for a location. Use this to render the frontend weather card.",
)
def get_weather(
location: Annotated[str, Field(description="The city or region to describe. Use fully spelled out names.")],
) -> str:
"""
Return a short natural language weather summary.
Args:
location: The city or region name to get the weather for.
Returns:
A friendly weather description string that can be displayed to the user.
"""
# Normalise the location string: remove whitespace, capitalise words
normalized = location.strip().title() or "the requested location"
# Return a mock weather response (in production, this would query a real API)
return (
f"The weather in {normalised} is mild with a light breeze. "
"Skies are mostly clear—perfect for planning something fun."
)
# Human-in-the-loop tool: Demonstrates requiring explicit user approval before executing.
# The approval_mode="always_require" parameter ensures this function will pause execution
# and wait for the user to explicitly approve or reject the action via the UI.
@ai_function(
name="go_to_moon",
description="Request a playful human-in-the-loop confirmation before launching a mission to the moon.",
approval_mode="always_require", # CRITICAL: Forces user approval before this tool executes
)
def go_to_moon() -> str:
"""
Request human approval before continuing.
Returns:
A message confirming the approval request has been initiated.
"""
return "Mission control requested. Awaiting human approval for the lunar launch."
步骤 4:创建、配置代理并将其与 AG-UI 协议集成
定义好代理工具后,使用 Microsoft Agent Framework 创建代理。然后按照下图所示,配置代理的说明、聊天客户端和工具。
from __future__ import annotations
from textwrap import dedent
from typing import Annotated
# Import core agent framework components for building conversational AI agents
from agent_framework import ChatAgent, ChatClientProtocol, ai_function
# Import CopilotKit integration layer that bridges Agent Framework with the frontend
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field
// ...
def create_agent(chat_client: ChatClientProtocol) -> AgentFrameworkAgent:
"""
Instantiate the Microsoft Agent Framework with AG-UI.
This is the main entry point for creating the agent. It configures the base ChatAgent
with instructions and tools, then wraps it in an AgentFrameworkAgent for AG-UI integration.
Args:
chat_client: The chat client protocol implementation that handles LLM communication.
Returns:
A fully configured AgentFrameworkAgent ready to handle user interactions.
"""
# Step 1: Create the base ChatAgent with Microsoft Agent Framework
# This agent handles the core conversational logic and tool execution
base_agent = ChatAgent(
name="proverbs_agent", # Internal identifier for this agent
# System instructions: These guide the agent's behaviour throughout the conversation.
# The instructions are carefully crafted to ensure proper state management,
# tool usage, and user experience.
instructions=dedent(
"""
You help users brainstorm, organize, and refine proverbs while coordinating UI updates.
// ...
""".strip()
),
# The chat client handles actual LLM API calls (e.g., to OpenAI, Azure OpenAI, etc.)
chat_client=chat_client,
# Tools: These are the functions the agent can call to perform actions
tools=[update_proverbs, get_weather, go_to_moon],
)
// ...
之后,AgentFrameworkAgent使用 AG-UI 将代理与前端通信的中间件封装起来,如下所示。
from __future__ import annotations
from textwrap import dedent
from typing import Annotated
# Import core agent framework components for building conversational AI agents
from agent_framework import ChatAgent, ChatClientProtocol, ai_function
# Import CopilotKit integration layer that bridges Agent Framework with the frontend
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field
// ...
def create_agent(chat_client: ChatClientProtocol) -> AgentFrameworkAgent:
"""
Instantiate the Microsoft Agent Framework with AG-UI.
This is the main entry point for creating the agent. It configures the base ChatAgent
with instructions and tools, then wraps it in an AgentFrameworkAgent for CopilotKit integration.
Args:
chat_client: The chat client protocol implementation that handles LLM communication.
Returns:
A fully configured AgentFrameworkAgent ready to handle user interactions.
"""
# Step 1: Create the base ChatAgent with Microsoft Agent Framework
# This agent handles the core conversational logic and tool execution
// ...
# Step 2: Wrap the base agent in an AgentFrameworkAgent for AG-UI integration
# This wrapper adds CopilotKit-specific features like state sync and frontend coordination
return AgentFrameworkAgent(
agent=base_agent, # The underlying ChatAgent we just configured
name="CopilotKitMicrosoftAgentFrameworkAgent", # Display name for the agent
description="Manages proverbs, weather snippets, and human-in-the-loop moon launches.",
# STATE_SCHEMA tells CopilotKit what state this agent manages
state_schema=STATE_SCHEMA,
# PREDICT_STATE_CONFIG maps state fields to the tools that update them
predict_state_config=PREDICT_STATE_CONFIG,
# require_confirmation=False means the agent can update the state and continue
# without waiting for explicit user confirmation after each state change.
# This allows for smoother conversational flow.
require_confirmation=False,
)
步骤 5:构建和配置聊天客户端
使用中间件封装代理后AgentFrameworkAgent,使用 Azure OpenAI 或 OpenAI 凭据和各自的客户端构建并配置聊天客户端,如下面的./main.py文件中所示。
from __future__ import annotations
import os
# Uvicorn: ASGI server for running FastAPI applications
import uvicorn
# ChatClientProtocol: Interface that all chat clients must implement
from agent_framework._clients import ChatClientProtocol
// ...
# Load environment variables from .env file (must be done before accessing os.getenv)
# This allows developers to configure API keys and endpoints without hardcoding them
load_dotenv()
def _build_chat_client() -> ChatClientProtocol:
"""
Build and configure the appropriate chat client based on environment variables.
Returns:
ChatClientProtocol: A configured chat client ready to communicate with an LLM.
Raises:
RuntimeError: If credentials are missing or invalid.
"""
try:
# Option 1: Azure OpenAI Service
# Check if Azure OpenAI endpoint is configured
if bool(os.getenv("AZURE_OPENAI_ENDPOINT")):
# Azure OpenAI uses deployment names instead of model IDs
# Deployments are custom instances of models you create in Azure
deployment_name = os.getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_NAME", "gpt-4o-mini")
return AzureOpenAIChatClient(
# DefaultAzureCredential tries multiple authentication methods:
# 1. Environment variables (AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, etc.)
# 2. Managed Identity (if running on Azure infrastructure)
# 3. Azure CLI credentials (for local development)
credential=DefaultAzureCredential(),
# The name of your deployed model in Azure OpenAI Studio
deployment_name=deployment_name,
# Your Azure OpenAI resource endpoint (e.g., https://my-resource.openai.azure.com/)
endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
)
# Option 2: OpenAI API (public service)
# Check if OpenAI API key is configured
if bool(os.getenv("OPENAI_API_KEY")):
return OpenAIChatClient(
# Model identifier from OpenAI's catalogue (e.g., gpt-4o-mini, gpt-4, etc.)
model_id=os.getenv("OPENAI_CHAT_MODEL_ID", "gpt-4o-mini"),
# Your OpenAI API key from platform.openai.com
api_key=os.getenv("OPENAI_API_KEY"),
)
# If neither Azure nor OpenAI credentials are found, raise an error
raise ValueError("Either AZURE_OPENAI_ENDPOINT or OPENAI_API_KEY environment variable is required")
except Exception as exc: # pragma: no cover
# Catch any initialization errors and provide a helpful message
raise RuntimeError(
"Unable to initialize the chat client. Double-check your API credentials as documented in README.md."
) from exc
然后按照下图所示,将 Microsoft Agent Framework + AG-UI 代理与聊天客户端进行配置。
from __future__ import annotations
import os
# Uvicorn: ASGI server for running FastAPI applications
import uvicorn
# ChatClientProtocol: Interface that all chat clients must implement
from agent_framework._clients import ChatClientProtocol
// ...
# Step 1: Initialize the chat client
# This creates the connection to either Azure OpenAI or OpenAI API
chat_client = _build_chat_client()
# Step 2: Create the agent with the configured chat client
# This instantiates our MAF + AG-UI agent with all its tools and instructions
my_agent = create_agent(chat_client)
// ...
步骤 6:添加 FastAPI 服务器并配置代理端点
使用凭据构建聊天客户端后,添加一个 FastAPI 服务器,该服务器通过 AG-UI 公开您的 Microsoft Agent Framework 代理,如下所示。
from __future__ import annotations
import os
# Uvicorn: ASGI server for running FastAPI applications
import uvicorn
# add_agent_framework_fastapi_endpoint: CopilotKit integration that registers agent endpoints
from agent_framework_ag_ui import add_agent_framework_fastapi_endpoint
# dotenv: Loads environment variables from .env file
from dotenv import load_dotenv
# FastAPI: Modern web framework for building APIs
from fastapi import FastAPI
# CORSMiddleware: Handles Cross-Origin Resource Sharing for frontend communication
from fastapi.middleware.cors import CORSMiddleware
// ...
# Step 3: Create the FastAPI application
# FastAPI will handle HTTP requests from the frontend and route them to our agent
app = FastAPI(title="CopilotKit + Microsoft Agent Framework (Python)")
# Step 4: Configure CORS (Cross-Origin Resource Sharing)
# This is essential for allowing the frontend (running on a different port/domain)
# to communicate with this backend API
app.add_middleware(
CORSMiddleware,
# allow_origins=["*"] means accept requests from any domain
# In production, you should restrict this to your specific frontend domain(s)
# e.g., allow_origins=["https://myapp.com", "https://www.myapp.com"]
allow_origins=["*"],
# Allow cookies and authentication headers to be included in requests
allow_credentials=True,
# Allow all HTTP methods (GET, POST, PUT, DELETE, etc.)
allow_methods=["*"],
# Allow all headers (Content-Type, Authorization, etc.)
allow_headers=["*"],
)
# Step 5: Register the CopilotKit endpoint
# This function adds the necessary routes to handle CopilotKit's communication protocol
# It creates endpoints for:
# - Agent chat interactions
# - State synchronization
# - Tool execution
# - Streaming responses
add_agent_framework_fastapi_endpoint(
app=app, # The FastAPI application to add routes to
agent=my_agent, # Our configured agent instance
path="/", # Base path for CopilotKit endpoints (frontend will connect here)
)
# ============================================================================
# Main Entry Point
# ============================================================================
if __name__ == "__main__":
# This block runs only when executing this file directly (not when imported)
# It starts the web server that listens for requests from the frontend
# Read server configuration from environment variables with sensible defaults
host = os.getenv("AGENT_HOST", "0.0.0.0") # 0.0.0.0 means listen on all network interfaces
port = int(os.getenv("AGENT_PORT", "8000")) # Default to port 8000
# Start the Uvicorn ASGI server
# - "main:app" references the 'app' variable in the 'main' module
# - host and port determine where the server listens
# - reload=True enables auto-restart when code changes (great for development)
# NOTE: In production, set reload=False for better performance and stability
uvicorn.run("main:app", host=host, port=port, reload=True)
恭喜!您已成功将 Python Microsoft Agent Framework Agent 与 AG-UI 协议集成,并且它可通过http://localhost:8000(或指定端口)端点访问。
现在让我们看看如何为 AG-UI 封装的 Microsoft Agent Framework 代理添加前端。
使用 CopilotKit 为您的 Microsoft Agent Framework + AG-UI 代理构建前端
在本节中,您将学习如何使用 CopilotKit 为您的 Microsoft Agent Framework + AG-UI 代理添加前端,CopilotKit 可以在 React 运行的任何地方运行。
我们开始吧。
步骤 1:安装 CopilotKit 软件包
首先,请在前端安装最新的 CopilotKit 软件包。
npm install @copilotkit/react-ui @copilotkit/react-core @copilotkit/runtime
步骤 2:设置 Copilot 运行时实例
安装 CopilotKit 软件包后,在/api/copilotkitAPI 路由中设置 Copilot 运行时实例和 HttpAgent 实例,使前端能够向后端发出 HTTP 请求。
import {
CopilotRuntime, // Main runtime that manages agent communication
ExperimentalEmptyAdapter, // Service adapter for single-agent setups
copilotRuntimeNextJSAppRouterEndpoint, // Next.js App Router endpoint handler
} from "@copilotkit/runtime";
// Import AG-UI client for connecting to Microsoft Agent Framework agents
import { HttpAgent } from "@ag-ui/client";
// Import Next.js types for request handling
import { NextRequest } from "next/server";
// Create a service adapter for the CopilotKit runtime
const serviceAdapter = new ExperimentalEmptyAdapter();
// Create the main CopilotRuntime instance that manages communication between the frontend and backend agents
const runtime = new CopilotRuntime({
// Define the agents that will be available to the frontend
agents: {
// Configure the ADK agent connection
my_agent: new HttpAgent({
// Specify the URL where the Microsoft Agent Framework agent is running
url: "http://localhost:8000/",
}),
},
});
// Export the POST handler for the API route
export const POST = async (req: NextRequest) => {
// Create the request handler using CopilotKit's Next.js helper
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
runtime, // The CopilotRuntime instance we configured
serviceAdapter, // The service adapter for agent coordination
endpoint: "/api/copilotkit", // The endpoint path (matches this file's location)
});
return handleRequest(req);
};
步骤 3:设置 CopilotKit 提供程序
设置好 Copilot Runtime 实例后,设置管理 ADK 代理会话的 CopilotKit 提供程序组件。
要设置 CopilotKit 提供程序, [<CopilotKit>](https://docs.copilotkit.ai/reference/components/CopilotKit) 组件必须包装应用程序中与 Copilot 相关的部分。
对于大多数使用场景,最好将 CopilotKit 提供程序包装在整个应用程序周围,例如,在您的 layout.tsx文件中。
// Step 1: Import necessary types and components from Next.js and CopilotKit
import type { Metadata } from "next";
import { CopilotKit } from "@copilotkit/react-core";
import "./globals.css";
import "@copilotkit/react-ui/styles.css";
// Step 2: Define metadata for the application, used by Next.js for SEO and page headers
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
// Step 3: Define the RootLayout component, which wraps the entire application
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
// Step 4: Return the JSX structure for the layout
return (
<html lang="en">
<body className={"antialiased"}>
{/* Step 5: Wrap the children components with CopilotKit provider to enable CopilotKit functionality */}
<CopilotKit runtimeUrl="/api/copilotkit" agent="my_agent">
{children}
</CopilotKit>
</body>
</html>
);
}
步骤 4:设置 Copilot UI 组件
设置好 CopilotKit 提供程序后,设置一个 Copilot UI 组件,以便与 ADK 代理进行交互。CopilotKit 附带多个内置聊天组件,包括CopilotPopup、 CopilotSidebar和CopilotChat。
要设置 Copilot UI 组件,请将其与核心页面组件一起定义,例如在您的 page.tsx 文件中。
"use client";
import { CopilotKitCSSProperties, CopilotSidebar } from "@copilotkit/react-ui";
import { useState } from "react";
export default function CopilotKitPage() {
const [themeColor, setThemeColor] = useState("#6366f1");
// ...
return (
<main style={{ "--copilot-kit-primary-color": themeColor } as CopilotKitCSSProperties}>
<CopilotSidebar
disableSystemMessage={true}
clickOutsideToClose={false}
labels={{
title: "Popup Assistant",
initial: "👋 Hi, there! You're chatting with an agent.",
}}
suggestions={[
{
title: "Generative UI",
message: "Get the weather in San Francisco.",
},
{
title: "Frontend Tools",
message: "Set the theme to green.",
},
{
title: "Human in the Loop",
message: "Please go to the moon.",
},
{
title: "Write Agent State",
message: "Add a proverb about AI.",
},
{
title: "Update Agent State",
message: "Please remove 1 random proverb from the list if there are any.",
},
{
title: "Read Agent State",
message: "What are the proverbs?",
},
]}
>
<YourMainContent themeColor={themeColor} />
</CopilotSidebar>
</main>
);
}
步骤 5:将 Microsoft Agent Framework 代理状态与前端同步
设置好 Copilot UI 组件后,使用 CopilotKit 钩子将 Microsoft Agent Framework 代理状态与前端同步。
要将 Microsoft Agent Framework 代理状态与前端同步,请使用 CopilotKit useCoAgent 钩子, 该钩子允许您在应用程序和代理之间双向共享状态。
"use client";
import { useCoAgent } from "@copilotkit/react-core";
// State of the agent, make sure this aligns with your agent's state.
type AgentState = {
proverbs: string[];
}
function YourMainContent({ themeColor }: { themeColor: string }) {
// 🪁 Shared State: https://docs.copilotkit.ai/coagents/shared-state
const { state, setState } = useCoAgent<AgentState>({
name: "my_agent",
initialState: {
proverbs: [
"CopilotKit may be new, but it's the best thing since sliced bread.",
],
},
})
// ...
return (
// ...
)
要使用自定义 UI 组件实时渲染代理的状态、进度、输出或工具调用,您可以使用基于工具的生成式 UI。
"use client";
import { useCoAgent, useCopilotAction } from "@copilotkit/react-core";
// ...
function YourMainContent({ themeColor }: { themeColor: string }) {
// ...
//🪁 Generative UI: https://docs.copilotkit.ai/coagents/generative-ui
useCopilotAction({
name: "get_weather",
description: "Get the weather for a given location.",
available: "disabled",
parameters: [
{ name: "location", type: "string", required: true },
],
render: ({ args }) => {
return <WeatherCard location={args.location} themeColor={themeColor} />
},
});
return ( ... )
然后尝试让代理获取某个位置的天气。您应该会看到我们添加的自定义 UI 组件渲染get weather工具调用并显示传递给工具的参数。
步骤 6:在前端实现人机交互(HITL)
人机交互(HITL)允许智能体在执行过程中请求人类输入或批准,从而提高人工智能系统的可靠性和可信度。对于需要处理复杂决策或需要人类判断的行动的人工智能应用而言,这种模式至关重要。
您可以在CopilotKit 文档中了解更多关于“人机交互”的信息。
要在前端实现人机交互(HITL),您需要使用 CopilotKit 的 useCopilotKitAction 钩子renderAndWaitForResponse方法,该方法允许从渲染函数异步返回值,如src/app/page.tsx文件中所示。
import { MoonCard } from "@/components/moon";
import { useCopilotAction } from "@copilotkit/react-core";
// ...
function YourMainContent({ themeColor }: { themeColor: string }) {
// ...
// 🪁 Human In the Loop: https://docs.copilotkit.ai/pydantic-ai/human-in-the-loop
useCopilotAction(
{
name: "go_to_moon",
description: "Go to the moon on request.",
renderAndWaitForResponse: ({ respond, status }) => {
return <MoonCard themeColor={themeColor} status={status} respond={respond} />;
},
},
[themeColor],
);
return (
// ...
);
}
然后尝试让智能体去月球。此时,智能体会根据工具/操作名称触发前端操作,在执行过程中请求用户输入或反馈,并弹出选择提示(显示在聊天界面中)。然后,您可以通过点击聊天界面中的按钮进行选择,如下图所示。
步骤 7:在前端流式传输 Microsoft Agent Framework 代理响应
将 Microsoft Agent Framework 代理状态与前端同步后,即可在前端流式传输 MAF 代理响应或结果。
要在前端流式传输 Microsoft Agent Framework 代理的响应或结果,请将代理的状态字段值传递给前端组件,如下所示。
"use client";
import { useCoAgent } from "@copilotkit/react-core";
import { ProverbsCard } from "@/components/proverbs";
// State of the agent, make sure this aligns with your agent's state.
type AgentState = {
proverbs: string[];
}
function YourMainContent({ themeColor }: { themeColor: string }) {
// 🪁 Shared State: https://docs.copilotkit.ai/coagents/shared-state
const { state, setState } = useCoAgent<AgentState>({
name: "my_agent",
initialState: {
proverbs: [
"CopilotKit may be new, but it's the best thing since sliced bread.",
],
},
})
// ...
return (
<div
style={{ backgroundColor: themeColor }}
className="h-screen flex justify-center items-center flex-col transition-colors duration-300"
>
<ProverbsCard state={state} setState={setState} />
</div>
);
}
如果您查询 Microsoft Agent Framework 代理,您应该会在 UI 中看到代理的响应或结果流,如下所示。
结论
在本指南中,我们逐步介绍了如何使用 AG-UI 协议和 CopilotKit 为 Microsoft Agent Framework 代理构建前端。
虽然我们已经探索了一些功能,但我们仅仅触及了 CopilotKit 无数用例的冰山一角,从构建交互式 AI 聊天机器人到构建代理解决方案——本质上,CopilotKit 可以让您在几分钟内为您的产品添加大量有用的 AI 功能。
希望本指南能帮助您更轻松地将人工智能驱动的副驾驶功能集成到您现有的应用程序中。
在Twitter上关注 CopilotKit 并打个招呼,如果你想开发一些很酷的东西,请加入 Discord 社区。
文章来源:https://dev.to/copilotkit/build-a-frontend-for-your-microsoft-agent-framework-python-agents-with-ag-ui-4ghk






