How to Intermediate · 3 min read

How to implement user preferences memory

Quick answer
Implement user preferences memory by storing user data externally (e.g., in a database or vector store) and retrieving it to provide context in messages for AI chat models like gpt-4o. Update preferences dynamically by appending or modifying stored data and including it in subsequent prompts.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the openai Python SDK and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0
output
Collecting openai
  Downloading openai-1.x.x-py3-none-any.whl
Installing collected packages: openai
Successfully installed openai-1.x.x

Step by step

This example demonstrates storing user preferences in a simple Python dictionary and including them as context in chat messages to the gpt-4o model. The preferences are updated and reused to personalize responses.

python
import os
from openai import OpenAI

# Initialize OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Simulated user preferences storage
user_preferences = {
    "user123": {
        "name": "Alice",
        "favorite_color": "blue",
        "preferred_topics": ["technology", "AI"]
    }
}

def get_user_preferences(user_id):
    return user_preferences.get(user_id, {})

def update_user_preferences(user_id, new_prefs):
    if user_id in user_preferences:
        user_preferences[user_id].update(new_prefs)
    else:
        user_preferences[user_id] = new_prefs

# Compose messages including user preferences
user_id = "user123"
prefs = get_user_preferences(user_id)

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": (
        f"User preferences: {prefs}. "
        "Please tailor your responses accordingly."
    )},
    {"role": "user", "content": "Tell me about the latest in AI."}
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages
)

print("AI response:", response.choices[0].message.content)

# Example of updating preferences
update_user_preferences(user_id, {"favorite_color": "green"})
print("Updated preferences:", get_user_preferences(user_id))
output
AI response: The latest advancements in AI include improvements in large language models, multimodal AI, and more efficient training techniques.
Updated preferences: {'name': 'Alice', 'favorite_color': 'green', 'preferred_topics': ['technology', 'AI']}

Common variations

You can implement user preferences memory with persistent storage like databases or vector stores for scalability. Use async calls for better performance or switch to other models like claude-3-5-sonnet-20241022 by adapting the SDK usage accordingly.

python
import os
import asyncio
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

async def chat_with_preferences(user_id, prefs, query):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": f"User preferences: {prefs}. Please tailor your responses accordingly."},
        {"role": "user", "content": query}
    ]
    response = await client.chat.completions.acreate(
        model="gpt-4o",
        messages=messages
    )
    return response.choices[0].message.content

async def main():
    user_id = "user123"
    prefs = {"name": "Alice", "favorite_color": "green", "preferred_topics": ["technology", "AI"]}
    answer = await chat_with_preferences(user_id, prefs, "What are some AI trends?")
    print("AI response:", answer)

if __name__ == "__main__":
    asyncio.run(main())
output
AI response: Current AI trends include generative models, AI ethics, and integration of AI in everyday applications.

Troubleshooting

  • If you get authentication errors, verify your OPENAI_API_KEY environment variable is set correctly.
  • If responses ignore preferences, ensure preferences are included clearly in the messages context.
  • For large or complex preferences, consider summarizing or embedding them to fit model context limits.

Key Takeaways

  • Store user preferences externally and include them in chat messages to maintain memory across sessions.
  • Update preferences dynamically and reuse them to personalize AI responses effectively.
  • Use async API calls and persistent storage for scalable, responsive user memory implementations.
Verified 2026-04 · gpt-4o, claude-3-5-sonnet-20241022
Verify ↗