agno 2.3.1__py3-none-any.whl → 2.3.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. agno/agent/agent.py +514 -186
  2. agno/compression/__init__.py +3 -0
  3. agno/compression/manager.py +176 -0
  4. agno/db/dynamo/dynamo.py +11 -0
  5. agno/db/firestore/firestore.py +5 -1
  6. agno/db/gcs_json/gcs_json_db.py +5 -2
  7. agno/db/in_memory/in_memory_db.py +5 -2
  8. agno/db/json/json_db.py +5 -1
  9. agno/db/migrations/manager.py +4 -4
  10. agno/db/mongo/async_mongo.py +158 -34
  11. agno/db/mongo/mongo.py +6 -2
  12. agno/db/mysql/mysql.py +48 -54
  13. agno/db/postgres/async_postgres.py +61 -51
  14. agno/db/postgres/postgres.py +42 -50
  15. agno/db/redis/redis.py +5 -0
  16. agno/db/redis/utils.py +5 -5
  17. agno/db/schemas/memory.py +7 -5
  18. agno/db/singlestore/singlestore.py +99 -108
  19. agno/db/sqlite/async_sqlite.py +32 -30
  20. agno/db/sqlite/sqlite.py +34 -30
  21. agno/knowledge/reader/pdf_reader.py +2 -2
  22. agno/knowledge/reader/tavily_reader.py +0 -1
  23. agno/memory/__init__.py +14 -1
  24. agno/memory/manager.py +223 -8
  25. agno/memory/strategies/__init__.py +15 -0
  26. agno/memory/strategies/base.py +67 -0
  27. agno/memory/strategies/summarize.py +196 -0
  28. agno/memory/strategies/types.py +37 -0
  29. agno/models/anthropic/claude.py +84 -80
  30. agno/models/aws/bedrock.py +38 -16
  31. agno/models/aws/claude.py +97 -277
  32. agno/models/azure/ai_foundry.py +8 -4
  33. agno/models/base.py +101 -14
  34. agno/models/cerebras/cerebras.py +18 -7
  35. agno/models/cerebras/cerebras_openai.py +4 -2
  36. agno/models/cohere/chat.py +8 -4
  37. agno/models/google/gemini.py +578 -20
  38. agno/models/groq/groq.py +18 -5
  39. agno/models/huggingface/huggingface.py +17 -6
  40. agno/models/ibm/watsonx.py +16 -6
  41. agno/models/litellm/chat.py +17 -7
  42. agno/models/message.py +19 -5
  43. agno/models/meta/llama.py +20 -4
  44. agno/models/mistral/mistral.py +8 -4
  45. agno/models/ollama/chat.py +17 -6
  46. agno/models/openai/chat.py +17 -6
  47. agno/models/openai/responses.py +23 -9
  48. agno/models/vertexai/claude.py +99 -5
  49. agno/os/interfaces/agui/router.py +1 -0
  50. agno/os/interfaces/agui/utils.py +97 -57
  51. agno/os/router.py +16 -1
  52. agno/os/routers/memory/memory.py +146 -0
  53. agno/os/routers/memory/schemas.py +26 -0
  54. agno/os/schema.py +21 -6
  55. agno/os/utils.py +134 -10
  56. agno/run/base.py +2 -1
  57. agno/run/workflow.py +1 -1
  58. agno/team/team.py +571 -225
  59. agno/tools/mcp/mcp.py +1 -1
  60. agno/utils/agent.py +119 -1
  61. agno/utils/dttm.py +33 -0
  62. agno/utils/models/ai_foundry.py +9 -2
  63. agno/utils/models/claude.py +12 -5
  64. agno/utils/models/cohere.py +9 -2
  65. agno/utils/models/llama.py +9 -2
  66. agno/utils/models/mistral.py +4 -2
  67. agno/utils/print_response/agent.py +37 -2
  68. agno/utils/print_response/team.py +52 -0
  69. agno/utils/tokens.py +41 -0
  70. agno/workflow/types.py +2 -2
  71. {agno-2.3.1.dist-info → agno-2.3.3.dist-info}/METADATA +45 -40
  72. {agno-2.3.1.dist-info → agno-2.3.3.dist-info}/RECORD +75 -68
  73. {agno-2.3.1.dist-info → agno-2.3.3.dist-info}/WHEEL +0 -0
  74. {agno-2.3.1.dist-info → agno-2.3.3.dist-info}/licenses/LICENSE +0 -0
  75. {agno-2.3.1.dist-info → agno-2.3.3.dist-info}/top_level.txt +0 -0
agno/db/sqlite/sqlite.py CHANGED
@@ -28,7 +28,7 @@ from agno.utils.log import log_debug, log_error, log_info, log_warning
28
28
  from agno.utils.string import generate_id
29
29
 
30
30
  try:
31
- from sqlalchemy import Column, MetaData, Table, and_, func, select, text
31
+ from sqlalchemy import Column, MetaData, String, Table, func, select, text
32
32
  from sqlalchemy.dialects import sqlite
33
33
  from sqlalchemy.engine import Engine, create_engine
34
34
  from sqlalchemy.orm import scoped_session, sessionmaker
@@ -141,12 +141,7 @@ class SqliteDb(BaseDb):
141
141
  ]
142
142
 
143
143
  for table_name, table_type in tables_to_create:
144
- if table_name != self.versions_table_name:
145
- # Also store the schema version for the created table
146
- latest_schema_version = MigrationManager(self).latest_schema_version
147
- self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public)
148
-
149
- self._create_table(table_name=table_name, table_type=table_type)
144
+ self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True)
150
145
 
151
146
  def _create_table(self, table_name: str, table_type: str) -> Table:
152
147
  """
@@ -161,7 +156,6 @@ class SqliteDb(BaseDb):
161
156
  """
162
157
  try:
163
158
  table_schema = get_table_schema_definition(table_type)
164
- log_debug(f"Creating table {table_name}")
165
159
 
166
160
  columns: List[Column] = []
167
161
  indexes: List[str] = []
@@ -186,8 +180,7 @@ class SqliteDb(BaseDb):
186
180
  columns.append(Column(*column_args, **column_kwargs)) # type: ignore
187
181
 
188
182
  # Create the table object
189
- table_metadata = MetaData()
190
- table = Table(table_name, table_metadata, *columns)
183
+ table = Table(table_name, self.metadata, *columns)
191
184
 
192
185
  # Add multi-column unique constraints with table-specific names
193
186
  for constraint in schema_unique_constraints:
@@ -201,12 +194,17 @@ class SqliteDb(BaseDb):
201
194
  table.append_constraint(Index(idx_name, idx_col))
202
195
 
203
196
  # Create table
204
- table.create(self.db_engine, checkfirst=True)
197
+ table_created = False
198
+ if not self.table_exists(table_name):
199
+ table.create(self.db_engine, checkfirst=True)
200
+ log_debug(f"Successfully created table '{table_name}'")
201
+ table_created = True
202
+ else:
203
+ log_debug(f"Table '{table_name}' already exists, skipping creation")
205
204
 
206
205
  # Create indexes
207
206
  for idx in table.indexes:
208
207
  try:
209
- log_debug(f"Creating index: {idx.name}")
210
208
  # Check if index already exists
211
209
  with self.Session() as sess:
212
210
  exists_query = text("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = :index_name")
@@ -217,13 +215,21 @@ class SqliteDb(BaseDb):
217
215
 
218
216
  idx.create(self.db_engine)
219
217
 
218
+ log_debug(f"Created index: {idx.name} for table {table_name}")
220
219
  except Exception as e:
221
220
  log_warning(f"Error creating index {idx.name}: {e}")
222
221
 
223
- log_debug(f"Successfully created table '{table_name}'")
222
+ # Store the schema version for the created table
223
+ if table_name != self.versions_table_name and table_created:
224
+ latest_schema_version = MigrationManager(self).latest_schema_version
225
+ self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public)
226
+
224
227
  return table
225
228
 
226
229
  except Exception as e:
230
+ from traceback import format_exc
231
+
232
+ print(format_exc())
227
233
  log_error(f"Could not create table '{table_name}': {e}")
228
234
  raise e
229
235
 
@@ -311,11 +317,6 @@ class SqliteDb(BaseDb):
311
317
  if not create_table_if_not_found:
312
318
  return None
313
319
 
314
- if table_name != self.versions_table_name:
315
- # Also store the schema version for the created table
316
- latest_schema_version = MigrationManager(self).latest_schema_version
317
- self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public)
318
-
319
320
  return self._create_table(table_name=table_name, table_type=table_type)
320
321
 
321
322
  # SQLite version of table validation (no schema)
@@ -1176,8 +1177,8 @@ class SqliteDb(BaseDb):
1176
1177
  if team_id is not None:
1177
1178
  stmt = stmt.where(table.c.team_id == team_id)
1178
1179
  if topics is not None:
1179
- topic_conditions = [text(f"topics::text LIKE '%\"{topic}\"%'") for topic in topics]
1180
- stmt = stmt.where(and_(*topic_conditions))
1180
+ for topic in topics:
1181
+ stmt = stmt.where(func.cast(table.c.topics, String).like(f'%"{topic}"%'))
1181
1182
  if search_content is not None:
1182
1183
  stmt = stmt.where(table.c.memory.ilike(f"%{search_content}%"))
1183
1184
 
@@ -1212,12 +1213,14 @@ class SqliteDb(BaseDb):
1212
1213
  self,
1213
1214
  limit: Optional[int] = None,
1214
1215
  page: Optional[int] = None,
1216
+ user_id: Optional[str] = None,
1215
1217
  ) -> Tuple[List[Dict[str, Any]], int]:
1216
1218
  """Get user memories stats.
1217
1219
 
1218
1220
  Args:
1219
1221
  limit (Optional[int]): The maximum number of user stats to return.
1220
1222
  page (Optional[int]): The page number.
1223
+ user_id (Optional[str]): User ID for filtering.
1221
1224
 
1222
1225
  Returns:
1223
1226
  Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count.
@@ -1240,19 +1243,20 @@ class SqliteDb(BaseDb):
1240
1243
  return [], 0
1241
1244
 
1242
1245
  with self.Session() as sess, sess.begin():
1243
- stmt = (
1244
- select(
1245
- table.c.user_id,
1246
- func.count(table.c.memory_id).label("total_memories"),
1247
- func.max(table.c.updated_at).label("last_memory_updated_at"),
1248
- )
1249
- .where(table.c.user_id.is_not(None))
1250
- .group_by(table.c.user_id)
1251
- .order_by(func.max(table.c.updated_at).desc())
1246
+ stmt = select(
1247
+ table.c.user_id,
1248
+ func.count(table.c.memory_id).label("total_memories"),
1249
+ func.max(table.c.updated_at).label("last_memory_updated_at"),
1252
1250
  )
1251
+ if user_id is not None:
1252
+ stmt = stmt.where(table.c.user_id == user_id)
1253
+ else:
1254
+ stmt = stmt.where(table.c.user_id.is_not(None))
1255
+ stmt = stmt.group_by(table.c.user_id)
1256
+ stmt = stmt.order_by(func.max(table.c.updated_at).desc())
1253
1257
 
1254
1258
  count_stmt = select(func.count()).select_from(stmt.alias())
1255
- total_count = sess.execute(count_stmt).scalar()
1259
+ total_count = sess.execute(count_stmt).scalar() or 0
1256
1260
 
1257
1261
  # Pagination
1258
1262
  if limit is not None:
@@ -406,7 +406,7 @@ class PDFImageReader(BasePDFReader):
406
406
  return []
407
407
 
408
408
  # Read and chunk.
409
- return self._pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=False)
409
+ return self._pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=True)
410
410
 
411
411
  async def async_read(
412
412
  self, pdf: Union[str, Path, IO[Any]], name: Optional[str] = None, password: Optional[str] = None
@@ -428,4 +428,4 @@ class PDFImageReader(BasePDFReader):
428
428
  return []
429
429
 
430
430
  # Read and chunk.
431
- return await self._async_pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=False)
431
+ return await self._async_pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=True)
@@ -140,7 +140,6 @@ class TavilyReader(Reader):
140
140
  documents.extend(self.chunk_document(Document(name=name or url, id=url, content=content)))
141
141
  else:
142
142
  documents.append(Document(name=name or url, id=url, content=content))
143
-
144
143
  return documents
145
144
 
146
145
  except Exception as e:
agno/memory/__init__.py CHANGED
@@ -1,3 +1,16 @@
1
1
  from agno.memory.manager import MemoryManager, UserMemory
2
+ from agno.memory.strategies import (
3
+ MemoryOptimizationStrategy,
4
+ MemoryOptimizationStrategyFactory,
5
+ MemoryOptimizationStrategyType,
6
+ SummarizeStrategy,
7
+ )
2
8
 
3
- __all__ = ["MemoryManager", "UserMemory"]
9
+ __all__ = [
10
+ "MemoryManager",
11
+ "UserMemory",
12
+ "MemoryOptimizationStrategy",
13
+ "MemoryOptimizationStrategyType",
14
+ "MemoryOptimizationStrategyFactory",
15
+ "SummarizeStrategy",
16
+ ]
agno/memory/manager.py CHANGED
@@ -1,6 +1,5 @@
1
1
  from copy import deepcopy
2
2
  from dataclasses import dataclass
3
- from datetime import datetime
4
3
  from os import getenv
5
4
  from textwrap import dedent
6
5
  from typing import Any, Callable, Dict, List, Literal, Optional, Type, Union
@@ -9,10 +8,16 @@ from pydantic import BaseModel, Field
9
8
 
10
9
  from agno.db.base import AsyncBaseDb, BaseDb
11
10
  from agno.db.schemas import UserMemory
11
+ from agno.memory.strategies import MemoryOptimizationStrategy
12
+ from agno.memory.strategies.types import (
13
+ MemoryOptimizationStrategyFactory,
14
+ MemoryOptimizationStrategyType,
15
+ )
12
16
  from agno.models.base import Model
13
17
  from agno.models.message import Message
14
18
  from agno.models.utils import get_model
15
19
  from agno.tools.function import Function
20
+ from agno.utils.dttm import now_epoch_s
16
21
  from agno.utils.log import (
17
22
  log_debug,
18
23
  log_error,
@@ -89,9 +94,6 @@ class MemoryManager:
89
94
  self.clear_memories = clear_memories
90
95
  self.debug_mode = debug_mode
91
96
 
92
- self._get_models()
93
-
94
- def _get_models(self) -> None:
95
97
  if self.model is not None:
96
98
  self.model = get_model(self.model)
97
99
 
@@ -227,7 +229,7 @@ class MemoryManager:
227
229
  memory.user_id = user_id
228
230
 
229
231
  if not memory.updated_at:
230
- memory.updated_at = datetime.now()
232
+ memory.updated_at = now_epoch_s()
231
233
 
232
234
  self._upsert_db_memory(memory=memory)
233
235
  return memory.memory_id
@@ -255,7 +257,7 @@ class MemoryManager:
255
257
  user_id = "default"
256
258
 
257
259
  if not memory.updated_at:
258
- memory.updated_at = datetime.now()
260
+ memory.updated_at = now_epoch_s()
259
261
 
260
262
  memory.memory_id = memory_id
261
263
  memory.user_id = user_id
@@ -291,6 +293,74 @@ class MemoryManager:
291
293
  log_warning("Memory DB not provided.")
292
294
  return None
293
295
 
296
+ def clear_user_memories(self, user_id: Optional[str] = None) -> None:
297
+ """Clear all memories for a specific user.
298
+
299
+ Args:
300
+ user_id (Optional[str]): The user id to clear memories for. If not provided, clears memories for the "default" user.
301
+ """
302
+ if user_id is None:
303
+ log_warning("Using default user id.")
304
+ user_id = "default"
305
+
306
+ if not self.db:
307
+ log_warning("Memory DB not provided.")
308
+ return
309
+
310
+ if isinstance(self.db, AsyncBaseDb):
311
+ raise ValueError(
312
+ "clear_user_memories() is not supported with an async DB. Please use aclear_user_memories() instead."
313
+ )
314
+
315
+ # TODO: This is inefficient - we fetch all memories just to get their IDs.
316
+ # Extend delete_user_memories() to accept just user_id and delete all memories
317
+ # for that user directly without requiring a list of memory_ids.
318
+ memories = self.get_user_memories(user_id=user_id)
319
+ if not memories:
320
+ log_debug(f"No memories found for user {user_id}")
321
+ return
322
+
323
+ # Extract memory IDs
324
+ memory_ids = [mem.memory_id for mem in memories if mem.memory_id]
325
+
326
+ if memory_ids:
327
+ # Delete all memories in a single batch operation
328
+ self.db.delete_user_memories(memory_ids=memory_ids, user_id=user_id)
329
+ log_debug(f"Cleared {len(memory_ids)} memories for user {user_id}")
330
+
331
+ async def aclear_user_memories(self, user_id: Optional[str] = None) -> None:
332
+ """Clear all memories for a specific user (async).
333
+
334
+ Args:
335
+ user_id (Optional[str]): The user id to clear memories for. If not provided, clears memories for the "default" user.
336
+ """
337
+ if user_id is None:
338
+ user_id = "default"
339
+
340
+ if not self.db:
341
+ log_warning("Memory DB not provided.")
342
+ return
343
+
344
+ if isinstance(self.db, AsyncBaseDb):
345
+ memories = await self.aget_user_memories(user_id=user_id)
346
+ else:
347
+ memories = self.get_user_memories(user_id=user_id)
348
+
349
+ if not memories:
350
+ log_debug(f"No memories found for user {user_id}")
351
+ return
352
+
353
+ # Extract memory IDs
354
+ memory_ids = [mem.memory_id for mem in memories if mem.memory_id]
355
+
356
+ if memory_ids:
357
+ # Delete all memories in a single batch operation
358
+ if isinstance(self.db, AsyncBaseDb):
359
+ await self.db.delete_user_memories(memory_ids=memory_ids, user_id=user_id)
360
+ else:
361
+ self.db.delete_user_memories(memory_ids=memory_ids, user_id=user_id)
362
+ log_debug(f"Cleared {len(memory_ids)} memories for user {user_id}")
363
+
294
364
  # -*- Agent Functions
295
365
  def create_user_memories(
296
366
  self,
@@ -671,7 +741,7 @@ class MemoryManager:
671
741
  # If updated_at is None, place at the beginning of the list
672
742
  sorted_memories_list = sorted(
673
743
  memories_list,
674
- key=lambda memory: memory.updated_at or datetime.min,
744
+ key=lambda m: m.updated_at if m.updated_at is not None else 0,
675
745
  )
676
746
  else:
677
747
  sorted_memories_list = []
@@ -694,6 +764,7 @@ class MemoryManager:
694
764
  if memories is None:
695
765
  memories = {}
696
766
 
767
+ MAX_UNIX_TS = 2**63 - 1
697
768
  memories_list = memories.get(user_id, [])
698
769
  # Sort memories by updated_at timestamp if available
699
770
  if memories_list:
@@ -701,7 +772,7 @@ class MemoryManager:
701
772
  # If updated_at is None, place at the end of the list
702
773
  sorted_memories_list = sorted(
703
774
  memories_list,
704
- key=lambda memory: memory.updated_at or datetime.max,
775
+ key=lambda m: m.updated_at if m.updated_at is not None else MAX_UNIX_TS,
705
776
  )
706
777
 
707
778
  else:
@@ -712,6 +783,150 @@ class MemoryManager:
712
783
 
713
784
  return sorted_memories_list
714
785
 
786
+ def optimize_memories(
787
+ self,
788
+ user_id: Optional[str] = None,
789
+ strategy: Union[
790
+ MemoryOptimizationStrategyType, MemoryOptimizationStrategy
791
+ ] = MemoryOptimizationStrategyType.SUMMARIZE,
792
+ apply: bool = True,
793
+ ) -> List[UserMemory]:
794
+ """Optimize user memories using the specified strategy.
795
+
796
+ Args:
797
+ user_id: User ID to optimize memories for. Defaults to "default".
798
+ strategy: Optimization strategy. Can be:
799
+ - Enum: MemoryOptimizationStrategyType.SUMMARIZE
800
+ - Instance: Custom MemoryOptimizationStrategy instance
801
+ apply: If True, automatically replace memories in database.
802
+
803
+ Returns:
804
+ List of optimized UserMemory objects.
805
+ """
806
+ if user_id is None:
807
+ user_id = "default"
808
+
809
+ if isinstance(self.db, AsyncBaseDb):
810
+ raise ValueError(
811
+ "optimize_memories() is not supported with an async DB. Please use aoptimize_memories() instead."
812
+ )
813
+
814
+ # Get user memories
815
+ memories = self.get_user_memories(user_id=user_id)
816
+ if not memories:
817
+ log_debug("No memories to optimize")
818
+ return []
819
+
820
+ # Get strategy instance
821
+ if isinstance(strategy, MemoryOptimizationStrategyType):
822
+ strategy_instance = MemoryOptimizationStrategyFactory.create_strategy(strategy)
823
+ else:
824
+ # Already a strategy instance
825
+ strategy_instance = strategy
826
+
827
+ # Optimize memories using strategy
828
+ optimization_model = self.get_model()
829
+ optimized_memories = strategy_instance.optimize(memories=memories, model=optimization_model)
830
+
831
+ # Apply to database if requested
832
+ if apply:
833
+ log_debug(f"Applying optimized memories to database for user {user_id}")
834
+
835
+ if not self.db:
836
+ log_warning("Memory DB not provided. Cannot apply optimized memories.")
837
+ return optimized_memories
838
+
839
+ # Clear all existing memories for the user
840
+ self.clear_user_memories(user_id=user_id)
841
+
842
+ # Add all optimized memories
843
+ for opt_mem in optimized_memories:
844
+ # Ensure memory has an ID (generate if needed for new memories)
845
+ if not opt_mem.memory_id:
846
+ from uuid import uuid4
847
+
848
+ opt_mem.memory_id = str(uuid4())
849
+
850
+ self.db.upsert_user_memory(memory=opt_mem)
851
+
852
+ optimized_tokens = strategy_instance.count_tokens(optimized_memories)
853
+ log_debug(f"Optimization complete. New token count: {optimized_tokens}")
854
+
855
+ return optimized_memories
856
+
857
+ async def aoptimize_memories(
858
+ self,
859
+ user_id: Optional[str] = None,
860
+ strategy: Union[
861
+ MemoryOptimizationStrategyType, MemoryOptimizationStrategy
862
+ ] = MemoryOptimizationStrategyType.SUMMARIZE,
863
+ apply: bool = True,
864
+ ) -> List[UserMemory]:
865
+ """Async version of optimize_memories.
866
+
867
+ Args:
868
+ user_id: User ID to optimize memories for. Defaults to "default".
869
+ strategy: Optimization strategy. Can be:
870
+ - Enum: MemoryOptimizationStrategyType.SUMMARIZE
871
+ - Instance: Custom MemoryOptimizationStrategy instance
872
+ apply: If True, automatically replace memories in database.
873
+
874
+ Returns:
875
+ List of optimized UserMemory objects.
876
+ """
877
+ if user_id is None:
878
+ user_id = "default"
879
+
880
+ # Get user memories - handle both sync and async DBs
881
+ if isinstance(self.db, AsyncBaseDb):
882
+ memories = await self.aget_user_memories(user_id=user_id)
883
+ else:
884
+ memories = self.get_user_memories(user_id=user_id)
885
+
886
+ if not memories:
887
+ log_debug("No memories to optimize")
888
+ return []
889
+
890
+ # Get strategy instance
891
+ if isinstance(strategy, MemoryOptimizationStrategyType):
892
+ strategy_instance = MemoryOptimizationStrategyFactory.create_strategy(strategy)
893
+ else:
894
+ # Already a strategy instance
895
+ strategy_instance = strategy
896
+
897
+ # Optimize memories using strategy (async)
898
+ optimization_model = self.get_model()
899
+ optimized_memories = await strategy_instance.aoptimize(memories=memories, model=optimization_model)
900
+
901
+ # Apply to database if requested
902
+ if apply:
903
+ log_debug(f"Optimizing memories for user {user_id}")
904
+
905
+ if not self.db:
906
+ log_warning("Memory DB not provided. Cannot apply optimized memories.")
907
+ return optimized_memories
908
+
909
+ # Clear all existing memories for the user
910
+ await self.aclear_user_memories(user_id=user_id)
911
+
912
+ # Add all optimized memories
913
+ for opt_mem in optimized_memories:
914
+ # Ensure memory has an ID (generate if needed for new memories)
915
+ if not opt_mem.memory_id:
916
+ from uuid import uuid4
917
+
918
+ opt_mem.memory_id = str(uuid4())
919
+
920
+ if isinstance(self.db, AsyncBaseDb):
921
+ await self.db.upsert_user_memory(memory=opt_mem)
922
+ elif isinstance(self.db, BaseDb):
923
+ self.db.upsert_user_memory(memory=opt_mem)
924
+
925
+ optimized_tokens = strategy_instance.count_tokens(optimized_memories)
926
+ log_debug(f"Memory optimization complete. New token count: {optimized_tokens}")
927
+
928
+ return optimized_memories
929
+
715
930
  # --Memory Manager Functions--
716
931
  def determine_tools_for_model(self, tools: List[Callable]) -> List[Union[Function, dict]]:
717
932
  # Have to reset each time, because of different user IDs
@@ -0,0 +1,15 @@
1
+ """Memory optimization strategy implementations."""
2
+
3
+ from agno.memory.strategies.base import MemoryOptimizationStrategy
4
+ from agno.memory.strategies.summarize import SummarizeStrategy
5
+ from agno.memory.strategies.types import (
6
+ MemoryOptimizationStrategyFactory,
7
+ MemoryOptimizationStrategyType,
8
+ )
9
+
10
+ __all__ = [
11
+ "MemoryOptimizationStrategy",
12
+ "MemoryOptimizationStrategyFactory",
13
+ "MemoryOptimizationStrategyType",
14
+ "SummarizeStrategy",
15
+ ]
@@ -0,0 +1,67 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import List
3
+
4
+ from agno.db.schemas import UserMemory
5
+ from agno.models.base import Model
6
+ from agno.utils.tokens import count_tokens as count_text_tokens
7
+
8
+
9
+ class MemoryOptimizationStrategy(ABC):
10
+ """Abstract base class for memory optimization strategies.
11
+
12
+ Subclasses must implement optimize() and aoptimize().
13
+ get_system_prompt() is optional and only needed for LLM-based strategies.
14
+ """
15
+
16
+ def get_system_prompt(self) -> str:
17
+ """Get system prompt for this optimization strategy.
18
+
19
+ Returns:
20
+ System prompt string for LLM-based strategies.
21
+ """
22
+ raise NotImplementedError
23
+
24
+ @abstractmethod
25
+ def optimize(
26
+ self,
27
+ memories: List[UserMemory],
28
+ model: Model,
29
+ ) -> List[UserMemory]:
30
+ """Optimize memories synchronously.
31
+
32
+ Args:
33
+ memories: List of UserMemory objects to optimize
34
+ model: Model to use for optimization (if needed)
35
+
36
+ Returns:
37
+ List of optimized UserMemory objects
38
+ """
39
+ raise NotImplementedError
40
+
41
+ @abstractmethod
42
+ async def aoptimize(
43
+ self,
44
+ memories: List[UserMemory],
45
+ model: Model,
46
+ ) -> List[UserMemory]:
47
+ """Optimize memories asynchronously.
48
+
49
+ Args:
50
+ memories: List of UserMemory objects to optimize
51
+ model: Model to use for optimization (if needed)
52
+
53
+ Returns:
54
+ List of optimized UserMemory objects
55
+ """
56
+ raise NotImplementedError
57
+
58
+ def count_tokens(self, memories: List[UserMemory]) -> int:
59
+ """Count total tokens across all memories.
60
+
61
+ Args:
62
+ memories: List of UserMemory objects
63
+
64
+ Returns:
65
+ Total token count using tiktoken (or fallback estimation)
66
+ """
67
+ return sum(count_text_tokens(mem.memory or "") for mem in memories)