This example shows how to create an agent with persistent memory stored in a SQLite database. We set the session_id on the agent when resuming the conversation, this way the previous chat history is preserved.Key features:
import jsonfrom typing import List, Optionalimport typerfrom agno.agent import Agentfrom agno.db.base import SessionTypefrom agno.db.sqlite import SqliteDbfrom agno.models.openai import OpenAIChatfrom agno.session import AgentSessionfrom rich import printfrom rich.console import Consolefrom rich.json import JSONfrom rich.panel import Panelfrom rich.prompt import Promptconsole = Console()def create_agent(user: str = "user"): session_id: Optional[str] = None # Ask if user wants to start new session or continue existing one new = typer.confirm("Do you want to start a new session?") # Get existing session if user doesn't want a new one db = SqliteDb(db_file="tmp/agents.db") if not new: existing_sessions: List[AgentSession] = db.get_sessions( user_id=user, session_type=SessionType.AGENT ) # type: ignore if len(existing_sessions) > 0: session_id = existing_sessions[0].session_id agent = Agent( user_id=user, # Set the session_id on the agent to resume the conversation session_id=session_id, model=OpenAIChat(id="gpt-5-mini"), db=db, # Add chat history to messages add_history_to_context=True, num_history_runs=3, markdown=True, ) if session_id is None: session_id = agent.session_id if session_id is not None: print(f"Started Session: {session_id}\n") else: print("Started Session\n") else: print(f"Continuing Session: {session_id}\n") return agentdef print_messages(agent): """Print the current chat history in a formatted panel""" console.print( Panel( JSON( json.dumps( [ m.model_dump(include={"role", "content"}) for m in agent.get_messages_for_session() ] ), indent=4, ), title=f"Chat History for session_id: {agent.session_id}", expand=True, ) )def main(user: str = "user"): agent = create_agent(user) print("Chat with an OpenAI agent!") exit_on = ["exit", "quit", "bye"] while True: message = Prompt.ask(f"[bold] :sunglasses: {user} [/bold]") if message in exit_on: break agent.print_response(input=message, stream=True, markdown=True) print_messages(agent)if __name__ == "__main__": typer.run(main)