使用 AG-UI 呈现前端工具

前端工具由 AG-UI 客户端声明和执行。 服务器接收其架构,以便模型可以请求它们,但不会接收其实现。

注册前端工具

创建该工具并将其传递给由 AGUIChatClient 提供支持的代理:

using System.ComponentModel;
using AGUI.Client;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

[Description("Get the user's current location from the client device.")]
static string GetUserLocation() => "Amsterdam, Netherlands";

AITool locationTool = AIFunctionFactory.Create(
    GetUserLocation,
    name: "get_user_location");

using HttpClient httpClient = new() { BaseAddress = new Uri("http://localhost:8888") };
AGUIChatClient chatClient = new(new AGUIChatClientOptions(httpClient, "/"));
AIAgent agent = chatClient.AsAIAgent(tools: [locationTool]);

AGUIChatClient 会处理延续流:

  1. 随运行请求一并发送前端工具声明。
  2. 从服务器接收模型的工具调用请求。
  3. 在本地执行匹配函数。
  4. 将结果发送回服务器。
  5. 继续运行并流式传输最终响应。

Tip

有关完整的客户端和服务器,请参阅.NET前端工具示例。

Warning

不受信任的客户端提供的工具声明和结果是不受信任的输入。 授权哪些客户端工具可能会影响服务器端代理执行,并在将结果用于特权操作之前对其进行验证。

有关常规工具创作指南,请参阅 将函数工具与代理配合使用。

后续步骤

本教程介绍如何将前端函数工具添加到 AG-UI 客户端。 前端工具是在客户端执行的函数,允许 AI 代理与用户的本地环境交互、访问特定于客户端的数据或执行 UI作。

Prerequisites

在开始之前,请确保已完成 入门 教程并具有:

  • Python 3.11 或更高版本
  • httpx 为实现 HTTP 客户端功能而安装
  • 基本了解 AG-UI 客户端配置
  • 已配置 Azure OpenAI 服务

什么是前端工具?

前端工具是以下的功能性工具:

  • 在客户端上定义和注册
  • 在客户端的环境中执行(不在服务器上)
  • 允许 AI 代理与特定于客户端的资源进行交互
  • 将结果返回给服务器,使代理合并到响应中

常见用例:

  • 读取本地传感器数据
  • 访问客户端存储或首选项
  • 执行 UI操作
  • 与设备特定的功能交互

创建前端工具

Python 中的前端工具与后端工具定义类似,但注册到客户端:

from typing import Annotated
from pydantic import BaseModel, Field


class SensorReading(BaseModel):
    """Sensor reading from client device."""
    temperature: float
    humidity: float
    air_quality_index: int


def read_climate_sensors(
    include_temperature: Annotated[bool, Field(description="Include temperature reading")] = True,
    include_humidity: Annotated[bool, Field(description="Include humidity reading")] = True,
) -> SensorReading:
    """Read climate sensor data from the client device."""
    # Simulate reading from local sensors
    return SensorReading(
        temperature=22.5 if include_temperature else 0.0,
        humidity=45.0 if include_humidity else 0.0,
        air_quality_index=75,
    )


def change_background_color(color: Annotated[str, Field(description="Color name")] = "blue") -> str:
    """Change the console background color."""
    # Simulate UI change
    print(f"\n🎨 Background color changed to {color}")
    return f"Background changed to {color}"

使用前端工具创建 AG-UI 客户端

下面是使用前端工具的完整客户端实现:

"""AG-UI client with frontend tools."""

import asyncio
import json
import os
from typing import Annotated, AsyncIterator

import httpx
from pydantic import BaseModel, Field


class SensorReading(BaseModel):
    """Sensor reading from client device."""
    temperature: float
    humidity: float
    air_quality_index: int


# Define frontend tools
def read_climate_sensors(
    include_temperature: Annotated[bool, Field(description="Include temperature")] = True,
    include_humidity: Annotated[bool, Field(description="Include humidity")] = True,
) -> SensorReading:
    """Read climate sensor data from the client device."""
    return SensorReading(
        temperature=22.5 if include_temperature else 0.0,
        humidity=45.0 if include_humidity else 0.0,
        air_quality_index=75,
    )


def get_user_location() -> dict:
    """Get the user's current GPS location."""
    # Simulate GPS reading
    return {
        "latitude": 52.3676,
        "longitude": 4.9041,
        "accuracy": 10.0,
        "city": "Amsterdam",
    }


# Tool registry maps tool names to functions
FRONTEND_TOOLS = {
    "read_climate_sensors": read_climate_sensors,
    "get_user_location": get_user_location,
}


class AGUIClientWithTools:
    """AG-UI client with frontend tool support."""

    def __init__(self, server_url: str, tools: dict):
        self.server_url = server_url
        self.tools = tools
        self.thread_id: str | None = None

    async def send_message(self, message: str) -> AsyncIterator[dict]:
        """Send a message and handle streaming response with tool execution."""
        # Prepare tool declarations for the server
        tool_declarations = []
        for name, func in self.tools.items():
            tool_declarations.append({
                "name": name,
                "description": func.__doc__ or "",
                # Add parameter schema from function signature
            })

        request_data = {
            "messages": [
                {"role": "system", "content": "You are a helpful assistant with access to client tools."},
                {"role": "user", "content": message},
            ],
            "tools": tool_declarations,  # Send tool declarations to server
        }

        if self.thread_id:
            request_data["thread_id"] = self.thread_id

        async with httpx.AsyncClient(timeout=60.0) as client:
            async with client.stream(
                "POST",
                self.server_url,
                json=request_data,
                headers={"Accept": "text/event-stream"},
            ) as response:
                response.raise_for_status()

                async for line in response.aiter_lines():
                    if line.startswith("data: "):
                        data = line[6:]
                        try:
                            event = json.loads(data)

                            # Tool calls arrive as TOOL_CALL_START/ARGS/END events
                            # and results are streamed back as TOOL_CALL_RESULT events.
                            yield event

                            # Capture thread_id
                            if event.get("type") == "RUN_STARTED" and not self.thread_id:
                                self.thread_id = event.get("threadId")

                        except json.JSONDecodeError:
                            continue

    async def _handle_tool_call(self, event: dict, client: httpx.AsyncClient):
        """Execute frontend tool and send result back to server."""
        tool_name = event.get("toolName")
        tool_call_id = event.get("toolCallId")
        arguments = event.get("arguments", {})

        print(f"\n\033[95m[Client Tool Call: {tool_name}]\033[0m")
        print(f"  Arguments: {arguments}")

        try:
            # Execute the tool
            tool_func = self.tools.get(tool_name)
            if not tool_func:
                raise ValueError(f"Unknown tool: {tool_name}")

            result = tool_func(**arguments)

            # Convert Pydantic models to dict
            if hasattr(result, "model_dump"):
                result = result.model_dump()

            print(f"\033[94m[Client Tool Result: {result}]\033[0m")

            # In current Python AG-UI, frontend tool declarations are sent with
            # the run request. Tool-call lifecycle events are streamed back over SSE.
            print(f"Tool result for {tool_call_id}: {result}")

        except Exception as e:
            print(f"\033[91m[Tool Error: {e}]\033[0m")
            print(f"Tool error for {tool_call_id}: {e}")


async def main():
    """Main client loop with frontend tools."""
    server_url = os.environ.get("AGUI_SERVER_URL", "http://127.0.0.1:8888/")
    print(f"Connecting to AG-UI server at: {server_url}\n")

    client = AGUIClientWithTools(server_url, FRONTEND_TOOLS)

    try:
        while True:
            message = input("\nUser (:q or quit to exit): ")
            if not message.strip():
                continue

            if message.lower() in (":q", "quit"):
                break

            print()
            async for event in client.send_message(message):
                event_type = event.get("type", "")

                if event_type == "RUN_STARTED":
                    print(f"\033[93m[Run Started]\033[0m")

                elif event_type == "TEXT_MESSAGE_CONTENT":
                    print(f"\033[96m{event.get('delta', '')}\033[0m", end="", flush=True)

                elif event_type == "RUN_FINISHED":
                    print(f"\n\033[92m[Run Finished]\033[0m")

                elif event_type == "RUN_ERROR":
                    error_msg = event.get("message", "Unknown error")
                    print(f"\n\033[91m[Error: {error_msg}]\033[0m")

            print()

    except KeyboardInterrupt:
        print("\n\nExiting...")
    except Exception as e:
        print(f"\n\033[91mError: {e}\033[0m")


if __name__ == "__main__":
    asyncio.run(main())

前端工具的工作原理

协议流

  1. 客户端注册:客户端向服务器发送工具声明(名称、说明、参数)
  2. 服务器业务流程:AI 代理根据用户请求决定何时调用前端工具
  3. 工具调用事件:服务器向客户端流式传输 TOOL_CALL_START、TOOL_CALL_ARGS 和 TOOL_CALL_END 事件
  4. 客户端执行:客户端在本地执行该工具
  5. 结果事件:工具结果表示为 TOOL_CALL_RESULT 流中的事件
  6. 代理处理:服务器合并结果并继续响应

关键事件

  • TOOL_CALL_START / TOOL_CALL_ARGS / TOOL_CALL_END:服务器请求并流式传输工具调用详细信息
  • TOOL_CALL_RESULT:工具执行结果事件

预期输出

User (:q or quit to exit): What's the temperature reading from my sensors?

[Run Started]

[Client Tool Call: read_climate_sensors]
  Arguments: {'include_temperature': True, 'include_humidity': True}
[Client Tool Result: {'temperature': 22.5, 'humidity': 45.0, 'air_quality_index': 75}]

Based on your sensor readings, the current temperature is 22.5°C and the 
humidity is at 45%. These are comfortable conditions!
[Run Finished]

服务器设置

入门教程中的标准 AG-UI 服务器自动支持前端工具。 服务器端不需要更改 - 它会自动处理工具编排。

最佳做法

安全性

def access_sensitive_data() -> str:
    """Access user's sensitive data."""
    # Always check permissions first
    if not has_permission():
        return "Error: Permission denied"

    try:
        # Access data
        return "Data retrieved"
    except Exception as e:
        # Don't expose internal errors
        return "Unable to access data"

错误处理

def read_file(path: str) -> str:
    """Read a local file."""
    try:
        with open(path, "r") as f:
            return f.read()
    except FileNotFoundError:
        return f"Error: File not found: {path}"
    except PermissionError:
        return f"Error: Permission denied: {path}"
    except Exception as e:
        return f"Error reading file: {str(e)}"

异步操作

async def capture_photo() -> str:
    """Capture a photo from device camera."""
    # Simulate camera access
    await asyncio.sleep(1)
    return "photo_12345.jpg"

Troubleshooting

未调用的工具

  1. 确保将工具声明发送到服务器
  2. 验证工具说明明确指示用途
  3. 检查服务器日志以查看工具注册信息

执行错误

  1. 添加全面的错误处理
  2. 在处理之前验证参数
  3. 返回用户友好的错误消息
  4. 记录错误以进行调试

类型问题

  1. 使用 Pydantic 模型来处理复杂类型
  2. 在序列化之前将模型转换为字典
  3. 显式处理类型转换

后续步骤

其他资源

Go AG-UI 服务器可以通过禁用托管代理上的自动函数调用,将工具调用留给前端处理。

在提供程序配置中将new(0)设置为ToolAutoCall.MaximumIterationsPerRequest。 这会将函数调用留给前端处理,而不是在 Go 进程中执行它们:

// Copyright (c) Microsoft. All rights reserved.

package main

import (
    "net/http"

    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/agent/harness/toolautocall"
    "github.com/microsoft/agent-framework-go/examples/internal/demo"
    "github.com/microsoft/agent-framework-go/provider/aguiprovider"
    "github.com/microsoft/agent-framework-go/provider/foundryprovider"
)

const (
    addr      = ":8888"
    serverURL = "http://localhost:8888"
)

var _ = demo.NewLogger(
    "AG-UI Frontend Tools Server",
    "Serves a Foundry agent that delegates tool calls to the AG-UI client.",
    "Model", demo.FoundryModel,
    "URL", serverURL,
)

func main() {
    token := demo.FoundryTokenCredential()

    a := foundryprovider.NewAgent(
        demo.FoundryProjectEndpoint,
        token,
        foundryprovider.ModelDeployment(demo.FoundryModel),
        foundryprovider.AgentConfig{
            Instructions: "You are a helpful assistant.",
            ToolAutoCall: &toolautocall.Config{
                MaximumIterationsPerRequest: new(0),
            },
            Config: agent.Config{
                Name: "AGUIAssistant",
            },
        },
    )
    mux := http.NewServeMux()
    mux.Handle("/", aguiprovider.NewJSONHTTPHandler(a, aguiprovider.HandlerConfig{}))

    demo.Assistantf("AG-UI server listening at %s", serverURL)
    demo.Assistantf("Run the matching client with AGUI_SERVER_URL=%s if needed.", serverURL)
    if err := http.ListenAndServe(addr, mux); err != nil {
        demo.Panicf("AG-UI server failed on %s: %v", addr, err)
    }
}

在 aguiprovider.AgentConfig.Config.Tools 中注册客户端函数工具。 Go AG-UI 客户端将其声明发送到服务器,在本地执行返回的函数调用,并在后续请求中发送结果。 在这些调用中重复使用显式代理会话。

请参阅对应的前端工具客户端进行工具注册和执行。

Tip

有关完整的可运行示例,请参阅 AG-UI 前端工具示例 。