AG-UI 定义状态事件和请求字段,用于在客户端和代理终结点之间共享应用程序状态。 实现和支持的状态模式因 MAF SDK 而异。
Prerequisites
在开始之前,请确保了解:
什么是状态管理?
AG-UI 状态可提供以下内容:
- 共享状态:客户端和服务器都维护应用程序状态的同步视图
- 客户端和服务器更新:应用程序可以在请求中发送状态并发出状态事件
- 实时更新:使用状态事件立即流式传输更改
- 预测更新:SDK 可以将工具调用进度映射到乐观 UI 状态
- 结构化数据:状态遵循 JSON 架构进行验证
用例
状态管理在以下场景中很有价值:
- 生成 UI:基于代理控制状态生成 UI 组件
- 表单生成:代理在收集信息时填充表单字段
- 进度跟踪:显示多步骤操作的实时进度
- 交互式仪表板:在代理处理数据时显示更新的数据
- 协作编辑:多个用户看到一致的状态更新
AG-UI 状态是与运行关联的、客户端可见的 JSON 数据。 在.NET中,集成提供了两种显式机制:
- 从源
RunAgentInput读取客户端提供的状态。 - 使用
AGUIStreamOptions将所选工具调用或结果映射到 AG-UI 状态事件。
状态映射需要主动启用。 任意工具结果不会自动成为共享状态。
读取客户端状态
MapAGUIServer 存储起源 RunAgentInput 于 ChatOptions. 如果模型需要客户端的当前状态,请用轻量级的 DelegatingAIAgent 包装基础代理,该 DelegatingAIAgent 会使用 TryGetRunAgentInput 恢复该状态,并将其添加到模型上下文中:
using System.Text.Json;
using AGUI.Abstractions;
using AGUI.Server;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
internal sealed class RecipeStateAgent(AIAgent innerAgent)
: DelegatingAIAgent(innerAgent)
{
protected override Task<AgentResponse> RunCoreAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default) =>
RunCoreStreamingAsync(messages, session, options, cancellationToken)
.ToAgentResponseAsync(cancellationToken);
protected override IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
{
if (options is ChatClientAgentRunOptions { ChatOptions: { } chatOptions } &&
chatOptions.TryGetRunAgentInput(out RunAgentInput? input) &&
input.State is { ValueKind: JsonValueKind.Object } state)
{
ChatMessage stateMessage = new(
ChatRole.System,
$"The user's current recipe state is:\n{state.GetRawText()}");
messages = [stateMessage, .. messages];
}
return InnerAgent.RunStreamingAsync(
messages,
session,
options,
cancellationToken);
}
}
AIAgent agent = new RecipeStateAgent(baseAgent);
包装器仅处理输入路径。 如以下章节所示,状态事件仍通过 AGUIStreamOptions 以声明式方式发出。
TryGetRunAgentInput 读取托管层存储在其上的 ChatOptions.AdditionalProperties输入;应用程序代码不直接访问该字典。
客户端状态属于不受信任的请求输入。 在提示、路由或特权操作中使用它之前,请验证其形状和值。
发出状态快照
当工具返回完整状态时,将工具结果映射到 STATE_SNAPSHOT:
using AGUI.Server;
AGUIStreamOptions streamOptions = new AGUIStreamOptions()
.MapResultAsStateSnapshot("generate_recipe");
app.MapAGUIServer("/", agent).WithMetadata(streamOptions);
MapResultAsStateSnapshot 要求 FunctionResultContent.Result 的值为 JsonElement。 先将 POCO、字典或集合序列化到 JsonElement 工具中,然后再返回它。
generate_recipe 的结果随后会成为快照,并取代客户端当前的共享状态。
对于其他结果类型,请使用 MapResult 并配合自定义映射器来构建 StateSnapshotEvent。
发布状态增量
当工具返回 RFC 6902 JSON Patch 时,将其结果映射到 STATE_DELTA:
AGUIStreamOptions streamOptions = new AGUIStreamOptions()
.MapResultAsStateSnapshot("create_plan")
.MapResultAsStateDelta("update_plan_step");
app.MapAGUIServer("/", agent).WithMetadata(streamOptions);
使用快照来初始化或替换状态,并使用增量来处理增量变更。
MapResultAsStateDelta 还要求一个 JsonElement 结果。 该元素必须包含RFC 6902 JSON Patch数组。 如果该工具返回其他表示形式,请使用 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;
}
}
客户端负责保留并应用共享状态,然后在应用程序需要时在后续请求上发送当前状态。
后续步骤
Python适配器将客户端共享状态作为具有显式不受信任数据警告的用户角色消息插入。 它不会优先考虑客户端状态系统或开发人员说明。 将受信任的策略和常设说明移至归服务器所有的智能体说明或配置中。
定义状态模型
首先,为状态结构定义 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."
重要
工具函数的参数名 (recipe) 必须与你的 predict_state_config 中的 tool_argument 相匹配。
使用状态管理创建代理
下面是使用状态管理的完整服务器实现:
"""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 receive the current recipe state as untrusted client 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,
"/",
single_user=True,
)
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"
]
}
}
}
状态增量事件
使用 JSON Patch 格式的增量状态更新,作为 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 更新。 工具完成执行时发出最终状态快照。
发送客户端状态
使用 state_carrier() 从 Python AGUIChatClient 发送共享状态。
将运营商置于其自己的用户消息中,并使用用户提示发送它。 客户端将最新的 carrier 放入 AG-UI 请求的 state 字段中,而不是将该 carrier 作为聊天消息发送。
from agent_framework import Message
from agent_framework_ag_ui import state_carrier
messages = [
Message(role="user", contents=["Update the sales dashboard."]),
Message(
role="user",
contents=[state_carrier({"selected_tab": "sales"})],
),
]
await agent.run(messages, session=thread)
普通 application/json 内容仍然是文档输入。 只有使用 state_carrier() 创建它时,它才会成为 state。
重要
allow_legacy_state_carrier=True 暂时识别已弃用的隐式 JSON 载体约定并发出弃用警告。 迁移至 ,不要为新代码启用此选项。
客户端实现
该 agent_framework_ag_ui 包提供 AGUIChatClient 用于连接到 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
asyncio.run(main())
主要优势
由 AGUIChatClient 提供:
- 简化的连接:自动处理 HTTP/SSE 通信
- 线程管理:用于聊天连续性的内置线程 ID 跟踪
-
代理集成:与熟悉的 API 无缝集成
Agent - 状态处理:从服务器自动分析状态事件
- 与 .NET 一致:跨语言的一致体验
Tip
利用AGUIChatClientAgent结合使用,充分发挥代理框架的功能,包括聊天记录、工具执行以及中间件支持等。
确认预测状态
当预测的状态更改在应用前应等待客户端确认时,请在 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时,客户端会在LLM实时生成工具参数的同时,在工具执行之前接收STATE_DELTA事件:
// 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事件进行预测更新) - 智能体在执行工具前在
RUN_FINISHED.outcome.interrupts中通过tool_call中断暂停 - 如果已批准,该工具将执行并发出最终状态(通过
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 支持:自动完成和类型检查
- 序列化:自动 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 receive the current recipe state as untrusted client 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 功能! 接下来,您可以执行以下操作:
- 浏览 Agent Framework 文档
- 构建一个完整的应用程序,将所有 AG-UI 功能组合在一起
- 将 AG-UI 服务部署到生产环境
其他资源
Go AG-UI 状态管理可以通过中间件实现,该中间件与普通文本更新一起发出结构化 message.DataContent 更新。
处理程序将application/json数据内容映射到STATE_SNAPSHOT事件,并将application/json-patch+json内容映射到STATE_DELTA事件。
DataContent.Data 包含 base64 编码的有效负载字节。 无效的 JSON 或补丁请求负载会返回转换错误。
Go 客户端将快照和增量事件映射回数据内容。 若要向远程终结点发送状态,请在输入消息中包含 application/json 数据内容;客户端将其提取到 RunAgentInput.State 中。
当前的 Go HTTP 处理程序不会将顶级请求状态注入其托管代理。 这与 Python 和 C# 的状态访问模式不同。 Go 也不提供这些选项卡中显示的预测状态 API。
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 状态管理示例。