Zarządzanie stanem za pomocą AG-UI

AG-UI definiuje zdarzenia stanu i pola żądania służące do udostępniania stanu aplikacji między klientem a punktem końcowym agenta. Implementacja i obsługiwane wzorce stanu różnią się w zależności od zestawu MAF SDK.

Wymagania wstępne

Przed rozpoczęciem upewnij się, że rozumiesz:

Co to jest zarządzanie stanem?

stan AG-UI może zapewnić:

  • Stan udostępniony: zarówno klient, jak i serwer zachowują zsynchronizowany widok stanu aplikacji
  • Aktualizacje klienta i serwera: aplikacje mogą wysyłać stan w żądaniach i emitować zdarzenia stanu
  • Aktualizacje w czasie rzeczywistym: zmiany są przesyłane strumieniowo natychmiast przy użyciu zdarzeń stanowych
  • Aktualizacje predykcyjne: SDK może odwzorowywać postęp wywołania narzędzia na optymistyczny stan interfejsu użytkownika
  • Dane ustrukturyzowane: stan jest zgodny ze schematem JSON na potrzeby walidacji

Przypadki użycia

Zarządzanie stanem jest cenne dla:

  • Generatywny interfejs użytkownika: tworzenie elementów interfejsu użytkownika na podstawie stanu kontrolowanego przez agenta
  • Kompilowanie formularzy: Agent wypełnia pola formularza podczas zbierania informacji
  • Śledzenie postępu: wyświetlanie postępu operacji wieloetapowych w czasie rzeczywistym
  • Interaktywne pulpity nawigacyjne: wyświetlanie danych aktualizowanych podczas przetwarzania przez agenta
  • Edytowanie zespołowe: wielu użytkowników widzi te spójne aktualizacje stanu

Stan AG-UI to widoczny dla klienta JSON powiązany z uruchomieniem. W .NET integracja zapewnia dwa jawne mechanizmy:

  • Stan odczytu dostarczony przez klienta z lokalizacji źródłowej RunAgentInput.
  • Przypisz wybrane wywołania narzędzi lub wyniki do zdarzeń stanu AG-UI za pomocą AGUIStreamOptions.

Mapowanie stanu jest opcjonalne. Dowolne wyniki narzędzia nie stają się automatycznie współdzielonym stanem.

Odczyt stanu klienta

MapAGUIServer przechowuje pierwotny element RunAgentInput na ChatOptions. Agent delegujący lub warstwa pośrednia klienta czatu może odzyskać to za pomocą TryGetRunAgentInput:

using System.Text.Json;
using AGUI.Abstractions;
using AGUI.Server;
using Microsoft.Extensions.AI;

static bool TryGetClientState(ChatOptions options, out JsonElement state)
{
    if (options.TryGetRunAgentInput(out RunAgentInput? input) &&
        input.State is { ValueKind: not JsonValueKind.Undefined } value)
    {
        state = value;
        return true;
    }

    state = default;
    return false;
}

Stan klienta to dane wejściowe żądania. Zweryfikuj jego kształt i wartości przed użyciem ich w monitach, routingu lub operacjach uprzywilejowanych.

Emituj migawkę stanu

Przypisz wynik narzędzia do STATE_SNAPSHOT, gdy narzędzie zwraca pełny stan:

using AGUI.Server;

AGUIStreamOptions streamOptions = new AGUIStreamOptions()
    .MapResultAsStateSnapshot("generate_recipe");

app.MapAGUIServer("/", agent).WithMetadata(streamOptions);

MapResultAsStateSnapshot wymaga, aby wartość FunctionResultContent.Result była typu JsonElement. Serializuj obiekt POCO, słownik lub kolekcję do formatu JsonElement w narzędziu przed jego zwróceniem. Wynik generate_recipe staje się migawką i zastępuje bieżący współdzielony stan klienta.

W przypadku innych typów wyników należy użyć MapResult z niestandardową funkcją mapującą, która tworzy StateSnapshotEvent.

Emitowanie różnic stanu

Zamapuj wynik narzędzia na STATE_DELTA , gdy zwraca poprawkę JSON RFC 6902:

AGUIStreamOptions streamOptions = new AGUIStreamOptions()
    .MapResultAsStateSnapshot("create_plan")
    .MapResultAsStateDelta("update_plan_step");

app.MapAGUIServer("/", agent).WithMetadata(streamOptions);

Użyj migawki, aby zainicjować lub zastąpić stan i dane różnicowe na potrzeby zmian przyrostowych.

MapResultAsStateDelta również wymaga JsonElement wyniku. Element musi zawierać tablicę JSON Patch RFC 6902. Użyj MapResult z niestandardową funkcją mapującą, jeśli narzędzie zwróci inną reprezentację.

Mapuj wywołania narzędzi do stanu

AGUIStreamOptions.MapCall odwzorowuje wybrane FunctionCallContent na dodatkowe zdarzenia AG-UI emitowane po standardowych zdarzeniach wywołania narzędzia. Użyj go, gdy stan pochodzi z argumentów narzędzi, a nie z wyniku narzędzia:

AGUIStreamOptions streamOptions = new AGUIStreamOptions()
    .MapCall("write_document", call =>
    {
        if (call.Arguments?.TryGetValue("document", out object? document) is not true)
        {
            return [];
        }

        JsonElement snapshot = JsonSerializer.SerializeToElement(new { document });
        return [new StateSnapshotEvent { Snapshot = snapshot }];
    });

app.MapAGUIServer("/", agent).WithMetadata(streamOptions);

Aplikacja odpowiada za mapowanie i strukturę stanu. MapCall nie wywnioskuje stanu z dowolnych argumentów narzędzi ani nie pomija normalnego wykonywania narzędzia. Aktualizacje przyrostowe wymagają, aby klient bazowego modelu udostępniał argumenty wywołań narzędzi przesyłane strumieniowo oraz aby aplikacja konfigurowała odpowiedni mechanizm wyodrębniania argumentów.

Stan odbierania w kliencie .NET

Klient AG-UI .NET wyświetla zdarzenia protokołu stanu za pomocą metody ChatResponseUpdate.RawRepresentation:

await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, session))
{
    if (update.AsChatResponseUpdate().RawRepresentation is StateSnapshotEvent snapshot)
    {
        JsonElement state = snapshot.Snapshot;
    }
    else if (update.AsChatResponseUpdate().RawRepresentation is StateDeltaEvent delta)
    {
        JsonElement changes = delta.Delta;
    }
}

Klient jest odpowiedzialny za zachowywanie i stosowanie stanu udostępnionego, a następnie wysyłanie bieżącego stanu na późniejsze żądania, gdy aplikacja tego wymaga.

Następne kroki

Definiowanie modeli stanu

Najpierw zdefiniuj modele Pydantic dla struktury stanu. Zapewnia to bezpieczeństwo i walidację typów:

from enum import Enum
from pydantic import BaseModel, Field


class SkillLevel(str, Enum):
    """The skill level required for the recipe."""
    BEGINNER = "Beginner"
    INTERMEDIATE = "Intermediate"
    ADVANCED = "Advanced"


class CookingTime(str, Enum):
    """The cooking time of the recipe."""
    FIVE_MIN = "5 min"
    FIFTEEN_MIN = "15 min"
    THIRTY_MIN = "30 min"
    FORTY_FIVE_MIN = "45 min"
    SIXTY_PLUS_MIN = "60+ min"


class Ingredient(BaseModel):
    """An ingredient with its details."""
    icon: str = Field(..., description="Emoji icon representing the ingredient (e.g., 🥕)")
    name: str = Field(..., description="Name of the ingredient")
    amount: str = Field(..., description="Amount or quantity of the ingredient")


class Recipe(BaseModel):
    """A complete recipe."""
    title: str = Field(..., description="The title of the recipe")
    skill_level: SkillLevel = Field(..., description="The skill level required")
    special_preferences: list[str] = Field(
        default_factory=list, description="Dietary preferences (e.g., Vegetarian, Gluten-free)"
    )
    cooking_time: CookingTime = Field(..., description="The estimated cooking time")
    ingredients: list[Ingredient] = Field(..., description="Complete list of ingredients")
    instructions: list[str] = Field(..., description="Step-by-step cooking instructions")

Schemat stanu

Zdefiniuj schemat stanu, aby określić strukturę i typy stanu:

state_schema = {
    "recipe": {"type": "object", "description": "The current recipe"},
}

Note

Schemat stanu używa prostego formatu z type i opcjonalnym description. Rzeczywista struktura jest definiowana przez modele Pydantic.

Aktualizacje stanu predykcyjnego

Argumenty narzędzia strumienia aktualizacji stanu predykcyjnego są aktualizowane do stanu w miarę ich generowania przez moduł LLM, co umożliwia optymistyczne aktualizacje interfejsu użytkownika:

predict_state_config = {
    "recipe": {"tool": "update_recipe", "tool_argument": "recipe"},
}

Konfiguracja przypisuje pole stanu recipe do argumentu recipe narzędzia update_recipe. Gdy agent wywołuje narzędzie, argumenty są strumieniowo przekazywane do stanu w czasie rzeczywistym, gdy LLM je generuje.

Definiowanie narzędzia do aktualizacji stanu

Utwórz funkcję narzędzia, która akceptuje model Pydantic:

from agent_framework import tool


@tool
def update_recipe(recipe: Recipe) -> str:
    """Update the recipe with new or modified content.

    You MUST write the complete recipe with ALL fields, even when changing only a few items.
    When modifying an existing recipe, include ALL existing ingredients and instructions plus your changes.
    NEVER delete existing data - only add or modify.

    Args:
        recipe: The complete recipe object with all details

    Returns:
        Confirmation that the recipe was updated
    """
    return "Recipe updated."

Ważna

Nazwa parametru funkcji narzędzia (recipe) musi być zgodna z elementem tool_argument w pliku predict_state_config.

Tworzenie agenta za pomocą zarządzania stanem

Oto kompletna implementacja serwera z zarządzaniem stanem:

"""AG-UI server with state management."""

from agent_framework import Agent
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

# Create the chat agent with tools
agent = Agent(
    name="recipe_agent",
    instructions="""You are a helpful recipe assistant that creates and modifies recipes.

    CRITICAL RULES:
    1. You will receive the current recipe state in the system context
    2. To update the recipe, you MUST use the update_recipe tool
    3. When modifying a recipe, ALWAYS include ALL existing data plus your changes in the tool call
    4. NEVER delete existing ingredients or instructions - only add or modify
    5. After calling the tool, provide a brief conversational message (1-2 sentences)

    When creating a NEW recipe:
    - Provide all required fields: title, skill_level, cooking_time, ingredients, instructions
    - Use actual emojis for ingredient icons (🥕 🧄 🧅 🍅 🌿 🍗 🥩 🧀)
    - Leave special_preferences empty unless specified
    - Message: "Here's your recipe!" or similar

    When MODIFYING or IMPROVING an existing recipe:
    - Include ALL existing ingredients + any new ones
    - Include ALL existing instructions + any new/modified ones
    - Update other fields as needed
    - Message: Explain what you improved (e.g., "I upgraded the ingredients to premium quality")
    - When asked to "improve", enhance with:
      * Better ingredients (upgrade quality, add complementary flavors)
      * More detailed instructions
      * Professional techniques
      * Adjust skill_level if complexity changes
      * Add relevant special_preferences

    Example improvements:
    - Upgrade "chicken" → "organic free-range chicken breast"
    - Add herbs: basil, oregano, thyme
    - Add aromatics: garlic, shallots
    - Add finishing touches: lemon zest, fresh parsley
    - Make instructions more detailed and professional
    """,
    client=OpenAIChatCompletionClient(
        model=deployment_name,
        azure_endpoint=endpoint,
        api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
        credential=AzureCliCredential(),
    ),
    tools=[update_recipe],
)

# Wrap agent with state management
recipe_agent = AgentFrameworkAgent(
    agent=agent,
    name="RecipeAgent",
    description="Creates and modifies recipes with streaming state updates",
    state_schema={
        "recipe": {"type": "object", "description": "The current recipe"},
    },
    predict_state_config={
        "recipe": {"tool": "update_recipe", "tool_argument": "recipe"},
    },
)

# Create FastAPI app
app = FastAPI(title="AG-UI Recipe Assistant")
add_agent_framework_fastapi_endpoint(app, recipe_agent, "/")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8888)

Kluczowe pojęcia

  • Modele Pydantic: Definiowanie stanu strukturalnego z bezpieczeństwem typów i walidacją
  • Schemat stanu: prosty format określający typy pól stanu
  • Konfiguracja stanu predykcyjnego: mapuje pola stanu na argumenty narzędzi na potrzeby aktualizacji przesyłania strumieniowego
  • Wstrzykiwanie stanu: bieżący stan jest automatycznie wstrzykiwany jako komunikaty systemowe w celu zapewnienia kontekstu
  • Pełne aktualizacje: Narzędzia muszą zapisywać pełny stan, a nie tylko zmiany delta
  • Strategia potwierdzenia: Dostosowywanie komunikatów zatwierdzenia dla domeny (przepis, dokument, planowanie zadań itp.)

Opis zdarzeń stanu

Zdarzenie przechwycenia stanu

Kompletna migawka bieżącego stanu, emitowana po zakończeniu pracy narzędzia:

{
    "type": "STATE_SNAPSHOT",
    "snapshot": {
        "recipe": {
            "title": "Classic Pasta Carbonara",
            "skill_level": "Intermediate",
            "special_preferences": ["Authentic Italian"],
            "cooking_time": "30 min",
            "ingredients": [
                {"icon": "🍝", "name": "Spaghetti", "amount": "400g"},
                {"icon": "🥓", "name": "Guanciale or bacon", "amount": "200g"},
                {"icon": "🥚", "name": "Egg yolks", "amount": "4"},
                {"icon": "🧀", "name": "Pecorino Romano", "amount": "100g grated"},
                {"icon": "🧂", "name": "Black pepper", "amount": "To taste"}
            ],
            "instructions": [
                "Bring a large pot of salted water to boil",
                "Cut guanciale into small strips and fry until crispy",
                "Beat egg yolks with grated Pecorino and black pepper",
                "Cook spaghetti until al dente",
                "Reserve 1 cup pasta water, then drain pasta",
                "Remove pan from heat, add hot pasta to guanciale",
                "Quickly stir in egg mixture, adding pasta water to create creamy sauce",
                "Serve immediately with extra Pecorino and black pepper"
            ]
        }
    }
}

Zdarzenie zmiany stanu

Aktualizacje stanu przyrostowego w formacie JSON Patch, emitowane jako argumenty narzędzia strumieni LLM:

{
    "type": "STATE_DELTA",
    "delta": [
        {
            "op": "replace",
            "path": "/recipe",
            "value": {
                "title": "Classic Pasta Carbonara",
                "skill_level": "Intermediate",
                "cooking_time": "30 min",
                "ingredients": [
                    {"icon": "🍝", "name": "Spaghetti", "amount": "400g"}
                ],
                "instructions": ["Bring a large pot of salted water to boil"]
            }
        }
    ]
}

Note

Strumień zdarzeń różnicowych stanu w czasie rzeczywistym, ponieważ funkcja LLM generuje argumenty narzędzia, zapewniając optymistyczne aktualizacje interfejsu użytkownika. Migawka stanu końcowego jest emitowana po zakończeniu działania narzędzia.

Wdrożenie klienta

Pakiet agent_framework_ag_ui zapewnia AGUIChatClient nawiązywanie połączenia z serwerami AG-UI, przenosząc środowisko klienta języka Python do parzystości z platformą .NET:

"""AG-UI client with state management."""

import asyncio
import json
import os
from typing import Any

from agent_framework import Agent, Message, Role
from agent_framework_ag_ui import AGUIChatClient


async def main():
    """Example client with state tracking."""
    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)

    # Wrap with Agent for convenient API
    agent = Agent(
        name="ClientAgent",
        client=chat_client,
        instructions="You are a helpful assistant.",
    )

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

    # Track state locally
    state: dict[str, Any] = {}

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

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

            if message.lower() == ":state":
                print(f"\nCurrent state: {json.dumps(state, indent=2)}")
                continue

            print()
            # Stream the agent response with state
            async for update in agent.run(message, session=thread, stream=True):
                # Handle text content
                if update.text:
                    print(update.text, end="", flush=True)

                # Handle state updates surfaced through AG-UI events.
                for content in update.contents:
                    if content.type == "data" and getattr(content, "media_type", None) == "application/json":
                        print("\n[JSON state payload received]")

            print(f"\n\nCurrent state: {json.dumps(state, indent=2)}")
            print()

    except KeyboardInterrupt:
        print("\n\nExiting...")


if __name__ == "__main__":
    # Install dependencies: pip install agent-framework-ag-ui --pre
    asyncio.run(main())

Najważniejsze korzyści

AGUIChatClient zapewnia:

  • Uproszczone połączenie: automatyczna obsługa komunikacji HTTP/SSE
  • Zarządzanie wątkami: wbudowane śledzenie identyfikatorów wątków na potrzeby ciągłości konwersacji
  • Integracja agenta: bezproblemowo współpracuje ze znanym interfejsem Agent API
  • Obsługa stanu: automatyczne analizowanie zdarzeń stanu z serwera
  • Równoważność z platformą .NET: spójne środowisko w różnych językach

Wskazówka

Użyj AGUIChatClient i Agent aby w pełni korzystać z funkcji frameworku agentów, takich jak historia konwersacji, wykonywanie narzędzi i wsparcie dla middleware.

Potwierdzanie przewidywanego stanu

Ustaw require_confirmation=True w AgentFrameworkAgent, gdy przewidywane zmiany stanu mają czekać na potwierdzenie klienta przed ich zastosowaniem:

recipe_agent = AgentFrameworkAgent(
    agent=agent,
    state_schema={"recipe": {"type": "object", "description": "The current recipe"}},
    predict_state_config={"recipe": {"tool": "update_recipe", "tool_argument": "recipe"}},
    require_confirmation=True,
)

Dostosuj treść potwierdzenia w interfejsie użytkownika klienta AG-UI podczas renderowania zdarzenia potwierdzenia.

Przykładowa interakcja

Po uruchomieniu serwera i klienta:

User (:q to quit, :state to show state): I want to make a classic Italian pasta carbonara

[Run Started]
[Calling Tool: update_recipe]
[State Updated]
[State Updated]
[State Updated]
[Tool Result: Recipe updated.]
Here's your recipe!
[Run Finished]

============================================================
CURRENT STATE
============================================================

recipe:
  title: Classic Pasta Carbonara
  skill_level: Intermediate
  special_preferences: ['Authentic Italian']
  cooking_time: 30 min
  ingredients:
    - 🍝 Spaghetti: 400g
    - 🥓 Guanciale or bacon: 200g
    - 🥚 Egg yolks: 4
    - 🧀 Pecorino Romano: 100g grated
    - 🧂 Black pepper: To taste
  instructions:
    1. Bring a large pot of salted water to boil
    2. Cut guanciale into small strips and fry until crispy
    3. Beat egg yolks with grated Pecorino and black pepper
    4. Cook spaghetti until al dente
    5. Reserve 1 cup pasta water, then drain pasta
    6. Remove pan from heat, add hot pasta to guanciale
    7. Quickly stir in egg mixture, adding pasta water to create creamy sauce
    8. Serve immediately with extra Pecorino and black pepper

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

Wskazówka

Użyj polecenia , :state aby wyświetlić bieżący stan w dowolnym momencie podczas konwersacji.

Aktualizacje stanu predykcyjnego w akcji

W przypadku korzystania z aktualizacji stanu predykcyjnego za pomocą programu, klient otrzymuje zdarzenia, ponieważ usługa LLM generuje argumenty narzędzi w czasie rzeczywistym, zanim narzędzie zostanie uruchomione.

// Agent starts generating tool call for update_recipe
// Client receives STATE_DELTA events as the recipe argument streams:

// First delta - partial recipe with title
{
  "type": "STATE_DELTA",
  "delta": [{"op": "replace", "path": "/recipe", "value": {"title": "Classic Pasta"}}]
}

// Second delta - title complete with more fields
{
  "type": "STATE_DELTA",
  "delta": [{"op": "replace", "path": "/recipe", "value": {
    "title": "Classic Pasta Carbonara",
    "skill_level": "Intermediate"
  }}]
}

// Third delta - ingredients starting to appear
{
  "type": "STATE_DELTA",
  "delta": [{"op": "replace", "path": "/recipe", "value": {
    "title": "Classic Pasta Carbonara",
    "skill_level": "Intermediate",
    "cooking_time": "30 min",
    "ingredients": [
      {"icon": "🍝", "name": "Spaghetti", "amount": "400g"}
    ]
  }}]
}

// ... more deltas as the LLM generates the complete recipe

Dzięki temu klient może wyświetlać optymistyczne aktualizacje interfejsu użytkownika w czasie rzeczywistym, ponieważ agent myśli, zapewniając natychmiastową opinię użytkownikom.

Stan z interakcją człowieka w pętli

Zarządzanie stanami można połączyć z przepływami pracy zatwierdzania, ustawiając ustawienie require_confirmation=True:

recipe_agent = AgentFrameworkAgent(
    agent=agent,
    state_schema={"recipe": {"type": "object", "description": "The current recipe"}},
    predict_state_config={"recipe": {"tool": "update_recipe", "tool_argument": "recipe"}},
    require_confirmation=True,  # Require approval for state changes
)

Po włączeniu:

  1. Strumień aktualizacji stanu, gdy agent generuje argumenty narzędzi (aktualizacje predykcyjne za pośrednictwem zdarzeń STATE_DELTA )
  2. Agent wstrzymuje się przed wykonaniem narzędzia z przerwą tool_call w RUN_FINISHED.outcome.interrupts
  3. Po zatwierdzeniu narzędzie zostaje wykonane, a stan końcowy emitowany jest za pośrednictwem zdarzenia STATE_SNAPSHOT.
  4. W przypadku odrzucenia zmiany stanu predykcyjnego zostaną odrzucone

Zaawansowane wzorce stanu

Stan złożony z wieloma polami

Możesz zarządzać wieloma polami stanu za pomocą różnych narzędzi:

from pydantic import BaseModel


class TaskStep(BaseModel):
    """A single task step."""
    description: str
    status: str = "pending"
    estimated_duration: str = "5 min"


@tool
def generate_task_steps(steps: list[TaskStep]) -> str:
    """Generate task steps for a given task."""
    return f"Generated {len(steps)} steps."


@tool
def update_preferences(preferences: dict[str, Any]) -> str:
    """Update user preferences."""
    return "Preferences updated."


# Configure with multiple state fields
agent_with_multiple_state = AgentFrameworkAgent(
    agent=agent,
    state_schema={
        "steps": {"type": "array", "description": "List of task steps"},
        "preferences": {"type": "object", "description": "User preferences"},
    },
    predict_state_config={
        "steps": {"tool": "generate_task_steps", "tool_argument": "steps"},
        "preferences": {"tool": "update_preferences", "tool_argument": "preferences"},
    },
)

Używanie argumentów narzędzi z symbolami wieloznacznymi

Gdy narzędzie zwraca złożone zagnieżdżone dane, użyj polecenia "*", aby przemapować wszystkie argumenty narzędzia na stan:

@tool
def create_document(title: str, content: str, metadata: dict[str, Any]) -> str:
    """Create a document with title, content, and metadata."""
    return "Document created."


# Map all tool arguments to document state
predict_state_config = {
    "document": {"tool": "create_document", "tool_argument": "*"}
}

Spowoduje to mapowania całego wywołania narzędzia (wszystkich argumentów) na document pole stanu.

Najlepsze praktyki

Korzystanie z modeli Pydantic

Zdefiniuj modele ustrukturyzowane pod kątem bezpieczeństwa typów:

class Recipe(BaseModel):
    """Use Pydantic models for structured, validated state."""
    title: str
    skill_level: SkillLevel
    ingredients: list[Ingredient]
    instructions: list[str]

Korzyści:

  • Bezpieczeństwo typów: automatyczna walidacja typów danych
  • Dokumentacja: Opisy pól służą jako dokumentacja
  • Obsługa środowiska IDE: automatyczne uzupełnianie i sprawdzanie typów
  • Serializacja: automatyczna konwersja JSON

Pełne aktualizacje stanu

Zawsze zapisuj pełny stan, a nie tylko różnice:

@tool
def update_recipe(recipe: Recipe) -> str:
    """
    You MUST write the complete recipe with ALL fields.
    When modifying a recipe, include ALL existing ingredients and
    instructions plus your changes. NEVER delete existing data.
    """
    return "Recipe updated."

Zapewnia to spójność stanu i odpowiednie aktualizacje predykcyjne.

Dopasowywanie nazw parametrów

Upewnij się, że nazwy parametrów narzędzi są zgodne z tool_argument konfiguracją:

# Tool parameter name
def update_recipe(recipe: Recipe) -> str:  # Parameter name: 'recipe'
    ...

# Must match in predict_state_config
predict_state_config = {
    "recipe": {"tool": "update_recipe", "tool_argument": "recipe"}  # Same name
}

Podaj kontekst w instrukcjach

Dołącz jasne instrukcje dotyczące zarządzania stanem:

agent = Agent(
    instructions="""
    CRITICAL RULES:
    1. You will receive the current recipe state in the system context
    2. To update the recipe, you MUST use the update_recipe tool
    3. When modifying a recipe, ALWAYS include ALL existing data plus your changes
    4. NEVER delete existing ingredients or instructions - only add or modify
    """,
    ...
)

Dostosuj interfejs użytkownika potwierdzenia

Dostosuj komunikaty akceptacji i potwierdzenia stanu w kliencie AG-UI podczas wyświetlania zdarzeń potwierdzenia z serwera.

Dalsze kroki

Znasz już wszystkie podstawowe funkcje AG-UI! Następnie możesz:

Dodatkowe zasoby

Zarządzanie stanem w Go AG-UI można zaimplementować za pomocą middleware, które emituje ustrukturyzowane aktualizacje message.DataContent wraz ze zwykłymi aktualizacjami tekstowymi.

stateSnapshotMiddleware := agent.MiddlewareFunc(func(next agent.RunFunc, ctx context.Context, messages []*message.Message, opts ...agent.Option) iter.Seq2[*agent.ResponseUpdate, error] {
    return func(yield func(*agent.ResponseUpdate, error) bool) {
        for update, err := range next(ctx, messages, opts...) {
            if err != nil {
                yield(nil, err)
                return
            }
            if update != nil {
                // Inspect update contents and yield DataContent snapshots as needed.
            }
            if !yield(update, nil) {
                return
            }
        }
    }
})

a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
    Config: agent.Config{
        Middlewares: []agent.Middleware{stateSnapshotMiddleware},
    },
})

Wskazówka

Zobacz przykład zarządzania stanem AG-UI, aby zapoznać się z kompletnym, działającym przykładem.