my-gradio-app / examples /session_persistence_example.py
Nguyen Trong Lap
Recreate history without binary blobs
eeb0f9c
raw
history blame
3.19 kB
"""
Session Persistence Example
Demonstrates how conversation memory persists across sessions
"""
from agents.core.coordinator import AgentCoordinator
def example_first_session():
"""First session - user provides information"""
print("=" * 60)
print("SESSION 1: User provides information")
print("=" * 60)
# Create coordinator with user_id
coordinator = AgentCoordinator(user_id="user123")
# User provides information
query1 = "Tôi 25 tuổi, nam, 70kg, 175cm, muốn giảm cân"
response1 = coordinator.handle_query(query1, [])
print(f"\nUser: {query1}")
print(f"Bot: {response1[:200]}...")
# Check what's in memory
profile = coordinator.memory.get_full_profile()
print(f"\n📊 Memory saved:")
print(f" Age: {profile['age']}")
print(f" Gender: {profile['gender']}")
print(f" Weight: {profile['weight']}kg")
print(f" Height: {profile['height']}cm")
print("\n✅ Session saved automatically!")
print(" (User closes app)")
def example_second_session():
"""Second session - memory is restored"""
print("\n" + "=" * 60)
print("SESSION 2: User returns (next day)")
print("=" * 60)
# Create NEW coordinator with SAME user_id
# Memory will be automatically loaded!
coordinator = AgentCoordinator(user_id="user123")
# Check memory - it should be loaded!
profile = coordinator.memory.get_full_profile()
print(f"\n📊 Memory restored:")
print(f" Age: {profile['age']}")
print(f" Gender: {profile['gender']}")
print(f" Weight: {profile['weight']}kg")
print(f" Height: {profile['height']}cm")
# User asks new question - bot remembers!
query2 = "Tôi nên ăn bao nhiêu calo mỗi ngày?"
response2 = coordinator.handle_query(query2, [])
print(f"\nUser: {query2}")
print(f"Bot: {response2[:200]}...")
print("\n✅ Bot remembers user info from previous session!")
def example_different_user():
"""Different user - separate session"""
print("\n" + "=" * 60)
print("SESSION 3: Different user")
print("=" * 60)
# Different user_id = different session
coordinator = AgentCoordinator(user_id="user456")
profile = coordinator.memory.get_full_profile()
print(f"\n📊 Memory for user456:")
print(f" Age: {profile['age']}") # Should be None
print(f" Gender: {profile['gender']}") # Should be None
print("\n✅ Each user has separate session!")
def example_without_persistence():
"""Without user_id - no persistence"""
print("\n" + "=" * 60)
print("SESSION 4: Without persistence (no user_id)")
print("=" * 60)
# No user_id = no persistence
coordinator = AgentCoordinator() # No user_id
print("\n⚠️ Memory will NOT persist across sessions")
print(" (Useful for anonymous/guest users)")
if __name__ == '__main__':
# Run examples
example_first_session()
example_second_session()
example_different_user()
example_without_persistence()
print("\n" + "=" * 60)
print("✅ Session Persistence Demo Complete!")
print("=" * 60)