1+ #!/usr/bin/env python3
2+ """
3+ Basic State Management Example
4+ ==============================
5+
6+ This example demonstrates the fundamental state management capabilities in PraisonAI.
7+ It shows how to set, get, update, and manage state values in a multi-agent workflow.
8+
9+ Run this example:
10+ python 01_basic_state_management.py
11+ """
12+
13+ from praisonaiagents import Agent , Task , PraisonAIAgents
14+ import json
15+ from typing import Dict , Any
16+
17+
18+ def display_project_status () -> str :
19+ """Tool to display current project status from workflow state"""
20+ # Access state from the global workflow variable
21+ project_name = workflow .get_state ("project_name" , "Unknown Project" )
22+ budget = workflow .get_state ("budget" , 0 )
23+ stage = workflow .get_state ("stage" , "not_started" )
24+ team_size = workflow .get_state ("team_size" , 0 )
25+ features = workflow .get_state ("features" , [])
26+
27+ status = f"""
28+ Project Status Report
29+ ====================
30+ Project: { project_name }
31+ Budget: ${ budget :,}
32+ Stage: { stage }
33+ Team Size: { team_size }
34+ Features: { ', ' .join (features ) if features else 'None added yet' }
35+ """
36+
37+ return status
38+
39+
40+ def add_feature (feature_name : str ) -> str :
41+ """Tool to add a new feature to the project"""
42+ features = workflow .get_state ("features" , [])
43+ features .append (feature_name )
44+ workflow .set_state ("features" , features )
45+
46+ return f"Added feature: { feature_name } . Total features: { len (features )} "
47+
48+
49+ def update_project_stage (new_stage : str ) -> str :
50+ """Tool to update the project stage"""
51+ old_stage = workflow .get_state ("stage" , "not_started" )
52+ workflow .set_state ("stage" , new_stage )
53+
54+ # Log stage transition
55+ transitions = workflow .get_state ("stage_transitions" , [])
56+ transitions .append ({"from" : old_stage , "to" : new_stage })
57+ workflow .set_state ("stage_transitions" , transitions )
58+
59+ return f"Project stage updated from '{ old_stage } ' to '{ new_stage } '"
60+
61+
62+ def check_budget_health () -> Dict [str , Any ]:
63+ """Tool to check budget health"""
64+ budget = workflow .get_state ("budget" , 0 )
65+ spent = workflow .get_state ("spent" , 0 )
66+
67+ if budget == 0 :
68+ health = "undefined"
69+ percentage = 0
70+ else :
71+ percentage = (spent / budget ) * 100
72+ if percentage > 90 :
73+ health = "critical"
74+ elif percentage > 70 :
75+ health = "warning"
76+ else :
77+ health = "healthy"
78+
79+ return {
80+ "budget" : budget ,
81+ "spent" : spent ,
82+ "remaining" : budget - spent ,
83+ "percentage_used" : percentage ,
84+ "health" : health
85+ }
86+
87+
88+ # Create agents
89+ project_manager = Agent (
90+ name = "ProjectManager" ,
91+ role = "Manage project state and status" ,
92+ goal = "Track and report project progress" ,
93+ backstory = "An experienced project manager who keeps track of all project details" ,
94+ tools = [display_project_status , update_project_stage ],
95+ llm = "gpt-4o-mini" ,
96+ verbose = True
97+ )
98+
99+ developer = Agent (
100+ name = "Developer" ,
101+ role = "Add features to the project" ,
102+ goal = "Implement new features and track them in state" ,
103+ backstory = "A skilled developer who implements features" ,
104+ tools = [add_feature , display_project_status ],
105+ llm = "gpt-4o-mini" ,
106+ verbose = True
107+ )
108+
109+ finance_manager = Agent (
110+ name = "FinanceManager" ,
111+ role = "Monitor project budget" ,
112+ goal = "Ensure project stays within budget" ,
113+ backstory = "A careful finance manager who tracks spending" ,
114+ tools = [check_budget_health ],
115+ llm = "gpt-4o-mini" ,
116+ verbose = True
117+ )
118+
119+ # Create tasks
120+ task1 = Task (
121+ name = "initialize_project" ,
122+ description = "Initialize the project and display initial status" ,
123+ expected_output = "Initial project status report" ,
124+ agent = project_manager ,
125+ tools = [display_project_status ]
126+ )
127+
128+ task2 = Task (
129+ name = "add_core_features" ,
130+ description = "Add the following core features to the project: 'User Authentication', 'Dashboard', 'API Integration'" ,
131+ expected_output = "Confirmation of added features" ,
132+ agent = developer ,
133+ tools = [add_feature ]
134+ )
135+
136+ task3 = Task (
137+ name = "update_to_development" ,
138+ description = "Update the project stage to 'development' and show updated status" ,
139+ expected_output = "Updated project status" ,
140+ agent = project_manager ,
141+ tools = [update_project_stage , display_project_status ]
142+ )
143+
144+ task4 = Task (
145+ name = "check_budget" ,
146+ description = "Check the current budget health and provide a financial report" ,
147+ expected_output = "Budget health report" ,
148+ agent = finance_manager ,
149+ tools = [check_budget_health ]
150+ )
151+
152+ # Create workflow (global variable for state access in tools)
153+ workflow = PraisonAIAgents (
154+ agents = [project_manager , developer , finance_manager ],
155+ tasks = [task1 , task2 , task3 , task4 ],
156+ verbose = True ,
157+ process = "sequential"
158+ )
159+
160+ # Set initial state values
161+ print ("\n === Setting Initial State ===" )
162+ workflow .set_state ("project_name" , "AI Assistant Platform" )
163+ workflow .set_state ("budget" , 100000 )
164+ workflow .set_state ("spent" , 25000 )
165+ workflow .set_state ("features" , [])
166+
167+ # Update multiple state values at once
168+ workflow .update_state ({
169+ "stage" : "planning" ,
170+ "team_size" : 5 ,
171+ "project_manager" : "Alice" ,
172+ "tech_stack" : ["Python" , "React" , "PostgreSQL" ]
173+ })
174+
175+ # Demonstrate state operations
176+ print ("\n === State Operations Demo ===" )
177+
178+ # Check if state exists
179+ if workflow .has_state ("budget" ):
180+ budget = workflow .get_state ("budget" )
181+ print (f"Project budget: ${ budget :,} " )
182+
183+ # Get all state
184+ all_state = workflow .get_all_state ()
185+ print (f"\n All state keys: { list (all_state .keys ())} " )
186+
187+ # Get state with default
188+ priority = workflow .get_state ("priority" , "medium" )
189+ print (f"Project priority: { priority } " )
190+
191+ # Run the workflow
192+ print ("\n === Starting Workflow ===" )
193+ result = workflow .start ()
194+
195+ # Display final state
196+ print ("\n === Final State ===" )
197+ final_state = workflow .get_all_state ()
198+ print (json .dumps (final_state , indent = 2 ))
199+
200+ # Demonstrate state deletion
201+ print ("\n === State Cleanup Demo ===" )
202+ workflow .delete_state ("project_manager" )
203+ print (f"State after deletion: { list (workflow .get_all_state ().keys ())} " )
204+
205+ # Clear all state (commented out to preserve results)
206+ # workflow.clear_state()
207+ # print(f"State after clear: {workflow.get_all_state()}")
0 commit comments