人工干预与 AG-UI 结合

是否需要对某个工具进行审批,仍由 MAF 工具审批负责决定。 AG-UI 将审批请求传输到客户端,并将客户端的决定发回服务器。

有关审批策略、条件规则和通用安全指南,请参阅 在人工参与审批的情况下使用函数工具。

需要审批

用 ApprovalRequiredAIFunction 包装 MAF 函数,并正常公开智能体:

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

AIFunction deleteFile = AIFunctionFactory.Create(
    (string path) => $"Deleted {path}",
    name: "delete_file",
    description: "Delete a file.");

AITool approvalRequiredTool = new ApprovalRequiredAIFunction(deleteFile);
AIAgent agent = chatClient.AsAIAgent(tools: [approvalRequiredTool]);

app.MapAGUIServer("/", agent);

当模型调用该工具时,AG-UI 适配器使用工具调用中断完成运行,而不是执行函数。

处理来自 .NET 客户端的中断

AGUIChatClient 将中断显示为 ToolApprovalRequestContent。 使用正常的 MAF 审批类型创建和发送响应:

ToolApprovalRequestContent? request = null;

await foreach (AgentResponseUpdate update in
    remoteAgent.RunStreamingAsync(messages, session))
{
    request ??= update.Contents
        .OfType<ToolApprovalRequestContent>()
        .FirstOrDefault();
}

if (request is not null)
{
    ToolApprovalResponseContent response = request.CreateResponse(approved: true);
    ChatMessage resume = new(ChatRole.User, [response]);

    await foreach (AgentResponseUpdate update in
        remoteAgent.RunStreamingAsync([resume], session))
    {
        // Process the resumed response.
    }
}

发送响应时重复使用相同的 AgentSession 内容,以便客户端可以继续中断的运行。 使用 approved: false 拒接来电。 适配器将 MAF 响应转换成标准的 AG-UI resume 负载。

后续步骤

本教程介绍如何使用 AG-UI 实现人为介入的工作流,其中用户必须在工具执行前批准这些执行。 这对于敏感操作(如财务交易、数据修改或具有重大后果的操作)至关重要。

Prerequisites

在开始之前,请确保已完成 后端工具呈现 教程并了解:

  • 如何创建函数工具
  • AG-UI 如何处理工具事件流
  • 基本服务器和客户端设置

什么是“人工干预”?

人机交互(HITL)是一种模式,其中代理在执行某些操作之前请求用户批准。 使用 AG-UI:

  • 代理会像往常一样生成工具调用
  • 服务器不会立即执行,而是将审批请求发送到客户端
  • 客户端显示请求并提示用户
  • 用户批准或拒绝操作
  • 服务器接收响应并相应地继续

Benefits

  • 安全:防止意外的操作被执行
  • 透明度:用户确切地看到代理想要执行的作
  • 控制:用户对敏感操作有最终决定权
  • 合规性:满足人工监督的法规要求

用于审批的标记工具

如若要求对某个工具进行审批,请在 approval_mode 修饰器中使用 @tool 参数:

from agent_framework import tool
from typing import Annotated
from pydantic import Field


@tool(approval_mode="always_require")
def send_email(
    to: Annotated[str, Field(description="Email recipient address")],
    subject: Annotated[str, Field(description="Email subject line")],
    body: Annotated[str, Field(description="Email body content")],
) -> str:
    """Send an email to the specified recipient."""
    # Send email logic here
    return f"Email sent to {to} with subject '{subject}'"


@tool(approval_mode="always_require")
def delete_file(
    filepath: Annotated[str, Field(description="Path to the file to delete")],
) -> str:
    """Delete a file from the filesystem."""
    # Delete file logic here
    return f"File {filepath} has been deleted"

审批模式

  • always_require:在执行前始终请求审批
  • never_require:从不请求审批(默认行为)
  • conditional:根据某些条件(自定义逻辑)请求审批

使用 Human-in-the-Loop 创建服务器

下面是一个完整的服务器实现,其中包含审批所需的工具:

"""AG-UI server with human-in-the-loop."""

import os
from typing import Annotated

from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatCompletionClient
from agent_framework_ag_ui import AgentFrameworkAgent, add_agent_framework_fastapi_endpoint
from azure.identity import AzureCliCredential
from fastapi import FastAPI
from pydantic import Field


# Tools that require approval
@tool(approval_mode="always_require")
def transfer_money(
    from_account: Annotated[str, Field(description="Source account number")],
    to_account: Annotated[str, Field(description="Destination account number")],
    amount: Annotated[float, Field(description="Amount to transfer")],
    currency: Annotated[str, Field(description="Currency code")] = "USD",
) -> str:
    """Transfer money between accounts."""
    return f"Transferred {amount} {currency} from {from_account} to {to_account}"


@tool(approval_mode="always_require")
def cancel_subscription(
    subscription_id: Annotated[str, Field(description="Subscription identifier")],
) -> str:
    """Cancel a subscription."""
    return f"Subscription {subscription_id} has been cancelled"


# Regular tools (no approval required)
@tool
def check_balance(
    account: Annotated[str, Field(description="Account number")],
) -> str:
    """Check account balance."""
    # Simulated balance check
    return f"Account {account} balance: $5,432.10 USD"


# Read required configuration
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
deployment_name = os.environ.get("AZURE_OPENAI_CHAT_COMPLETION_MODEL")

if not endpoint:
    raise ValueError("AZURE_OPENAI_ENDPOINT environment variable is required")
if not deployment_name:
    raise ValueError("AZURE_OPENAI_CHAT_COMPLETION_MODEL environment variable is required")

chat_client = OpenAIChatCompletionClient(
    model=deployment_name,
    azure_endpoint=endpoint,
    api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
    credential=AzureCliCredential(),
)

# Create agent with tools
agent = Agent(
    name="BankingAssistant",
    instructions="You are a banking assistant. Help users with their banking needs. Always confirm details before performing transfers.",
    client=chat_client,
    tools=[transfer_money, cancel_subscription, check_balance],
)

# Wrap agent to enable human-in-the-loop
wrapped_agent = AgentFrameworkAgent(
    agent=agent,
    require_confirmation=True,  # Enable human-in-the-loop
)

# Create FastAPI app
app = FastAPI(title="AG-UI Banking Assistant")
add_agent_framework_fastapi_endpoint(
    app,
    wrapped_agent,
    "/",
    single_user=True,
)

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8888)

关键概念

  • AgentFrameworkAgent 包装器:启用 AG-UI 协议功能,例如人工干预
  • require_confirmation=True:激活标记工具的审批工作流
  • 工具级控制:只有带有 approval_mode="always_require" 标记的工具将请求批准

了解审批中断

当工具需要批准时,此次运行会以标准的 AG-UI 中断结束。

审批中断

{
  "type": "RUN_FINISHED",
  "threadId": "thread-1",
  "runId": "run-1",
  "outcome": {
    "type": "interrupt",
    "interrupts": [
      {
        "id": "approval-1",
        "reason": "tool_call",
        "message": "Approve tool call transfer_money?",
        "toolCallId": "call-1",
        "responseSchema": {
          "type": "object",
          "properties": {
            "accepted": { "type": "boolean" },
            "arguments": { "type": "object" }
          },
          "required": ["accepted"]
        },
        "metadata": {
          "agent_framework": {
            "type": "function_approval_request",
            "function_call": {
              "call_id": "call-1",
              "name": "transfer_money",
              "arguments": {
                "from_account": "1234567890",
                "to_account": "0987654321",
                "amount": 500.00,
                "currency": "USD"
              }
            }
          }
        }
      }
    ]
  }
}

工具审批中断使用 reason: "tool_call" 并包含 toolCallId。 来自ChatResponseUpdate的最终AGUIChatClient保留outcome中的interrupts和additional_properties值。 Interrupt 和 ResumeEntry 协议类型来自 ag_ui.core,而不是特定于代理框架的模型。

简历格式

使用规范的 resume 数组恢复同一个线程。 用于 accepted: false 拒绝操作,同时允许代理继续。 在没有有效负载的情况下使用 status: "cancelled" 可取消中断的运行。

{
  "threadId": "thread-1",
  "messages": [],
  "resume": [
    {
      "interruptId": "approval-1",
      "status": "resolved",
      "payload": {
        "accepted": true
      }
    }
  ]
}

支持审批流程的客户端

使用 AGUIChatClient 来处理审批请求的客户端如下:

"""AG-UI client with human-in-the-loop support."""

import asyncio
import os

from agent_framework import Agent
from agent_framework_ag_ui import AGUIChatClient


def display_approval_request(update) -> None:
    """Display approval request details to the user."""
    print("\n\033[93m" + "=" * 60 + "\033[0m")
    print("\033[93mAPPROVAL REQUIRED\033[0m")
    print("\033[93m" + "=" * 60 + "\033[0m")

    # Display tool call details from update contents
    for i, content in enumerate(update.contents, 1):
        if content.type == "function_approval_request":
            function_call = content.function_call
            print(f"\nAction {i}:")
            print(f"  Tool: \033[95m{function_call.name}\033[0m")
            print(f"  Arguments:")
            for key, value in (function_call.arguments or {}).items():
                print(f"    {key}: {value}")

    print("\n\033[93m" + "=" * 60 + "\033[0m")


async def main():
    """Main client loop with approval handling."""
    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")

    # Create AG-UI chat client
    chat_client = AGUIChatClient(endpoint=server_url)

    # Create agent with the chat client
    agent = Agent(
        name="ClientAgent",
        client=chat_client,
        instructions="You are a helpful assistant.",
    )

    # Get a thread for conversation continuity
    thread = agent.create_session()

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

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

            print("\nAssistant: ", end="", flush=True)
            pending_interrupts = []

            async for update in agent.run(message, session=thread, stream=True):
                # Check if this update carries an approval request.
                if any(content.type == "function_approval_request" for content in update.contents):
                    display_approval_request(update)

                if update.text:
                    print(f"\033[96m{update.text}\033[0m", end="", flush=True)

                properties = update.additional_properties or {}
                outcome = properties.get("outcome")
                if isinstance(outcome, dict) and outcome.get("type") == "interrupt":
                    pending_interrupts = outcome.get("interrupts", [])

            if pending_interrupts:
                resume_entries = []
                for interrupt in pending_interrupts:
                    prompt = interrupt.get("message", "Approve this action?")
                    user_choice = input(f"\n{prompt} (yes/no): ").strip().lower()
                    resume_entries.append({
                        "interruptId": interrupt["id"],
                        "status": "resolved",
                        "payload": {"accepted": user_choice in ("yes", "y")},
                    })

                print("\nAssistant: ", end="", flush=True)
                async for update in agent.run(
                    [],
                    session=thread,
                    stream=True,
                    options={
                        "available_interrupts": pending_interrupts,
                        "resume": resume_entries,
                    },
                ):
                    if update.text:
                        print(f"\033[96m{update.text}\033[0m", end="", flush=True)

            print()

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


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

示例交互

在服务器和客户端运行的情况下:

User (:q or quit to exit): Transfer $500 from account 1234567890 to account 0987654321

[Run Started]
============================================================
APPROVAL REQUIRED
============================================================

Action 1:
  Tool: transfer_money
  Arguments:
    from_account: 1234567890
    to_account: 0987654321
    amount: 500.0
    currency: USD

============================================================

Approve this action? (yes/no): yes

[Sending approval response: True]

[Tool Result: Transferred 500.0 USD from 1234567890 to 0987654321]
The transfer of $500 from account 1234567890 to account 0987654321 has been completed successfully.
[Run Finished]

如果用户拒绝:

Approve this action? (yes/no): no

[Sending approval response: False]

I understand. The transfer has been cancelled and no money was moved.
[Run Finished]

自定义确认消息

在渲染来自服务器的审批中断时,可在 AG-UI 客户端界面中自定义审批和确认消息。 Python AgentFrameworkAgent 公开审批请求和中断元数据;它不接受服务器端确认策略对象。

最佳做法

清晰的工具说明

提供详细说明,以便用户了解他们正在批准的内容:

@tool(approval_mode="always_require")
def delete_database(
    database_name: Annotated[str, Field(description="Name of the database to permanently delete")],
) -> str:
    """
    Permanently delete a database and all its contents.

    WARNING: This action cannot be undone. All data in the database will be lost.
    Use with extreme caution.
    """
    # Implementation
    pass

细粒度审批

请求对单个敏感操作进行审批,而不是批处理。

# Good: Individual approval per transfer
@tool(approval_mode="always_require")
def transfer_money(...): pass

# Avoid: Batching multiple sensitive operations
# Users should approve each operation separately

信息性论据

使用描述性参数名称并提供上下文:

@tool(approval_mode="always_require")
def purchase_item(
    item_name: Annotated[str, Field(description="Name of the item to purchase")],
    quantity: Annotated[int, Field(description="Number of items to purchase")],
    price_per_item: Annotated[float, Field(description="Price per item in USD")],
    total_cost: Annotated[float, Field(description="Total cost including tax and shipping")],
) -> str:
    """Purchase items from the store."""
    pass

超时处理

为审批请求设置合适的超时:

# Client side
async with httpx.AsyncClient(timeout=120.0) as client:  # 2 minutes for user to respond
    # Handle approval
    pass

选择性审批

可以将需要审批的工具与不需要审批的工具结合使用:

# No approval needed for read-only operations
@tool
def get_account_balance(...): pass

@tool
def list_transactions(...): pass

# Approval required for write operations
@tool(approval_mode="always_require")
def transfer_funds(...): pass

@tool(approval_mode="always_require")
def close_account(...): pass

批量审批和取消

一个模型响应可以包含不需要审批的所需工具和工具。 解决可见中断也会根据该批次的其他工具调用的审批决定完成它们。 例如,never_require 同级执行,并且其 TOOL_CALL_RESULT 在恢复的运行中流式传输,即使需要审批的同级被拒绝。

已获批准的调用会继续通过正常的代理策略和中间件管道;批准并不会绕过准入或调度。 如果在恢复授予时函数调用被禁用,则该授予将保持为待处理状态,直到重新启用函数调用后进行显式重试。 可以重播已完成的终端同级以还原客户端状态,而无需重新执行其副作用操作。

Important

审批权限归服务器所有。 Python适配器可防止客户端共享状态(包括从线程快照重播的状态)填充或替换工具审批状态。 当 AG-UI 包装不公开其中间件的代理时,此保护也适用。 有关详细信息,请参阅 State 对象验证。

使用 status: "cancelled" 取消会中止审批恢复并清除线程的排队审批状态。 后续请求无法再次出现或执行已取消批处理中的过时工具调用。

后续步骤

其他资源

使用 tool.ApprovalRequiredFunc 将 Go 函数工具标记为需要审批。 这会在代理层配置审批,但未实现端到端的 AG-UI 审批流。

当前 Go NewJSONHTTPHandler 不会将 ToolApprovalRequestContent 转换为审批事件,也不会跨 HTTP 请求保留代理会话。 应用程序需要自定义审批传输和授权会话持久化才能完成该流程。

approveExpense := functool.MustNew(functool.Config{
    Name:        "approve_expense_report",
    Description: "Approve the expense report.",
}, func(ctx context.Context, expenseReportID string) (string, error) {
    return fmt.Sprintf("Expense report %s approved", expenseReportID), nil
})

a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
    Config: agent.Config{
        Tools: []tool.Tool{tool.ApprovalRequiredFunc(approveExpense)},
    },
})

Tip

Go 服务器示例演示了工具注册,而非完整的审批传输流程。 有关标准智能体审批合同,请参阅工具审批。