In this lesson, you’ll learn how to give your agent a memory. By default, an agent is stateless—it forgets everything after providing a response. Session management allows an agent to remember past interactions, maintain context, and have more natural, ongoing conversations.We’ll use a FileSessionManager to automatically save and load the conversation history to your local computer.
Because the agent loads the previous messages, it has the full context of the conversation. When the user asks “Do you remember my name?”, the agent can look back at the history and provide the correct answer.
The FileSessionManager creates a folder for each session_id. Inside that folder, it saves each message in the conversation as a separate JSON file. When you create an agent with an existing session_id, the manager loads all those JSON files to reconstruct the conversation history.
def create_persistent_agent(session_id: str) -> Agent: """ Creates an agent with persistent memory using a FileSessionManager. Args: session_id: A unique identifier for the conversation session. Returns: An Agent instance that can remember past interactions. """ # Configure the language model model = LiteLLMModel( client_args={"api_key": os.getenv("NEBIUS_API_KEY")}, model_id="nebius/deepseek-ai/DeepSeek-V3-0324", ) # Set up the directory to store session files base_dir = Path(__file__).parent.resolve() storage_dir = base_dir / "tmp" / "sessions" print(f"Session files will be stored in: {storage_dir}") # Create a FileSessionManager to handle saving and loading the conversation session_manager = FileSessionManager( session_id=session_id, storage_dir=str(storage_dir), ) # Create an agent and attach the session manager # This agent will now have memory! persistent_agent = Agent( model=model, session_manager=session_manager, system_prompt="You are a friendly assistant. Keep your responses concise." ) return persistent_agent
The session_id is crucial—it’s how the agent knows which conversation history to load. Use descriptive IDs like user_123_chat or project_brainstorm_session.
def main(): """ Main function to demonstrate a conversational agent with memory. """ # Each session ID represents a unique conversation history session_id = "user_arindam_convo_123" agent = create_persistent_agent(session_id) print("--- Conversation Start ---") # First interaction: The user introduces themselves print("\nUser: Hey, my name is Arindam.") response1 = agent("Hey, my name is Arindam.") print(f"Agent: {response1}") # Second interaction: Ask the agent if it remembers the name print("\nUser: Do you remember my name?") response2 = agent("Do you remember my name?") print(f"Agent: {response2}") print("\n--- Conversation End ---") print(f"\nThe agent was able to remember the name because its memory is persisted in the session '{session_id}'.")if __name__ == "__main__": main()
Session files will be stored in: /path/to/tmp/sessions--- Conversation Start ---User: Hey, my name is Arindam.Agent: Hello Arindam! Nice to meet you. How can I help you today?User: Do you remember my name?Agent: Yes, of course! Your name is Arindam.--- Conversation End ---The agent was able to remember the name because its memory is persisted in the session 'user_arindam_convo_123'.
The agent successfully recalls the user’s name from the previous message because the session manager loaded the conversation history!
Create multiple sessions with different session IDs:
# Session 1: Planning a tripagent1 = create_persistent_agent("trip_planning_session")agent1("I want to visit Japan in the spring")# Session 2: Learning Pythonagent2 = create_persistent_agent("python_learning_session")agent2("I'm learning Python. Can you help me?")# Later, resume session 1agent1_resumed = create_persistent_agent("trip_planning_session")agent1_resumed("What did we discuss about Japan?")# Agent remembers the trip planning conversation!
Experiment 2: Long Conversations
Test the agent’s memory over many interactions:
agent = create_persistent_agent("long_conversation")# Message 1: Share informationagent("My favorite color is blue.")# Message 2: More informationagent("I work as a software engineer.")# Message 3: Even moreagent("I have a dog named Max.")# Message 4: Test memoryresponse = agent("What do you know about me?")print(response) # Should recall color, job, and dog!
Your agent now has memory! But what if you need to extract structured data from unstructured text? In the next lesson, you’ll learn how to use Pydantic models to get structured output from your agent.
Lesson 03: Structured Output
Learn how to extract structured JSON data from natural language using Pydantic