1from kern.agent import Agent
2from kern.db.sqlite import SqliteDb
3from kern.memory import MemoryManager, SummarizeStrategy
4from kern.memory.strategies.types import MemoryOptimizationStrategyType
5from kern.models.openai import OpenAIResponses
6
7db_file = "tmp/memory_summarize_strategy.db"
8db = SqliteDb(db_file=db_file)
9
10user_id = "user2"
11
12# Create agent with memory enabled
13agent = Agent(
14 model=OpenAIResponses(id="gpt-5.2"),
15 db=db,
16 update_memory_on_run=True,
17)
18
19# Create some memories for a user
20print("Creating memories...")
21agent.print_response(
22 "I have a wonderful pet dog named Max who is 3 years old. He's a golden retriever and he's such a friendly and energetic dog. "
23 "We got him as a puppy when he was just 8 weeks old. He loves playing fetch in the park and going on long walks. "
24 "Max is really smart too - he knows about 15 different commands and tricks. Taking care of him has been one of the most "
25 "rewarding experiences of my life. He's basically part of the family now.",
26 user_id=user_id,
27)
28agent.print_response(
29 "I currently live in San Francisco, which is an amazing city despite all its challenges. I've been here for about 5 years now. "
30 "I work in the tech industry as a product manager at a mid-sized software company. The tech scene here is incredible - "
31 "there are so many smart people working on interesting problems. The cost of living is definitely high, but the opportunities "
32 "and the community make it worthwhile. I live in the Mission district which has great food and a vibrant culture.",
33 user_id=user_id,
34)
35agent.print_response(
36 "On weekends, I really enjoy hiking in the beautiful areas around the Bay Area. There are so many amazing trails - "
37 "from Mount Tamalpais to Big Basin Redwoods. I usually go hiking with a group of friends and we try to explore new trails every month. "
38 "I also love trying new restaurants. San Francisco has such an incredible food scene with cuisines from all over the world. "
39 "I'm always on the lookout for hidden gems and new places to try. My favorite types of cuisine are Japanese, Thai, and Mexican.",
40 user_id=user_id,
41)
42agent.print_response(
43 "I've been learning to play the piano for about a year and a half now. It's something I always wanted to do but never had time for. "
44 "I finally decided to commit to it and I practice almost every day, usually for 30-45 minutes. "
45 "I'm working through classical pieces right now - I can play some simple Bach and Mozart compositions. "
46 "My goal is to eventually be able to play some jazz piano as well. Having a creative hobby like this has been great for my mental health "
47 "and it's nice to have something completely different from my day job.",
48 user_id=user_id,
49)
50
51# Check current memories
52print("\nBefore optimization:")
53memories_before = agent.get_user_memories(user_id=user_id)
54print(f" Memory count: {len(memories_before)}")
55
56# Count tokens before optimization
57strategy = SummarizeStrategy()
58tokens_before = strategy.count_tokens(memories_before)
59print(f" Token count: {tokens_before} tokens")
60
61print("\nIndividual memories:")
62for i, memory in enumerate(memories_before, 1):
63 print(f" {i}. {memory.memory}")
64
65# Create memory manager and optimize memories
66memory_manager = MemoryManager(
67 model=OpenAIResponses(id="gpt-5.2"),
68 db=db,
69)
70
71print("\nOptimizing memories with 'summarize' strategy...")
72memory_manager.optimize_memories(
73 user_id=user_id,
74 strategy=MemoryOptimizationStrategyType.SUMMARIZE, # Combine all memories into one
75 apply=True, # Apply changes to database
76)
77
78# Check optimized memories
79print("\nAfter optimization:")
80memories_after = agent.get_user_memories(user_id=user_id)
81print(f" Memory count: {len(memories_after)}")
82
83# Count tokens after optimization
84tokens_after = strategy.count_tokens(memories_after)
85print(f" Token count: {tokens_after} tokens")
86
87# Calculate reduction
88if tokens_before > 0:
89 reduction_pct = ((tokens_before - tokens_after) / tokens_before) * 100
90 tokens_saved = tokens_before - tokens_after
91 print(f" Reduction: {reduction_pct:.1f}% ({tokens_saved} tokens saved)")
92
93if memories_after:
94 print("\nSummarized memory:")
95 print(f" {memories_after[0].memory}")
96else:
97 print("\n No memories found after optimization")