AG-UI 클라이언트와 에이전트 엔드포인트 간에 애플리케이션 상태를 공유하기 위한 상태 이벤트 및 요청 필드를 정의합니다. 구현 및 지원되는 상태 패턴은 MAF SDK에 따라 다릅니다.
사전 요구 사항
시작하기 전에 다음을 이해해야 합니다.
상태 관리란?
AG-UI 상태는 다음을 제공할 수 있습니다.
- 공유 상태: 클라이언트와 서버 모두 애플리케이션 상태의 동기화된 보기를 유지 관리합니다.
- 클라이언트 및 서버 업데이트: 애플리케이션은 요청에서 상태를 보내고 상태 이벤트를 내보낼 수 있습니다.
- 실시간 업데이트: 변경 내용은 상태 이벤트를 사용하여 즉시 스트리밍됩니다.
- 예측 업데이트: SDK는 도구 호출 진행률을 낙관적 UI 상태로 매핑할 수 있습니다.
- 구조적 데이터: 상태는 유효성 검사를 위해 JSON 스키마를 따릅니다.
사용 사례
상태 관리는 다음을 위해 중요합니다.
- 생성 UI: 에이전트 제어 상태에 따라 UI 구성 요소 빌드
- 양식 작성: 에이전트가 정보를 수집할 때 양식 필드를 채웁니다.
- 진행률 추적: 다단계 작업의 실시간 진행률 표시
- 대화형 대시보드: 에이전트가 처리할 때 업데이트되는 데이터 표시
- 공동 작업 편집: 여러 사용자에게 일관된 상태 업데이트가 표시됩니다.
AG-UI 상태는 실행과 연결된 클라이언트 표시 JSON입니다. .NET 통합은 다음 두 가지 명시적 메커니즘을 제공합니다.
- 클라이언트가 제공한 상태를 원본
RunAgentInput에서 읽어옵니다. - 선택한 도구 호출 또는 결과를 AG-UI 상태 이벤트에
AGUIStreamOptions매핑합니다.
상태 매핑은 옵트인입니다. 임의 도구 결과는 자동으로 공유 상태가 되지 않습니다.
클라이언트 상태 읽기
MapAGUIServer은 원래의 RunAgentInput를 ChatOptions에 저장합니다. 위임 에이전트 또는 채팅 클라이언트 미들웨어는 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;
}
클라이언트 상태는 요청 입력입니다. 프롬프트, 라우팅 또는 권한 있는 작업에서 사용하기 전에 해당 셰이프 및 값의 유효성을 검사합니다.
상태 스냅샷 내보내기
도구가 전체 상태를 반환할 때 도구 실행 결과를 STATE_SNAPSHOT에 매핑합니다:
using AGUI.Server;
AGUIStreamOptions streamOptions = new AGUIStreamOptions()
.MapResultAsStateSnapshot("generate_recipe");
app.MapAGUIServer("/", agent).WithMetadata(streamOptions);
에서는 값이 여야 합니다. 도구에서 반환하기 전에 POCO, 사전 또는 컬렉션을 JsonElement 형식으로 직렬화하세요. 그러면 결과가 generate_recipe 스냅샷이 되고 클라이언트의 현재 공유 상태가 바뀝니다.
다른 결과 유형의 경우 StateSnapshotEvent를 생성하는 사용자 지정 매퍼와 함께 MapResult를 사용하세요.
상태 변화분 출력
STATE_DELTA를 반환할 경우 도구 결과를 에 매핑합니다.
AGUIStreamOptions streamOptions = new AGUIStreamOptions()
.MapResultAsStateSnapshot("create_plan")
.MapResultAsStateDelta("update_plan_step");
app.MapAGUIServer("/", agent).WithMetadata(streamOptions);
스냅샷을 사용하여 증분 변경에 대한 상태 및 델타를 초기화하거나 바꿉니다.
MapResultAsStateDelta 에는 JsonElement 결과도 필요합니다. 요소는 RFC 6902 JSON 패치 배열을 포함해야 합니다. 도구가 다른 표현을 반환하는 경우 사용자 지정 매퍼와 함께 사용합니다 MapResult .
도구 호출을 상태에 매핑
AGUIStreamOptions.MapCall 는 선택한 FunctionCallContent 이벤트를 일반 도구 호출 이벤트 이후에 내보내는 추가 AG-UI 이벤트에 매핑합니다. 도구 결과가 아닌 도구 인수에서 상태가 파생될 때 사용합니다.
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);
애플리케이션은 매핑 및 상태 셰이프를 소유합니다.
MapCall는 임의의 도구 인수를 바탕으로 상태를 유추하거나 일반적인 도구 실행을 억제하지 않습니다. 증분 업데이트를 사용하려면 기본 모델 클라이언트가 스트리밍된 도구 호출 인수를 노출하고 애플리케이션이 해당 인수 추출을 구성해야 합니다.
.NET 클라이언트의 수신 상태
AG-UI .NET 클라이언트는 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;
}
}
클라이언트는 공유 상태를 유지하고 적용한 다음, 애플리케이션에 필요할 때 나중에 요청 시 현재 상태를 전송할 책임이 있습니다.
다음 단계
상태 모델 정의
먼저 상태 구조에 대한 Pydantic 모델을 정의합니다. 이렇게 하면 형식 안전성 및 유효성 검사가 보장됩니다.
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")
상태 스키마
상태 스키마를 정의하여 상태의 구조 및 형식을 지정합니다.
state_schema = {
"recipe": {"type": "object", "description": "The current recipe"},
}
비고
상태 스키마는 type 형식과 선택적인 description 형식을 사용한 간단한 형식을 사용합니다. 실제 구조는 Pydantic 모델에 의해 정의됩니다.
예측 상태 업데이트
예측 상태 업데이트는 LLM이 툴 인수를 생성할 때 이를 상태에 반영하여 낙관적 UI 업데이트를 지원합니다.
predict_state_config = {
"recipe": {"tool": "update_recipe", "tool_argument": "recipe"},
}
이 구성은 recipe 상태 필드를 recipe 도구의 update_recipe 인수로 매핑합니다. 에이전트가 도구를 호출하면, LLM이 인수를 생성함과 동시에 인수들이 실시간으로 상태에 스트리밍됩니다.
상태 업데이트 도구 정의
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."
Important
도구 함수의 매개 변수 이름 recipe은 사용자의 tool_argument에서 predict_state_config과 일치해야 합니다.
상태 관리를 사용하여 에이전트 만들기
상태 관리를 사용하는 전체 서버 구현은 다음과 같습니다.
"""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)
주요 개념
- Pydantic 모델: 형식 안전성 및 유효성 검사를 사용하여 구조화된 상태 정의
- 상태 스키마: 상태 필드 형식을 지정하는 단순 형식
- 예측 상태 구성: 스트리밍 업데이트를 위한 도구 인수에 상태 필드를 매핑합니다.
- 상태 주입: 컨텍스트를 제공하기 위해 현재 상태가 시스템 메시지로 자동으로 삽입됩니다.
- 전체 업데이트: 도구는 델타뿐만 아니라 전체 상태를 작성해야 합니다.
- 확인 전략: 도메인에 대한 승인 메시지 사용자 지정(레시피, 문서, 작업 계획 등)
상태 이벤트의 이해
상태 스냅샷 이벤트
도구가 완료될 때 내보내는 현재 상태의 전체 스냅샷:
{
"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"
]
}
}
}
State Delta 이벤트
JSON 패치 형식을 사용하여, 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"]
}
}
]
}
비고
LLM이 도구 인수를 생성하여 낙관적 UI 업데이트를 제공하므로 상태 델타 이벤트가 실시간으로 스트리밍됩니다. 도구 실행이 완료되면 최종 상태 스냅샷이 내보내집니다.
클라이언트 구현
이 패키지는 AG-UI 서버와의 연결을 제공하여 Python 클라이언트 환경을 .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())
주요 이점
다음을 AGUIChatClient 제공합니다.
- 간소화된 연결: HTTP/SSE 통신 자동 처리
- 스레드 관리: 대화 연속성을 위한 기본 제공 스레드 ID 추적
-
에이전트 통합: 친숙한 API와
Agent원활하게 작동 - 상태 처리: 서버에서 상태 이벤트를 자동으로 해석합니다.
- .NET과의 패리티: 언어 간 일관된 경험
Tip
AGUIChatClient
Agent 대화 기록, 도구 실행 및 미들웨어 지원과 같은 에이전트 프레임워크의 기능을 최대한 활용할 수 있습니다.
예측 상태 확인
예측된 상태 변경 내용이 적용되기 전에 클라이언트 확인을 기다려야 하는 경우를 require_confirmation=True 설정합니다AgentFrameworkAgent.
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,
)
확인 이벤트를 렌더링할 때 AG-UI 클라이언트 UI에서 확인 복사본을 사용자 지정합니다.
상호 작용 예제
서버 및 클라이언트가 실행 중인 경우:
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
============================================================
Tip
:state 이 명령을 사용하여 대화 중에 언제든지 현재 상태를 볼 수 있습니다.
적용 중인 예측 상태 업데이트
예측 상태 업데이트를 사용하는 경우 predict_state_config, 클라이언트가 실시간으로 도구 인수를 생성할 때 STATE_DELTA 이벤트를 수신합니다. 이는 LLM이 도구를 실행하기 전에 발생합니다.
// 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
이를 통해 클라이언트는 에이전트가 생각하는 대로 실시간으로 낙관적 UI 업데이트를 표시하여 사용자에게 즉각적인 피드백을 제공할 수 있습니다.
휴먼 인 더 루프가 있는 상태
다음을 설정 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
)
사용하도록 설정된 경우:
- 에이전트가 도구 인수를 생성할 때 상태 업데이트 스트림(이벤트를 통한
STATE_DELTA예측 업데이트) - 에이전트가
tool_call에서RUN_FINISHED.outcome.interrupts인터럽트로 도구를 실행하기 전에 일시 중지됩니다. - 승인되면 도구가 실행되고 최종 상태가 내보내집니다(이벤트를 통해
STATE_SNAPSHOT). - 거부되면 예측 상태 변경 내용이 삭제됩니다.
고급 상태 패턴
여러 필드가 있는 복합 상태
다양한 도구를 사용하여 여러 상태 필드를 관리할 수 있습니다.
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"},
},
)
와일드카드 도구 인수 사용
도구가 복잡한 중첩 데이터를 반환하는 경우 모든 도구 인수를 상태에 매핑하는 데 사용합니다 "*" .
@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": "*"}
}
그러면 전체 도구 호출(모든 인수)이 document 상태 필드에 매핑됩니다.
모범 사례
Pydantic 모델 사용
형식 안전을 위해 구조화된 모델을 정의합니다.
class Recipe(BaseModel):
"""Use Pydantic models for structured, validated state."""
title: str
skill_level: SkillLevel
ingredients: list[Ingredient]
instructions: list[str]
이점:
- 형식 안전성: 데이터 형식의 자동 유효성 검사
- 설명서: 필드 설명은 설명서로 사용됩니다.
- IDE 지원: 자동 완성 및 형식 검사
- Serialization: 자동 JSON 변환
전체 상태 업데이트
항상 델타뿐만 아니라 전체 상태를 작성합니다.
@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."
이렇게 하면 상태 일관성과 적절한 예측 업데이트가 보장됩니다.
매개 변수 이름 일치
도구 매개 변수 이름이 구성과 일치하는지 tool_argument 확인합니다.
# 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
}
지침에 컨텍스트 제공
상태 관리에 대한 명확한 지침을 포함합니다.
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
""",
...
)
확인 UI 사용자 지정
서버에서 확인 이벤트를 렌더링할 때 AG-UI 클라이언트에서 승인 및 상태 확인 메시지를 사용자 지정합니다.
다음 단계
이제 모든 핵심 AG-UI 기능을 배웠습니다. 다음으로 다음을 수행할 수 있습니다.
- 에이전트 프레임워크 설명서 살펴보기
- 모든 AG-UI 기능을 결합한 완전한 애플리케이션 빌드
- 프로덕션에 AG-UI 서비스 배포
추가 리소스
go AG-UI 일반 텍스트 업데이트와 함께 구조화된 message.DataContent 업데이트를 내보내는 미들웨어를 사용하여 상태 관리를 구현할 수 있습니다.
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},
},
})
Tip
전체 실행 가능한 예제는 AG-UI 상태 관리 샘플을 참조하세요.