Skip to main content

agents.examples.shared_state

Shared State example.

Demonstrates bidirectional state synchronization between the agent and the UI. The agent can read and update shared state, and the UI reflects these changes in real-time.

Features:

  • State snapshot events (full state updates)
  • State delta events (incremental updates)
  • Bidirectional state flow (UI → Agent → UI)

This pattern is useful for:

  • Recipe builders
  • Form assistants
  • Document editors
  • Any collaborative editing scenario

Example: Recipe Builder

  • User can set ingredients via UI
  • Agent can add/modify recipe details
  • Both see the same state in real-time

SkillLevel Objects

class SkillLevel(StrEnum)

The skill level required for the recipe.

SpecialPreferences Objects

class SpecialPreferences(StrEnum)

Special preferences for the recipe.

CookingTime Objects

class CookingTime(StrEnum)

The cooking time of the recipe.

Ingredient Objects

class Ingredient(BaseModel)

An ingredient in a recipe.

Recipe Objects

class Recipe(BaseModel)

A recipe with all its details.

RecipeSnapshot Objects

class RecipeSnapshot(BaseModel)

The shared state for the recipe builder.

display_recipe

@agent.tool_plain
async def display_recipe(recipe: Recipe) -> StateSnapshotEvent

Display the recipe to the user.

This tool updates the shared state with the new recipe, which is then reflected in the UI.

Arguments:

  • recipe - The complete recipe to display.

Returns:

StateSnapshotEvent containing the recipe snapshot.

recipe_instructions

@agent.instructions
async def recipe_instructions(
ctx: RunContext[StateDeps[RecipeSnapshot]]) -> str

Dynamic instructions based on current recipe state.

Arguments:

  • ctx - The run context containing recipe state.

Returns:

Instructions string for the agent.