Introduction
State persistence means saving what an AI agent remembers or learns so it can use that information later, even after being turned off or restarted.
Jump into concepts and practice - no test required
save_state(state_data, filename) load_state(filename) -> state_data
save_state({'score': 100, 'level': 2}, 'game_state.json')state = load_state('game_state.json') print(state['score'])
import json # Function to save state to a file def save_state(state_data, filename): with open(filename, 'w') as f: json.dump(state_data, f) # Function to load state from a file def load_state(filename): try: with open(filename, 'r') as f: return json.load(f) except FileNotFoundError: return {} # Example usage # Initial state agent_state = {'conversations': 1, 'last_message': 'Hello!'} # Save the state save_state(agent_state, 'agent_state.json') # Later, load the state loaded_state = load_state('agent_state.json') print(f"Conversations so far: {loaded_state.get('conversations', 0)}") print(f"Last message: {loaded_state.get('last_message', '')}")
state persistence in agentic AI systems?state.pkl using the pickle module?pickle.dump(object, file) with file opened in write-binary mode.pickle.dump(agent_state, open('state.pkl', 'wb')).import pickle
with open('state.pkl', 'rb') as f:
agent_state = pickle.load(f)
print(agent_state)
What will be the output if state.pkl contains the dictionary {'score': 42, 'level': 3}?{'score': 42, 'level': 3}.import pickle
agent_state = {'score': 10}
file = open('state.pkl', 'r')
pickle.dump(agent_state, file)
file.close()
What is the main error causing the failure?