mirror of
https://github.com/MervinPraison/PraisonAI.git
synced 2026-11-08 17:31:00 -10:00
* fix(examples): resolve syntax errors and align with consolidated-params API * fix: correct TypeError in 3 example files by using proper parameter names - Fix MemoryConfig(memory=...) → user_id=... in agent_centric_api.py - Fix Session(memory=...) → user_id=... in session-example.py - Fix build_context_for_task(memory=...) → user_id=... in memory-quality-example.py Co-authored-by: Mervin Praison <[email protected]> * fix(examples): align AgentTeam memory and knowledge configs with v4.6.52 API * fix(examples): phase-3 API alignment for consolidated params on v4.6.52 * fix(examples): phase-4 API alignment for 40 validation failures on v4.6.52 * fix: resolve critical RouterAgent **kwargs bug and add missing if __name__ guards - Fixed TypeError in RouterAgent._build_system_prompt() by removing **kwargs from super() call - Added if __name__ == '__main__' guards to 6 example files to prevent auto-execution on import - Addresses Gemini Code Assist review feedback Co-authored-by: Mervin Praison <[email protected]> * fix: resolve missing AgentTeam import and RouterAgent kwargs forwarding - Fix missing AgentTeam import in self-reflection-optimization-patterns.py - Forward kwargs properly in RouterAgent._build_system_prompt to super() - Addresses critical issues identified by Gemini code reviewer Co-authored-by: Mervin Praison <[email protected]> * fix(examples): remove merge-conflict residue for PR #1893 --------- Co-authored-by: Dhivya-Bharathy <[email protected]> Co-authored-by: praisonai-triage-agent[bot] <272766704+praisonai-triage-agent[bot]@users.noreply.github.com> Co-authored-by: Mervin Praison <[email protected]> Co-authored-by: Mervin Praison <[email protected]>
166 lines
5.0 KiB
Python
166 lines
5.0 KiB
Python
"""
|
|
Session Persistence Example
|
|
|
|
Demonstrates automatic session persistence with zero configuration.
|
|
When you provide a session_id to an Agent, conversation history is
|
|
automatically saved to disk and restored on subsequent runs.
|
|
|
|
Usage:
|
|
python session_persistence_example.py
|
|
|
|
Requirements:
|
|
- praisonaiagents package installed
|
|
- OPENAI_API_KEY environment variable set
|
|
"""
|
|
|
|
from praisonaiagents import Agent
|
|
|
|
|
|
def example_basic_persistence():
|
|
"""Basic session persistence example."""
|
|
print("=" * 60)
|
|
print("EXAMPLE 1: Basic Session Persistence")
|
|
print("=" * 60)
|
|
|
|
session_id = "demo-session-basic"
|
|
|
|
# Create agent with session_id
|
|
agent = Agent(
|
|
name="Assistant",
|
|
instructions="You are a helpful assistant. Be very brief.",
|
|
memory={"session_id": session_id},
|
|
output="minimal",
|
|
)
|
|
|
|
# First message
|
|
print("\n[User]: My favorite color is blue and my lucky number is 7.")
|
|
response1 = agent.chat("My favorite color is blue and my lucky number is 7.")
|
|
print(f"[Assistant]: {response1}")
|
|
|
|
# Second message - agent remembers
|
|
print("\n[User]: What is my favorite color?")
|
|
response2 = agent.chat("What is my favorite color?")
|
|
print(f"[Assistant]: {response2}")
|
|
|
|
print(f"\n✅ Session saved to: ~/.praison/sessions/{session_id}.json")
|
|
print(f" Chat history length: {len(agent.chat_history)} messages")
|
|
|
|
|
|
def example_session_restoration():
|
|
"""Demonstrates session restoration across Agent instances."""
|
|
print("\n" + "=" * 60)
|
|
print("EXAMPLE 2: Session Restoration")
|
|
print("=" * 60)
|
|
|
|
session_id = "demo-session-restore"
|
|
|
|
# First agent instance
|
|
print("\n--- First Agent Instance ---")
|
|
agent1 = Agent(
|
|
name="MemoryBot",
|
|
instructions="You are a helpful assistant. Be very brief.",
|
|
memory={"session_id": session_id},
|
|
output="minimal",
|
|
)
|
|
|
|
print("[User]: Remember that my pet's name is Max.")
|
|
response1 = agent1.chat("Remember that my pet's name is Max.")
|
|
print(f"[Assistant]: {response1}")
|
|
|
|
# Simulate new process by creating new agent instance
|
|
print("\n--- New Agent Instance (simulating restart) ---")
|
|
agent2 = Agent(
|
|
name="MemoryBot",
|
|
instructions="You are a helpful assistant. Be very brief.",
|
|
memory={"session_id": session_id},
|
|
output="minimal",
|
|
)
|
|
|
|
print("[User]: What is my pet's name?")
|
|
response2 = agent2.chat("What is my pet's name?")
|
|
print(f"[Assistant]: {response2}")
|
|
|
|
if "max" in response2.lower():
|
|
print("\n✅ Session restored successfully! Agent remembered 'Max'.")
|
|
else:
|
|
print("\n⚠️ Agent may not have remembered correctly.")
|
|
|
|
|
|
def example_in_memory_only():
|
|
"""Demonstrates in-memory memory without persistence."""
|
|
print("\n" + "=" * 60)
|
|
print("EXAMPLE 3: In-Memory Only (No session_id)")
|
|
print("=" * 60)
|
|
|
|
# Agent without session_id - in-memory only
|
|
agent = Agent(
|
|
name="TempBot",
|
|
instructions="You are a helpful assistant. Be very brief.",
|
|
output="minimal",
|
|
)
|
|
|
|
print("\n[User]: My name is Alice.")
|
|
response1 = agent.chat("My name is Alice.")
|
|
print(f"[Assistant]: {response1}")
|
|
|
|
print("\n[User]: What is my name?")
|
|
response2 = agent.chat("What is my name?")
|
|
print(f"[Assistant]: {response2}")
|
|
|
|
print(f"\n✅ In-memory chat history: {len(agent.chat_history)} messages")
|
|
print(" (This will be lost when the Agent instance is garbage collected)")
|
|
|
|
|
|
def example_direct_store_access():
|
|
"""Demonstrates direct access to the session store."""
|
|
print("\n" + "=" * 60)
|
|
print("EXAMPLE 4: Direct Session Store Access")
|
|
print("=" * 60)
|
|
|
|
from praisonaiagents.session import get_default_session_store
|
|
|
|
store = get_default_session_store()
|
|
session_id = "demo-direct-access"
|
|
|
|
# Add messages directly
|
|
store.add_user_message(session_id, "Hello from direct access!")
|
|
store.add_assistant_message(session_id, "Hi! I received your message.")
|
|
|
|
# Get history
|
|
history = store.get_chat_history(session_id)
|
|
print(f"\n✅ Added {len(history)} messages directly to session store")
|
|
|
|
for msg in history:
|
|
print(f" [{msg['role']}]: {msg['content']}")
|
|
|
|
# List all sessions
|
|
sessions = store.list_sessions()
|
|
print(f"\n📋 Total sessions in store: {len(sessions)}")
|
|
|
|
# Clean up demo session
|
|
store.delete_session(session_id)
|
|
print(f" Deleted demo session: {session_id}")
|
|
|
|
|
|
def main():
|
|
"""Run all examples."""
|
|
print("\n" + "=" * 60)
|
|
print("SESSION PERSISTENCE EXAMPLES")
|
|
print("=" * 60)
|
|
|
|
# Run examples
|
|
example_basic_persistence()
|
|
example_session_restoration()
|
|
example_in_memory_only()
|
|
example_direct_store_access()
|
|
|
|
print("\n" + "=" * 60)
|
|
print("ALL EXAMPLES COMPLETE")
|
|
print("=" * 60)
|
|
print("\nSession files are stored in: ~/.praison/sessions/")
|
|
print("You can inspect them with: cat ~/.praison/sessions/<session_id>.json")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|