Бөлісу құралы:


Человек в контуре с AG-UI

В этом руководстве показано, как реализовать рабочие процессы утверждения с участием человека с использованием AG-UI в .NET. Реализация .NET использует Майкрософт.Extensions.AI ApprovalRequiredAIFunction и преобразует запросы на утверждение в "вызовы клиентских инструментов" AG-UI, которые клиент обрабатывает и на которые отвечает.

Обзор

Шаблон утверждения AG-UI C# работает следующим образом:

  1. Сервер: обертывает функции с ApprovalRequiredAIFunction для пометки их как требующих утверждения.
  2. ПО промежуточного слоя: перехватывает данные от агента и преобразует их в вызов клиентского средства
  3. Клиент: получает вызов средства, отображает пользовательский интерфейс утверждения и отправляет ответ на утверждение в качестве результата средства.
  4. Промежуточное ПО: извлекает ответ на одобрение и преобразует его в FunctionApprovalResponseContent
  5. Агент: продолжает выполнение с утверждением пользователя

Предпосылки

Реализация сервера

Определение средства, требующего одобрения

Создайте функцию и заключите ее с помощью ApprovalRequiredAIFunction:

using System.ComponentModel;
using Microsoft.Extensions.AI;

[Description("Send an email to a recipient.")]
static string SendEmail(
    [Description("The email address to send to")] string to,
    [Description("The subject line")] string subject,
    [Description("The email body")] string body)
{
    return $"Email sent to {to} with subject '{subject}'";
}

// Create approval-required tool
#pragma warning disable MEAI001 // Type is for evaluation purposes only
AITool[] tools = [new ApprovalRequiredAIFunction(AIFunctionFactory.Create(SendEmail))];
#pragma warning restore MEAI001

Создание моделей утверждения

Определите модели для запроса утверждения и ответа:

using System.Text.Json.Serialization;

public sealed class ApprovalRequest
{
    [JsonPropertyName("approval_id")]
    public required string ApprovalId { get; init; }

    [JsonPropertyName("function_name")]
    public required string FunctionName { get; init; }

    [JsonPropertyName("function_arguments")]
    public JsonElement? FunctionArguments { get; init; }

    [JsonPropertyName("message")]
    public string? Message { get; init; }
}

public sealed class ApprovalResponse
{
    [JsonPropertyName("approval_id")]
    public required string ApprovalId { get; init; }

    [JsonPropertyName("approved")]
    public required bool Approved { get; init; }
}

[JsonSerializable(typeof(ApprovalRequest))]
[JsonSerializable(typeof(ApprovalResponse))]
[JsonSerializable(typeof(Dictionary<string, object?>))]
internal partial class ApprovalJsonContext : JsonSerializerContext
{
}

Реализация промежуточного ПО для утверждения

Создайте ПО промежуточного слоя, которое преобразуется между типами утверждений Майкрософт.Extensions.AI и протоколом AG-UI:

Это важно

После преобразования ответов на одобрение, вызов средства request_approval и его результат должны быть удалены из журнала сообщений. В противном случае Azure OpenAI вернет ошибку: "tool_calls должны сопровождаться сообщениями инструментов, отвечающими на каждую tool_call_id".

using System.Runtime.CompilerServices;
using System.Text.Json;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;

// Get JsonSerializerOptions from the configured HTTP JSON options
var jsonOptions = app.Services.GetRequiredService<IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions>>().Value;

var agent = baseAgent
    .AsBuilder()
    .Use(runFunc: null, runStreamingFunc: (messages, session, options, innerAgent, cancellationToken) =>
        HandleApprovalRequestsMiddleware(
            messages,
            session,
            options,
            innerAgent,
            jsonOptions.SerializerOptions,
            cancellationToken))
    .Build();

static async IAsyncEnumerable<AgentResponseUpdate> HandleApprovalRequestsMiddleware(
    IEnumerable<ChatMessage> messages,
    AgentSession? session,
    AgentRunOptions? options,
    AIAgent innerAgent,
    JsonSerializerOptions jsonSerializerOptions,
    [EnumeratorCancellation] CancellationToken cancellationToken)
{
    // Process messages: Convert approval responses back to agent format
    var modifiedMessages = ConvertApprovalResponsesToFunctionApprovals(messages, jsonSerializerOptions);

    // Invoke inner agent
    await foreach (var update in innerAgent.RunStreamingAsync(
        modifiedMessages, session, options, cancellationToken))
    {
        // Process updates: Convert approval requests to client tool calls
        await foreach (var processedUpdate in ConvertFunctionApprovalsToToolCalls(update, jsonSerializerOptions))
        {
            yield return processedUpdate;
        }
    }

    // Local function: Convert approval responses from client back to FunctionApprovalResponseContent
    static IEnumerable<ChatMessage> ConvertApprovalResponsesToFunctionApprovals(
        IEnumerable<ChatMessage> messages,
        JsonSerializerOptions jsonSerializerOptions)
    {
        // Look for "request_approval" tool calls and their matching results
        Dictionary<string, FunctionCallContent> approvalToolCalls = [];
        FunctionResultContent? approvalResult = null;

        foreach (var message in messages)
        {
            foreach (var content in message.Contents)
            {
                if (content is FunctionCallContent { Name: "request_approval" } toolCall)
                {
                    approvalToolCalls[toolCall.CallId] = toolCall;
                }
                else if (content is FunctionResultContent result && approvalToolCalls.ContainsKey(result.CallId))
                {
                    approvalResult = result;
                }
            }
        }

        // If no approval response found, return messages unchanged
        if (approvalResult == null)
        {
            return messages;
        }

        // Deserialize the approval response
        if ((approvalResult.Result as JsonElement?)?.Deserialize(jsonSerializerOptions.GetTypeInfo(typeof(ApprovalResponse))) is not ApprovalResponse response)
        {
            return messages;
        }

        // Extract the original function call details from the approval request
        var originalToolCall = approvalToolCalls[approvalResult.CallId];

        if (originalToolCall.Arguments?.TryGetValue("request", out JsonElement request) != true ||
            request.Deserialize(jsonSerializerOptions.GetTypeInfo(typeof(ApprovalRequest))) is not ApprovalRequest approvalRequest)
        {
            return messages;
        }

        // Deserialize the function arguments from JsonElement
        var functionArguments = approvalRequest.FunctionArguments is { } args
            ? (Dictionary<string, object?>?)args.Deserialize(
                jsonSerializerOptions.GetTypeInfo(typeof(Dictionary<string, object?>)))
            : null;

        var originalFunctionCall = new FunctionCallContent(
            callId: response.ApprovalId,
            name: approvalRequest.FunctionName,
            arguments: functionArguments);

        var functionApprovalResponse = new FunctionApprovalResponseContent(
            response.ApprovalId,
            response.Approved,
            originalFunctionCall);

        // Replace/remove the approval-related messages
        List<ChatMessage> newMessages = [];
        foreach (var message in messages)
        {
            bool hasApprovalResult = false;
            bool hasApprovalRequest = false;

            foreach (var content in message.Contents)
            {
                if (content is FunctionResultContent { CallId: var callId } && callId == approvalResult.CallId)
                {
                    hasApprovalResult = true;
                    break;
                }
                if (content is FunctionCallContent { Name: "request_approval", CallId: var reqCallId } && reqCallId == approvalResult.CallId)
                {
                    hasApprovalRequest = true;
                    break;
                }
            }

            if (hasApprovalResult)
            {
                // Replace tool result with approval response
                newMessages.Add(new ChatMessage(ChatRole.User, [functionApprovalResponse]));
            }
            else if (hasApprovalRequest)
            {
                // Skip the request_approval tool call message
                continue;
            }
            else
            {
                newMessages.Add(message);
            }
        }

        return newMessages;
    }

    // Local function: Convert FunctionApprovalRequestContent to client tool calls
    static async IAsyncEnumerable<AgentResponseUpdate> ConvertFunctionApprovalsToToolCalls(
        AgentResponseUpdate update,
        JsonSerializerOptions jsonSerializerOptions)
    {
        // Check if this update contains a FunctionApprovalRequestContent
        FunctionApprovalRequestContent? approvalRequestContent = null;
        foreach (var content in update.Contents)
        {
            if (content is FunctionApprovalRequestContent request)
            {
                approvalRequestContent = request;
                break;
            }
        }

        // If no approval request, yield the update unchanged
        if (approvalRequestContent == null)
        {
            yield return update;
            yield break;
        }

        // Convert the approval request to a "client tool call"
        var functionCall = approvalRequestContent.FunctionCall;
        var approvalId = approvalRequestContent.Id;

        // Serialize the function arguments as JsonElement
        var argsElement = functionCall.Arguments?.Count > 0
            ? JsonSerializer.SerializeToElement(functionCall.Arguments, jsonSerializerOptions.GetTypeInfo(typeof(IDictionary<string, object?>)))
            : (JsonElement?)null;

        var approvalData = new ApprovalRequest
        {
            ApprovalId = approvalId,
            FunctionName = functionCall.Name,
            FunctionArguments = argsElement,
            Message = $"Approve execution of '{functionCall.Name}'?"
        };

        var approvalJson = JsonSerializer.Serialize(approvalData, jsonSerializerOptions.GetTypeInfo(typeof(ApprovalRequest)));

        // Yield a tool call update that represents the approval request
        yield return new AgentResponseUpdate(ChatRole.Assistant, [
            new FunctionCallContent(
                callId: approvalId,
                name: "request_approval",
                arguments: new Dictionary<string, object?> { ["request"] = approvalJson })
        ]);
    }
}

Реализация клиента

Реализация клиентского промежуточного ПО

Для клиента требуется двунаправленное ПО промежуточного слоя , которое обрабатывает оба:

  1. Входящий: преобразование request_approval вызовов инструмента в FunctionApprovalRequestContent
  2. ИсходящийFunctionApprovalResponseContent трафик: преобразование обратно в результаты инструмента

Это важно

Используйте объекты AdditionalProperties на AIContent для отслеживания корреляции между запросами утверждения и ответами, избегая внешних таблиц состояний.

using System.Runtime.CompilerServices;
using System.Text.Json;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.AGUI;
using Microsoft.Extensions.AI;

// Get JsonSerializerOptions from the client
var jsonSerializerOptions = JsonSerializerOptions.Default;

#pragma warning disable MEAI001 // Type is for evaluation purposes only
// Wrap the agent with approval middleware
var wrappedAgent = agent
    .AsBuilder()
    .Use(runFunc: null, runStreamingFunc: (messages, session, options, innerAgent, cancellationToken) =>
        HandleApprovalRequestsClientMiddleware(
            messages,
            session,
            options,
            innerAgent,
            jsonSerializerOptions,
            cancellationToken))
    .Build();

static async IAsyncEnumerable<AgentResponseUpdate> HandleApprovalRequestsClientMiddleware(
    IEnumerable<ChatMessage> messages,
    AgentSession? session,
    AgentRunOptions? options,
    AIAgent innerAgent,
    JsonSerializerOptions jsonSerializerOptions,
    [EnumeratorCancellation] CancellationToken cancellationToken)
{
    // Process messages: Convert approval responses back to tool results
    var processedMessages = ConvertApprovalResponsesToToolResults(messages, jsonSerializerOptions);

    // Invoke inner agent
    await foreach (var update in innerAgent.RunStreamingAsync(processedMessages, session, options, cancellationToken))
    {
        // Process updates: Convert tool calls to approval requests
        await foreach (var processedUpdate in ConvertToolCallsToApprovalRequests(update, jsonSerializerOptions))
        {
            yield return processedUpdate;
        }
    }

    // Local function: Convert FunctionApprovalResponseContent back to tool results
    static IEnumerable<ChatMessage> ConvertApprovalResponsesToToolResults(
        IEnumerable<ChatMessage> messages,
        JsonSerializerOptions jsonSerializerOptions)
    {
        List<ChatMessage> processedMessages = [];

        foreach (var message in messages)
        {
            List<AIContent> convertedContents = [];
            bool hasApprovalResponse = false;

            foreach (var content in message.Contents)
            {
                if (content is FunctionApprovalResponseContent approvalResponse)
                {
                    hasApprovalResponse = true;

                    // Get the original request_approval CallId from AdditionalProperties
                    if (approvalResponse.AdditionalProperties?.TryGetValue("request_approval_call_id", out string? requestApprovalCallId) == true)
                    {
                        var response = new ApprovalResponse
                        {
                            ApprovalId = approvalResponse.Id,
                            Approved = approvalResponse.Approved
                        };

                        var responseJson = JsonSerializer.SerializeToElement(response, jsonSerializerOptions.GetTypeInfo(typeof(ApprovalResponse)));

                        var toolResult = new FunctionResultContent(
                            callId: requestApprovalCallId,
                            result: responseJson);

                        convertedContents.Add(toolResult);
                    }
                }
                else
                {
                    convertedContents.Add(content);
                }
            }

            if (hasApprovalResponse && convertedContents.Count > 0)
            {
                processedMessages.Add(new ChatMessage(ChatRole.Tool, convertedContents));
            }
            else
            {
                processedMessages.Add(message);
            }
        }

        return processedMessages;
    }

    // Local function: Convert request_approval tool calls to FunctionApprovalRequestContent
    static async IAsyncEnumerable<AgentResponseUpdate> ConvertToolCallsToApprovalRequests(
        AgentResponseUpdate update,
        JsonSerializerOptions jsonSerializerOptions)
    {
        FunctionCallContent? approvalToolCall = null;
        foreach (var content in update.Contents)
        {
            if (content is FunctionCallContent { Name: "request_approval" } toolCall)
            {
                approvalToolCall = toolCall;
                break;
            }
        }

        if (approvalToolCall == null)
        {
            yield return update;
            yield break;
        }

        if (approvalToolCall.Arguments?.TryGetValue("request", out JsonElement request) != true ||
            request.Deserialize(jsonSerializerOptions.GetTypeInfo(typeof(ApprovalRequest))) is not ApprovalRequest approvalRequest)
        {
            yield return update;
            yield break;
        }

        var functionArguments = approvalRequest.FunctionArguments is { } args
            ? (Dictionary<string, object?>?)args.Deserialize(
                jsonSerializerOptions.GetTypeInfo(typeof(Dictionary<string, object?>)))
            : null;

        var originalFunctionCall = new FunctionCallContent(
            callId: approvalRequest.ApprovalId,
            name: approvalRequest.FunctionName,
            arguments: functionArguments);

        // Yield the original tool call first (for message history)
        yield return new AgentResponseUpdate(ChatRole.Assistant, [approvalToolCall]);

        // Create approval request with CallId stored in AdditionalProperties
        var approvalRequestContent = new FunctionApprovalRequestContent(
            approvalRequest.ApprovalId,
            originalFunctionCall);

        // Store the request_approval CallId in AdditionalProperties for later retrieval
        approvalRequestContent.AdditionalProperties ??= new Dictionary<string, object?>();
        approvalRequestContent.AdditionalProperties["request_approval_call_id"] = approvalToolCall.CallId;

        yield return new AgentResponseUpdate(ChatRole.Assistant, [approvalRequestContent]);
    }
}
#pragma warning restore MEAI001

Обработка запросов на утверждение и отправка ответов

Потребляющий код обрабатывает запросы на утверждение и автоматически продолжается до тех пор, пока не потребуется больше утверждений:

Обработка запросов на утверждение и отправка ответов

Потребляемый код обрабатывает запросы на утверждение. При получении FunctionApprovalRequestContent сохраните идентификатор request_approval CallId в AdditionalProperties ответа.

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

#pragma warning disable MEAI001 // Type is for evaluation purposes only
List<AIContent> approvalResponses = [];
List<FunctionCallContent> approvalToolCalls = [];

do
{
    approvalResponses.Clear();
    approvalToolCalls.Clear();

    await foreach (AgentResponseUpdate update in wrappedAgent.RunStreamingAsync(
        messages, session, cancellationToken: cancellationToken))
    {
        foreach (AIContent content in update.Contents)
        {
            if (content is FunctionApprovalRequestContent approvalRequest)
            {
                DisplayApprovalRequest(approvalRequest);

                // Get user approval
                Console.Write($"\nApprove '{approvalRequest.FunctionCall.Name}'? (yes/no): ");
                string? userInput = Console.ReadLine();
                bool approved = userInput?.ToUpperInvariant() is "YES" or "Y";

                // Create approval response and preserve the request_approval CallId
                var approvalResponse = approvalRequest.CreateResponse(approved);

                // Copy AdditionalProperties to preserve the request_approval_call_id
                if (approvalRequest.AdditionalProperties != null)
                {
                    approvalResponse.AdditionalProperties ??= new Dictionary<string, object?>();
                    foreach (var kvp in approvalRequest.AdditionalProperties)
                    {
                        approvalResponse.AdditionalProperties[kvp.Key] = kvp.Value;
                    }
                }

                approvalResponses.Add(approvalResponse);
            }
            else if (content is FunctionCallContent { Name: "request_approval" } requestApprovalCall)
            {
                // Track the original request_approval tool call
                approvalToolCalls.Add(requestApprovalCall);
            }
            else if (content is TextContent textContent)
            {
                Console.Write(textContent.Text);
            }
        }
    }

    // Add both messages in correct order
    if (approvalResponses.Count > 0 && approvalToolCalls.Count > 0)
    {
        messages.Add(new ChatMessage(ChatRole.Assistant, approvalToolCalls.ToArray()));
        messages.Add(new ChatMessage(ChatRole.User, approvalResponses.ToArray()));
    }
}
while (approvalResponses.Count > 0);
#pragma warning restore MEAI001

static void DisplayApprovalRequest(FunctionApprovalRequestContent approvalRequest)
{
    Console.WriteLine();
    Console.WriteLine("============================================================");
    Console.WriteLine("APPROVAL REQUIRED");
    Console.WriteLine("============================================================");
    Console.WriteLine($"Function: {approvalRequest.FunctionCall.Name}");

    if (approvalRequest.FunctionCall.Arguments != null)
    {
        Console.WriteLine("Arguments:");
        foreach (var arg in approvalRequest.FunctionCall.Arguments)
        {
            Console.WriteLine($"  {arg.Key} = {arg.Value}");
        }
    }

    Console.WriteLine("============================================================");
}

Пример взаимодействия

User (:q or quit to exit): Send an email to user@example.com about the meeting

[Run Started - Thread: thread_abc123, Run: run_xyz789]

============================================================
APPROVAL REQUIRED
============================================================

Function: SendEmail
Arguments: {"to":"user@example.com","subject":"Meeting","body":"..."}
Message: Approve execution of 'SendEmail'?

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

[Waiting for approval to execute SendEmail...]
[Run Finished - Thread: thread_abc123]

Approve this action? (yes/no): yes

[Sending approval response: APPROVED]

[Run Resumed - Thread: thread_abc123]
Email sent to user@example.com with subject 'Meeting'
[Run Finished]

Основные понятия

Шаблон клиентского инструмента

Реализация C# использует шаблон вызова клиентского инструмента:

  • Запрос на утверждение → вызов средства "request_approval" с подробными сведениями об утверждении
  • Ответ на утверждение → результат инструмента, содержащий решение пользователя
  • Middleware → Переводит между типами Майкрософт.Extensions.AI и протоколом AG-UI

Это позволяет стандартному ApprovalRequiredAIFunction шаблону работать по границе HTTP+SSE при сохранении согласованности с моделью утверждения платформы агента.

Двунаправленный паттерн промежуточного ПО

Серверное и клиентское промежуточное ПО следуют последовательной трехэтапной схеме.

  1. Обработка сообщений: преобразование входящих сообщений (ответы утверждения → FunctionApprovalResponseContent или результаты средства)
  2. Вызов внутреннего агента: вызов внутреннего агента с обработанными сообщениями
  3. Обновления процессов: преобразование исходящих обновлений (FunctionApprovalRequestContent → вызовы инструментов или наоборот)

Отслеживание состояния с помощью AdditionalProperties

Вместо внешних словарей реализация используется AdditionalProperties для AIContent объектов для отслеживания метаданных:

  • Клиент: хранит request_approval_call_id в FunctionApprovalRequestContent.AdditionalProperties
  • Сохранение ответа: копирует AdditionalProperties из запроса на ответ на сохранение корреляции
  • Преобразование: использует хранимый CallId для создания правильно коррелированных FunctionResultContent

Это сохраняет все данные корреляции в самих объектах содержимого, избегая необходимости управления внешним состоянием.

Очистка сообщений на стороне сервера

ПО промежуточного слоя сервера должно удалить сообщения протокола утверждения после обработки:

  • Проблема: Azure OpenAI требует, чтобы все обращения к инструментам получали соответствующие результаты
  • Решение: После преобразования ответов на одобрение удалите как вызов средства request_approval, так и его сообщение о результате.
  • Причина: предотвращает ошибки вида "tool_calls должны сопровождаться сообщениями об инструментах"

Дальнейшие действия

В этом руководстве показано, как реализовать рабочие процессы с участием человека с помощью AG-UI, где пользователи должны давать одобрение на выполнение инструментов перед их запуском. Это важно для конфиденциальных операций, таких как финансовые транзакции, изменения данных или действия, которые имеют значительные последствия.

Предпосылки

Прежде чем приступить к работе, убедитесь, что вы выполнили руководство по рендерингу бэкенд-инструмента и изучите следующее:

  • Создание средств функций
  • Как AG-UI передает события инструмента
  • Базовая настройка сервера и клиента

Что такое "Человек в контуре"?

Человек в процессе (HITL) — это модель, в которой агент запрашивает утверждение от пользователя перед выполнением определенных операций. С помощью AG-UI:

  • Агент создает вызовы средства как обычно
  • Вместо немедленного выполнения сервер отправляет запросы на утверждение клиенту.
  • Клиент показывает запрос и предлагает пользователю
  • Пользователь утверждает или отклоняет действие.
  • Сервер получает ответ и действует соответствующим образом.

Преимущества

  • Безопасность. Предотвращение выполнения непреднамеренных действий
  • Прозрачность: пользователи видят именно то, что агент хочет сделать
  • Управление: пользователи имеют окончательное слово по поводу конфиденциальных операций
  • Соответствие требованиям: соблюдение нормативных требований для контроля над человеком

Средства маркировки для утверждения

Чтобы запросить утверждение для инструмента, используйте параметр 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, "/")

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", будут запрашивать утверждение

Общие сведения о событиях утверждения

Когда инструменту требуется утверждение, клиент получает следующие события:

Событие запроса утверждения

{
    "type": "APPROVAL_REQUEST",
    "approvalId": "approval_abc123",
    "steps": [
        {
            "toolCallId": "call_xyz789",
            "toolCallName": "transfer_money",
            "arguments": {
                "from_account": "1234567890",
                "to_account": "0987654321",
                "amount": 500.00,
                "currency": "USD"
            }
        }
    ],
    "message": "Do you approve the following actions?"
}

Формат ответа на утверждение

Клиент должен отправить ответ на утверждение:

# Approve
{
    "type": "APPROVAL_RESPONSE",
    "approvalId": "approval_abc123",
    "approved": True
}

# Reject
{
    "type": "APPROVAL_RESPONSE",
    "approvalId": "approval_abc123",
    "approved": False
}

Клиент с поддержкой утверждения

Вот клиент, работающий с AGUIChatClient, который обрабатывает запросы на утверждение.

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

import asyncio
import os

from agent_framework import Agent, ToolCallContent, ToolResultContent
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 isinstance(content, ToolCallContent):
            print(f"\nAction {i}:")
            print(f"  Tool: \033[95m{content.name}\033[0m")
            print(f"  Arguments:")
            for key, value in (content.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(server_url=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_approval_update = None

            async for update in agent.run(message, session=thread, stream=True):
                # Check if this is an approval request
                # (Approval requests are detected by specific metadata or content markers)
                if update.additional_properties and update.additional_properties.get("requires_approval"):
                    pending_approval_update = update
                    display_approval_request(update)
                    break  # Exit the loop to handle approval

                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")

            # Handle approval request
            if pending_approval:
                approval_id = pending_approval.get("approvalId")
                user_choice = input("\nApprove this action? (yes/no): ").strip().lower()
                approved = user_choice in ("yes", "y")

                print(f"\n\033[93m[Sending approval response: {approved}]\033[0m\n")

                async for event in client.send_approval_response(approval_id, approved):
                    event_type = event.get("type", "")

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

                    elif event_type == "TOOL_CALL_RESULT":
                        content = event.get("content", "")
                        print(f"\033[94m[Tool Result: {content}]\033[0m")

                    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())

Пример взаимодействия

Когда сервер и клиент запущены:

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]

Настраиваемые сообщения подтверждения

Сообщения об утверждении можно настроить, предоставив настраиваемую стратегию подтверждения:

from typing import Any
from agent_framework_ag_ui import AgentFrameworkAgent, ConfirmationStrategy


class BankingConfirmationStrategy(ConfirmationStrategy):
    """Custom confirmation messages for banking operations."""

    def on_approval_accepted(self, steps: list[dict[str, Any]]) -> str:
        """Message when user approves the action."""
        tool_name = steps[0].get("toolCallName", "action")
        return f"Thank you for confirming. Proceeding with {tool_name}..."

    def on_approval_rejected(self, steps: list[dict[str, Any]]) -> str:
        """Message when user rejects the action."""
        return "Action cancelled. No changes have been made to your account."

    def on_state_confirmed(self) -> str:
        """Message when state changes are confirmed."""
        return "Changes confirmed and applied."

    def on_state_rejected(self) -> str:
        """Message when state changes are rejected."""
        return "Changes discarded."


# Use custom strategy
wrapped_agent = AgentFrameworkAgent(
    agent=agent,
    require_confirmation=True,
    confirmation_strategy=BankingConfirmationStrategy(),
)

Лучшие практики

Очистка описаний инструментов

Предоставьте подробные описания, чтобы пользователи понимали, что они одобряют.

@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

Дальнейшие действия

Дополнительные ресурсы