- Save user preferences to a JSON file on disk.
- Load that JSON at startup.
- Inject the loaded preferences into the system prompt so the model has awareness of previously saved state.
- Python and a virtual environment are available.
- The OpenAI Python SDK is installed.
- Your working directory is
/root/code. - This walkthrough creates a single file:
persistent_agent.py.

- A safe-agent pattern with a simple
check_calendartool and atry_call_toolwrapper. - A persistent memory layer backed by
agent_memory.json. save_preferenceandforget_preferencehandlers.- System prompt injection of loaded preferences at startup.
- A small main loop demonstrating the flow.
This lab focuses on the memory pattern and safe tool execution. In production, replace the local JSON file with a secure database and ensure sensitive information is encrypted.
- File and client setup
Create
persistent_agent.pyand start with imports, client initialization, and constants:
- Safe tool pattern
Define a simple calendar “tool” and a
try_call_toolhelper that catches exceptions and returns a safe string. This keeps the agent robust when tools fail.
- Persistent memory layer
Add the functions to load/save JSON and the two preference handlers:
save_preferenceandforget_preference. These read/writeagent_memory.jsonand return human-readable status strings for the agent.
- Optional: expose tool metadata
If your agent framework expects a tool registry, provide metadata for
save_preferenceandforget_preference. This is optional but helpful for structured agent orchestrators.
- Inject memory into the system prompt Load the memory at startup and append known preferences to the system prompt. This ensures the model is aware of persistent state without requiring the user to repeat preferences.
- Main loop: demonstration of flow A minimal main loop shows the overall pattern: build the system prompt (with memory injected), process messages, call tools safely, and save/forget preferences as appropriate. This example simulates agent behavior and is intentionally straightforward to illustrate the pattern.
- Run with:
python3 persistent_agent.py - Observe the printed system prompt (memory is injected) and the simulated session.
agent_memory.json to confirm persistence:
Storing sensitive user data or secrets in plaintext JSON on disk is not secure. For production systems, use an encrypted store or a database with proper access controls and encryption at rest.
- The pattern shown here is portable: swap
agent_memory.jsonfor a database or key-value store, and replace the simulatedcheck_calendartool with a real calendar API. - Consider schema validation for preferences and limits on memory size to avoid letting the system prompt become too large.
Links and references
Save, load, forget — that’s the persistent-memory layer. Adapt this pattern to your infrastructure and production-grade storage for robust, long-term agent memory.