agno 2.2.1__py3-none-any.whl → 2.2.2__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 (67) hide show
  1. agno/agent/agent.py +735 -574
  2. agno/culture/manager.py +22 -24
  3. agno/db/async_postgres/__init__.py +1 -1
  4. agno/db/dynamo/dynamo.py +0 -2
  5. agno/db/firestore/firestore.py +0 -2
  6. agno/db/gcs_json/gcs_json_db.py +0 -4
  7. agno/db/gcs_json/utils.py +0 -24
  8. agno/db/in_memory/in_memory_db.py +0 -3
  9. agno/db/json/json_db.py +4 -10
  10. agno/db/json/utils.py +0 -24
  11. agno/db/mongo/mongo.py +0 -2
  12. agno/db/mysql/mysql.py +0 -3
  13. agno/db/postgres/__init__.py +1 -1
  14. agno/db/{async_postgres → postgres}/async_postgres.py +19 -22
  15. agno/db/postgres/postgres.py +7 -10
  16. agno/db/postgres/utils.py +106 -2
  17. agno/db/redis/redis.py +0 -2
  18. agno/db/singlestore/singlestore.py +0 -3
  19. agno/db/sqlite/__init__.py +2 -1
  20. agno/db/sqlite/async_sqlite.py +2269 -0
  21. agno/db/sqlite/sqlite.py +0 -2
  22. agno/db/sqlite/utils.py +96 -0
  23. agno/db/surrealdb/surrealdb.py +0 -6
  24. agno/knowledge/knowledge.py +3 -3
  25. agno/knowledge/reader/reader_factory.py +16 -0
  26. agno/knowledge/reader/tavily_reader.py +194 -0
  27. agno/memory/manager.py +28 -25
  28. agno/models/anthropic/claude.py +63 -6
  29. agno/models/base.py +251 -32
  30. agno/models/response.py +69 -0
  31. agno/os/router.py +7 -5
  32. agno/os/routers/memory/memory.py +2 -1
  33. agno/os/routers/memory/schemas.py +5 -2
  34. agno/os/schema.py +26 -20
  35. agno/os/utils.py +9 -2
  36. agno/run/agent.py +23 -30
  37. agno/run/base.py +17 -1
  38. agno/run/team.py +23 -29
  39. agno/run/workflow.py +17 -12
  40. agno/session/agent.py +3 -0
  41. agno/session/summary.py +4 -1
  42. agno/session/team.py +1 -1
  43. agno/team/team.py +591 -365
  44. agno/tools/dalle.py +2 -4
  45. agno/tools/eleven_labs.py +23 -25
  46. agno/tools/function.py +40 -0
  47. agno/tools/mcp/__init__.py +10 -0
  48. agno/tools/mcp/mcp.py +324 -0
  49. agno/tools/mcp/multi_mcp.py +347 -0
  50. agno/tools/mcp/params.py +24 -0
  51. agno/tools/slack.py +18 -3
  52. agno/tools/tavily.py +146 -0
  53. agno/utils/agent.py +366 -1
  54. agno/utils/mcp.py +92 -2
  55. agno/utils/media.py +166 -1
  56. agno/utils/print_response/workflow.py +17 -1
  57. agno/utils/team.py +89 -1
  58. agno/workflow/step.py +0 -1
  59. agno/workflow/types.py +10 -15
  60. {agno-2.2.1.dist-info → agno-2.2.2.dist-info}/METADATA +28 -25
  61. {agno-2.2.1.dist-info → agno-2.2.2.dist-info}/RECORD +64 -61
  62. agno/db/async_postgres/schemas.py +0 -139
  63. agno/db/async_postgres/utils.py +0 -347
  64. agno/tools/mcp.py +0 -679
  65. {agno-2.2.1.dist-info → agno-2.2.2.dist-info}/WHEEL +0 -0
  66. {agno-2.2.1.dist-info → agno-2.2.2.dist-info}/licenses/LICENSE +0 -0
  67. {agno-2.2.1.dist-info → agno-2.2.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2269 @@
1
+ import time
2
+ from datetime import date, datetime, timedelta, timezone
3
+ from pathlib import Path
4
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
5
+ from uuid import uuid4
6
+
7
+ from agno.db.base import AsyncBaseDb, SessionType
8
+ from agno.db.schemas.culture import CulturalKnowledge
9
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
10
+ from agno.db.schemas.knowledge import KnowledgeRow
11
+ from agno.db.schemas.memory import UserMemory
12
+ from agno.db.sqlite.schemas import get_table_schema_definition
13
+ from agno.db.sqlite.utils import (
14
+ abulk_upsert_metrics,
15
+ ais_table_available,
16
+ ais_valid_table,
17
+ apply_sorting,
18
+ calculate_date_metrics,
19
+ deserialize_cultural_knowledge_from_db,
20
+ fetch_all_sessions_data,
21
+ get_dates_to_calculate_metrics_for,
22
+ serialize_cultural_knowledge_for_db,
23
+ )
24
+ from agno.db.utils import deserialize_session_json_fields, serialize_session_json_fields
25
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
26
+ from agno.utils.log import log_debug, log_error, log_info, log_warning
27
+ from agno.utils.string import generate_id
28
+
29
+ try:
30
+ from sqlalchemy import Column, MetaData, Table, and_, func, select, text
31
+ from sqlalchemy.dialects import sqlite
32
+ from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
33
+ from sqlalchemy.schema import Index, UniqueConstraint
34
+ except ImportError:
35
+ raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`")
36
+
37
+
38
+ class AsyncSqliteDb(AsyncBaseDb):
39
+ def __init__(
40
+ self,
41
+ db_file: Optional[str] = None,
42
+ db_engine: Optional[AsyncEngine] = None,
43
+ db_url: Optional[str] = None,
44
+ session_table: Optional[str] = None,
45
+ culture_table: Optional[str] = None,
46
+ memory_table: Optional[str] = None,
47
+ metrics_table: Optional[str] = None,
48
+ eval_table: Optional[str] = None,
49
+ knowledge_table: Optional[str] = None,
50
+ id: Optional[str] = None,
51
+ ):
52
+ """
53
+ Async interface for interacting with a SQLite database.
54
+
55
+ The following order is used to determine the database connection:
56
+ 1. Use the db_engine
57
+ 2. Use the db_url
58
+ 3. Use the db_file
59
+ 4. Create a new database in the current directory
60
+
61
+ Args:
62
+ db_file (Optional[str]): The database file to connect to.
63
+ db_engine (Optional[AsyncEngine]): The SQLAlchemy async database engine to use.
64
+ db_url (Optional[str]): The database URL to connect to.
65
+ session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions.
66
+ culture_table (Optional[str]): Name of the table to store cultural notions.
67
+ memory_table (Optional[str]): Name of the table to store user memories.
68
+ metrics_table (Optional[str]): Name of the table to store metrics.
69
+ eval_table (Optional[str]): Name of the table to store evaluation runs data.
70
+ knowledge_table (Optional[str]): Name of the table to store knowledge documents data.
71
+ id (Optional[str]): ID of the database.
72
+
73
+ Raises:
74
+ ValueError: If none of the tables are provided.
75
+ """
76
+ if id is None:
77
+ seed = db_url or db_file or str(db_engine.url) if db_engine else "sqlite+aiosqlite:///agno.db"
78
+ id = generate_id(seed)
79
+
80
+ super().__init__(
81
+ id=id,
82
+ session_table=session_table,
83
+ culture_table=culture_table,
84
+ memory_table=memory_table,
85
+ metrics_table=metrics_table,
86
+ eval_table=eval_table,
87
+ knowledge_table=knowledge_table,
88
+ )
89
+
90
+ _engine: Optional[AsyncEngine] = db_engine
91
+ if _engine is None:
92
+ if db_url is not None:
93
+ _engine = create_async_engine(db_url)
94
+ elif db_file is not None:
95
+ db_path = Path(db_file).resolve()
96
+ db_path.parent.mkdir(parents=True, exist_ok=True)
97
+ db_file = str(db_path)
98
+ _engine = create_async_engine(f"sqlite+aiosqlite:///{db_path}")
99
+ else:
100
+ # If none of db_engine, db_url, or db_file are provided, create a db in the current directory
101
+ default_db_path = Path("./agno.db").resolve()
102
+ _engine = create_async_engine(f"sqlite+aiosqlite:///{default_db_path}")
103
+ db_file = str(default_db_path)
104
+ log_debug(f"Created SQLite database: {default_db_path}")
105
+
106
+ self.db_engine: AsyncEngine = _engine
107
+ self.db_url: Optional[str] = db_url
108
+ self.db_file: Optional[str] = db_file
109
+ self.metadata: MetaData = MetaData()
110
+
111
+ # Initialize database session factory
112
+ self.async_session_factory = async_sessionmaker(bind=self.db_engine, expire_on_commit=False)
113
+
114
+ # -- DB methods --
115
+
116
+ async def _create_table(self, table_name: str, table_type: str) -> Table:
117
+ """
118
+ Create a table with the appropriate schema based on the table type.
119
+
120
+ Args:
121
+ table_name (str): Name of the table to create
122
+ table_type (str): Type of table (used to get schema definition)
123
+
124
+ Returns:
125
+ Table: SQLAlchemy Table object
126
+ """
127
+ try:
128
+ table_schema = get_table_schema_definition(table_type)
129
+ log_debug(f"Creating table {table_name} with schema: {table_schema}")
130
+
131
+ columns: List[Column] = []
132
+ indexes: List[str] = []
133
+ unique_constraints: List[str] = []
134
+ schema_unique_constraints = table_schema.pop("_unique_constraints", [])
135
+
136
+ # Get the columns, indexes, and unique constraints from the table schema
137
+ for col_name, col_config in table_schema.items():
138
+ column_args = [col_name, col_config["type"]()]
139
+ column_kwargs = {}
140
+
141
+ if col_config.get("primary_key", False):
142
+ column_kwargs["primary_key"] = True
143
+ if "nullable" in col_config:
144
+ column_kwargs["nullable"] = col_config["nullable"]
145
+ if col_config.get("index", False):
146
+ indexes.append(col_name)
147
+ if col_config.get("unique", False):
148
+ column_kwargs["unique"] = True
149
+ unique_constraints.append(col_name)
150
+
151
+ columns.append(Column(*column_args, **column_kwargs)) # type: ignore
152
+
153
+ # Create the table object
154
+ table_metadata = MetaData()
155
+ table = Table(table_name, table_metadata, *columns)
156
+
157
+ # Add multi-column unique constraints with table-specific names
158
+ for constraint in schema_unique_constraints:
159
+ constraint_name = f"{table_name}_{constraint['name']}"
160
+ constraint_columns = constraint["columns"]
161
+ table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name))
162
+
163
+ # Add indexes to the table definition
164
+ for idx_col in indexes:
165
+ idx_name = f"idx_{table_name}_{idx_col}"
166
+ table.append_constraint(Index(idx_name, idx_col))
167
+
168
+ # Create table
169
+ async with self.db_engine.begin() as conn:
170
+ await conn.run_sync(table.create, checkfirst=True)
171
+
172
+ # Create indexes
173
+ for idx in table.indexes:
174
+ try:
175
+ log_debug(f"Creating index: {idx.name}")
176
+ # Check if index already exists
177
+ async with self.async_session_factory() as sess:
178
+ exists_query = text("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = :index_name")
179
+ result = await sess.execute(exists_query, {"index_name": idx.name})
180
+ exists = result.scalar() is not None
181
+ if exists:
182
+ log_debug(f"Index {idx.name} already exists in table {table_name}, skipping creation")
183
+ continue
184
+
185
+ async with self.db_engine.begin() as conn:
186
+ await conn.run_sync(idx.create)
187
+
188
+ except Exception as e:
189
+ log_warning(f"Error creating index {idx.name}: {e}")
190
+
191
+ log_info(f"Successfully created table '{table_name}'")
192
+ return table
193
+
194
+ except Exception as e:
195
+ log_error(f"Could not create table '{table_name}': {e}")
196
+ raise e
197
+
198
+ async def _get_table(self, table_type: str) -> Optional[Table]:
199
+ if table_type == "sessions":
200
+ if not hasattr(self, "session_table"):
201
+ self.session_table = await self._get_or_create_table(
202
+ table_name=self.session_table_name,
203
+ table_type=table_type,
204
+ )
205
+ return self.session_table
206
+
207
+ elif table_type == "memories":
208
+ if not hasattr(self, "memory_table"):
209
+ self.memory_table = await self._get_or_create_table(
210
+ table_name=self.memory_table_name,
211
+ table_type="memories",
212
+ )
213
+ return self.memory_table
214
+
215
+ elif table_type == "metrics":
216
+ if not hasattr(self, "metrics_table"):
217
+ self.metrics_table = await self._get_or_create_table(
218
+ table_name=self.metrics_table_name,
219
+ table_type="metrics",
220
+ )
221
+ return self.metrics_table
222
+
223
+ elif table_type == "evals":
224
+ if not hasattr(self, "eval_table"):
225
+ self.eval_table = await self._get_or_create_table(
226
+ table_name=self.eval_table_name,
227
+ table_type="evals",
228
+ )
229
+ return self.eval_table
230
+
231
+ elif table_type == "knowledge":
232
+ if not hasattr(self, "knowledge_table"):
233
+ self.knowledge_table = await self._get_or_create_table(
234
+ table_name=self.knowledge_table_name,
235
+ table_type="knowledge",
236
+ )
237
+ return self.knowledge_table
238
+
239
+ elif table_type == "culture":
240
+ if not hasattr(self, "culture_table"):
241
+ self.culture_table = await self._get_or_create_table(
242
+ table_name=self.culture_table_name,
243
+ table_type="culture",
244
+ )
245
+ return self.culture_table
246
+
247
+ else:
248
+ raise ValueError(f"Unknown table type: '{table_type}'")
249
+
250
+ async def _get_or_create_table(
251
+ self,
252
+ table_name: str,
253
+ table_type: str,
254
+ ) -> Table:
255
+ """
256
+ Check if the table exists and is valid, else create it.
257
+
258
+ Args:
259
+ table_name (str): Name of the table to get or create
260
+ table_type (str): Type of table (used to get schema definition)
261
+
262
+ Returns:
263
+ Table: SQLAlchemy Table object
264
+ """
265
+ async with self.async_session_factory() as sess, sess.begin():
266
+ table_is_available = await ais_table_available(session=sess, table_name=table_name)
267
+
268
+ if not table_is_available:
269
+ return await self._create_table(table_name=table_name, table_type=table_type)
270
+
271
+ # SQLite version of table validation (no schema)
272
+ if not await ais_valid_table(db_engine=self.db_engine, table_name=table_name, table_type=table_type):
273
+ raise ValueError(f"Table {table_name} has an invalid schema")
274
+
275
+ try:
276
+ async with self.db_engine.connect() as conn:
277
+
278
+ def load_table(connection):
279
+ return Table(table_name, self.metadata, autoload_with=connection)
280
+
281
+ table = await conn.run_sync(load_table)
282
+ log_debug(f"Loaded existing table {table_name}")
283
+ return table
284
+
285
+ except Exception as e:
286
+ log_error(f"Error loading existing table {table_name}: {e}")
287
+ raise e
288
+
289
+ # -- Session methods --
290
+
291
+ async def delete_session(self, session_id: str) -> bool:
292
+ """
293
+ Delete a session from the database.
294
+
295
+ Args:
296
+ session_id (str): ID of the session to delete
297
+
298
+ Returns:
299
+ bool: True if the session was deleted, False otherwise.
300
+
301
+ Raises:
302
+ Exception: If an error occurs during deletion.
303
+ """
304
+ try:
305
+ table = await self._get_table(table_type="sessions")
306
+ if table is None:
307
+ return False
308
+
309
+ async with self.async_session_factory() as sess, sess.begin():
310
+ delete_stmt = table.delete().where(table.c.session_id == session_id)
311
+ result = await sess.execute(delete_stmt)
312
+ if result.rowcount == 0: # type: ignore
313
+ log_debug(f"No session found to delete with session_id: {session_id}")
314
+ return False
315
+ else:
316
+ log_debug(f"Successfully deleted session with session_id: {session_id}")
317
+ return True
318
+
319
+ except Exception as e:
320
+ log_error(f"Error deleting session: {e}")
321
+ return False
322
+
323
+ async def delete_sessions(self, session_ids: List[str]) -> None:
324
+ """Delete all given sessions from the database.
325
+ Can handle multiple session types in the same run.
326
+
327
+ Args:
328
+ session_ids (List[str]): The IDs of the sessions to delete.
329
+
330
+ Raises:
331
+ Exception: If an error occurs during deletion.
332
+ """
333
+ try:
334
+ table = await self._get_table(table_type="sessions")
335
+ if table is None:
336
+ return
337
+
338
+ async with self.async_session_factory() as sess, sess.begin():
339
+ delete_stmt = table.delete().where(table.c.session_id.in_(session_ids))
340
+ result = await sess.execute(delete_stmt)
341
+
342
+ log_debug(f"Successfully deleted {result.rowcount} sessions") # type: ignore
343
+
344
+ except Exception as e:
345
+ log_error(f"Error deleting sessions: {e}")
346
+
347
+ async def get_session(
348
+ self,
349
+ session_id: str,
350
+ session_type: SessionType,
351
+ user_id: Optional[str] = None,
352
+ deserialize: Optional[bool] = True,
353
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
354
+ """
355
+ Read a session from the database.
356
+
357
+ Args:
358
+ session_id (str): ID of the session to read.
359
+ session_type (SessionType): Type of session to get.
360
+ user_id (Optional[str]): User ID to filter by. Defaults to None.
361
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
362
+
363
+ Returns:
364
+ Optional[Union[Session, Dict[str, Any]]]:
365
+ - When deserialize=True: Session object
366
+ - When deserialize=False: Session dictionary
367
+
368
+ Raises:
369
+ Exception: If an error occurs during retrieval.
370
+ """
371
+ try:
372
+ table = await self._get_table(table_type="sessions")
373
+ if table is None:
374
+ return None
375
+
376
+ async with self.async_session_factory() as sess, sess.begin():
377
+ stmt = select(table).where(table.c.session_id == session_id)
378
+
379
+ # Filtering
380
+ if user_id is not None:
381
+ stmt = stmt.where(table.c.user_id == user_id)
382
+
383
+ result = await sess.execute(stmt)
384
+ row = result.fetchone()
385
+ if row is None:
386
+ return None
387
+
388
+ session_raw = deserialize_session_json_fields(dict(row._mapping))
389
+ if not session_raw or not deserialize:
390
+ return session_raw
391
+
392
+ if session_type == SessionType.AGENT:
393
+ return AgentSession.from_dict(session_raw)
394
+ elif session_type == SessionType.TEAM:
395
+ return TeamSession.from_dict(session_raw)
396
+ elif session_type == SessionType.WORKFLOW:
397
+ return WorkflowSession.from_dict(session_raw)
398
+ else:
399
+ raise ValueError(f"Invalid session type: {session_type}")
400
+
401
+ except Exception as e:
402
+ log_debug(f"Exception reading from sessions table: {e}")
403
+ raise e
404
+
405
+ async def get_sessions(
406
+ self,
407
+ session_type: Optional[SessionType] = None,
408
+ user_id: Optional[str] = None,
409
+ component_id: Optional[str] = None,
410
+ session_name: Optional[str] = None,
411
+ start_timestamp: Optional[int] = None,
412
+ end_timestamp: Optional[int] = None,
413
+ limit: Optional[int] = None,
414
+ page: Optional[int] = None,
415
+ sort_by: Optional[str] = None,
416
+ sort_order: Optional[str] = None,
417
+ deserialize: Optional[bool] = True,
418
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
419
+ """
420
+ Get all sessions in the given table. Can filter by user_id and entity_id.
421
+ Args:
422
+ session_type (Optional[SessionType]): The type of session to get.
423
+ user_id (Optional[str]): The ID of the user to filter by.
424
+ component_id (Optional[str]): The ID of the agent / workflow to filter by.
425
+ session_name (Optional[str]): The name of the session to filter by.
426
+ start_timestamp (Optional[int]): The start timestamp to filter by.
427
+ end_timestamp (Optional[int]): The end timestamp to filter by.
428
+ limit (Optional[int]): The maximum number of sessions to return. Defaults to None.
429
+ page (Optional[int]): The page number to return. Defaults to None.
430
+ sort_by (Optional[str]): The field to sort by. Defaults to None.
431
+ sort_order (Optional[str]): The sort order. Defaults to None.
432
+ deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True.
433
+
434
+ Returns:
435
+ List[Session]:
436
+ - When deserialize=True: List of Session objects matching the criteria.
437
+ - When deserialize=False: List of Session dictionaries matching the criteria.
438
+
439
+ Raises:
440
+ Exception: If an error occurs during retrieval.
441
+ """
442
+ try:
443
+ table = await self._get_table(table_type="sessions")
444
+ if table is None:
445
+ return [] if deserialize else ([], 0)
446
+
447
+ async with self.async_session_factory() as sess, sess.begin():
448
+ stmt = select(table)
449
+
450
+ # Filtering
451
+ if user_id is not None:
452
+ stmt = stmt.where(table.c.user_id == user_id)
453
+ if component_id is not None:
454
+ if session_type == SessionType.AGENT:
455
+ stmt = stmt.where(table.c.agent_id == component_id)
456
+ elif session_type == SessionType.TEAM:
457
+ stmt = stmt.where(table.c.team_id == component_id)
458
+ elif session_type == SessionType.WORKFLOW:
459
+ stmt = stmt.where(table.c.workflow_id == component_id)
460
+ if start_timestamp is not None:
461
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
462
+ if end_timestamp is not None:
463
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
464
+ if session_name is not None:
465
+ stmt = stmt.where(table.c.session_data.like(f"%{session_name}%"))
466
+ if session_type is not None:
467
+ stmt = stmt.where(table.c.session_type == session_type.value)
468
+
469
+ # Getting total count
470
+ count_stmt = select(func.count()).select_from(stmt.alias())
471
+ count_result = await sess.execute(count_stmt)
472
+ total_count = count_result.scalar() or 0
473
+
474
+ # Sorting
475
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
476
+
477
+ # Paginating
478
+ if limit is not None:
479
+ stmt = stmt.limit(limit)
480
+ if page is not None:
481
+ stmt = stmt.offset((page - 1) * limit)
482
+
483
+ result = await sess.execute(stmt)
484
+ records = result.fetchall()
485
+ if records is None:
486
+ return [] if deserialize else ([], 0)
487
+
488
+ sessions_raw = [deserialize_session_json_fields(dict(record._mapping)) for record in records]
489
+ if not deserialize:
490
+ return sessions_raw, total_count
491
+ if not sessions_raw:
492
+ return []
493
+
494
+ if session_type == SessionType.AGENT:
495
+ return [AgentSession.from_dict(record) for record in sessions_raw] # type: ignore
496
+ elif session_type == SessionType.TEAM:
497
+ return [TeamSession.from_dict(record) for record in sessions_raw] # type: ignore
498
+ elif session_type == SessionType.WORKFLOW:
499
+ return [WorkflowSession.from_dict(record) for record in sessions_raw] # type: ignore
500
+ else:
501
+ raise ValueError(f"Invalid session type: {session_type}")
502
+
503
+ except Exception as e:
504
+ log_debug(f"Exception reading from sessions table: {e}")
505
+ raise e
506
+
507
+ async def rename_session(
508
+ self,
509
+ session_id: str,
510
+ session_type: SessionType,
511
+ session_name: str,
512
+ deserialize: Optional[bool] = True,
513
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
514
+ """
515
+ Rename a session in the database.
516
+
517
+ Args:
518
+ session_id (str): The ID of the session to rename.
519
+ session_type (SessionType): The type of session to rename.
520
+ session_name (str): The new name for the session.
521
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
522
+
523
+ Returns:
524
+ Optional[Union[Session, Dict[str, Any]]]:
525
+ - When deserialize=True: Session object
526
+ - When deserialize=False: Session dictionary
527
+
528
+ Raises:
529
+ Exception: If an error occurs during renaming.
530
+ """
531
+ try:
532
+ # Get the current session as a deserialized object
533
+ session = await self.get_session(session_id, session_type, deserialize=True)
534
+ if session is None:
535
+ return None
536
+
537
+ session = cast(Session, session)
538
+ # Update the session name
539
+ if session.session_data is None:
540
+ session.session_data = {}
541
+ session.session_data["session_name"] = session_name
542
+
543
+ # Upsert the updated session back to the database
544
+ return await self.upsert_session(session, deserialize=deserialize)
545
+
546
+ except Exception as e:
547
+ log_error(f"Exception renaming session: {e}")
548
+ raise e
549
+
550
+ async def upsert_session(
551
+ self, session: Session, deserialize: Optional[bool] = True
552
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
553
+ """
554
+ Insert or update a session in the database.
555
+
556
+ Args:
557
+ session (Session): The session data to upsert.
558
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
559
+
560
+ Returns:
561
+ Optional[Session]:
562
+ - When deserialize=True: Session object
563
+ - When deserialize=False: Session dictionary
564
+
565
+ Raises:
566
+ Exception: If an error occurs during upserting.
567
+ """
568
+ try:
569
+ table = await self._get_table(table_type="sessions")
570
+ if table is None:
571
+ return None
572
+
573
+ serialized_session = serialize_session_json_fields(session.to_dict())
574
+
575
+ if isinstance(session, AgentSession):
576
+ async with self.async_session_factory() as sess, sess.begin():
577
+ stmt = sqlite.insert(table).values(
578
+ session_id=serialized_session.get("session_id"),
579
+ session_type=SessionType.AGENT.value,
580
+ agent_id=serialized_session.get("agent_id"),
581
+ user_id=serialized_session.get("user_id"),
582
+ agent_data=serialized_session.get("agent_data"),
583
+ session_data=serialized_session.get("session_data"),
584
+ metadata=serialized_session.get("metadata"),
585
+ runs=serialized_session.get("runs"),
586
+ summary=serialized_session.get("summary"),
587
+ created_at=serialized_session.get("created_at"),
588
+ updated_at=serialized_session.get("created_at"),
589
+ )
590
+ stmt = stmt.on_conflict_do_update(
591
+ index_elements=["session_id"],
592
+ set_=dict(
593
+ agent_id=serialized_session.get("agent_id"),
594
+ user_id=serialized_session.get("user_id"),
595
+ runs=serialized_session.get("runs"),
596
+ summary=serialized_session.get("summary"),
597
+ agent_data=serialized_session.get("agent_data"),
598
+ session_data=serialized_session.get("session_data"),
599
+ metadata=serialized_session.get("metadata"),
600
+ updated_at=int(time.time()),
601
+ ),
602
+ )
603
+ stmt = stmt.returning(*table.columns) # type: ignore
604
+ result = await sess.execute(stmt)
605
+ row = result.fetchone()
606
+
607
+ session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None
608
+ if session_raw is None or not deserialize:
609
+ return session_raw
610
+ return AgentSession.from_dict(session_raw)
611
+
612
+ elif isinstance(session, TeamSession):
613
+ async with self.async_session_factory() as sess, sess.begin():
614
+ stmt = sqlite.insert(table).values(
615
+ session_id=serialized_session.get("session_id"),
616
+ session_type=SessionType.TEAM.value,
617
+ team_id=serialized_session.get("team_id"),
618
+ user_id=serialized_session.get("user_id"),
619
+ runs=serialized_session.get("runs"),
620
+ summary=serialized_session.get("summary"),
621
+ created_at=serialized_session.get("created_at"),
622
+ updated_at=serialized_session.get("created_at"),
623
+ team_data=serialized_session.get("team_data"),
624
+ session_data=serialized_session.get("session_data"),
625
+ metadata=serialized_session.get("metadata"),
626
+ )
627
+
628
+ stmt = stmt.on_conflict_do_update(
629
+ index_elements=["session_id"],
630
+ set_=dict(
631
+ team_id=serialized_session.get("team_id"),
632
+ user_id=serialized_session.get("user_id"),
633
+ summary=serialized_session.get("summary"),
634
+ runs=serialized_session.get("runs"),
635
+ team_data=serialized_session.get("team_data"),
636
+ session_data=serialized_session.get("session_data"),
637
+ metadata=serialized_session.get("metadata"),
638
+ updated_at=int(time.time()),
639
+ ),
640
+ )
641
+ stmt = stmt.returning(*table.columns) # type: ignore
642
+ result = await sess.execute(stmt)
643
+ row = result.fetchone()
644
+
645
+ session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None
646
+ if session_raw is None or not deserialize:
647
+ return session_raw
648
+ return TeamSession.from_dict(session_raw)
649
+
650
+ else:
651
+ async with self.async_session_factory() as sess, sess.begin():
652
+ stmt = sqlite.insert(table).values(
653
+ session_id=serialized_session.get("session_id"),
654
+ session_type=SessionType.WORKFLOW.value,
655
+ workflow_id=serialized_session.get("workflow_id"),
656
+ user_id=serialized_session.get("user_id"),
657
+ runs=serialized_session.get("runs"),
658
+ summary=serialized_session.get("summary"),
659
+ created_at=serialized_session.get("created_at") or int(time.time()),
660
+ updated_at=serialized_session.get("updated_at") or int(time.time()),
661
+ workflow_data=serialized_session.get("workflow_data"),
662
+ session_data=serialized_session.get("session_data"),
663
+ metadata=serialized_session.get("metadata"),
664
+ )
665
+ stmt = stmt.on_conflict_do_update(
666
+ index_elements=["session_id"],
667
+ set_=dict(
668
+ workflow_id=serialized_session.get("workflow_id"),
669
+ user_id=serialized_session.get("user_id"),
670
+ summary=serialized_session.get("summary"),
671
+ runs=serialized_session.get("runs"),
672
+ workflow_data=serialized_session.get("workflow_data"),
673
+ session_data=serialized_session.get("session_data"),
674
+ metadata=serialized_session.get("metadata"),
675
+ updated_at=int(time.time()),
676
+ ),
677
+ )
678
+ stmt = stmt.returning(*table.columns) # type: ignore
679
+ result = await sess.execute(stmt)
680
+ row = result.fetchone()
681
+
682
+ session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None
683
+ if session_raw is None or not deserialize:
684
+ return session_raw
685
+ return WorkflowSession.from_dict(session_raw)
686
+
687
+ except Exception as e:
688
+ log_warning(f"Exception upserting into table: {e}")
689
+ raise e
690
+
691
+ async def upsert_sessions(
692
+ self,
693
+ sessions: List[Session],
694
+ deserialize: Optional[bool] = True,
695
+ preserve_updated_at: bool = False,
696
+ ) -> List[Union[Session, Dict[str, Any]]]:
697
+ """
698
+ Bulk upsert multiple sessions for improved performance on large datasets.
699
+
700
+ Args:
701
+ sessions (List[Session]): List of sessions to upsert.
702
+ deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True.
703
+ preserve_updated_at (bool): If True, preserve the updated_at from the session object.
704
+
705
+ Returns:
706
+ List[Union[Session, Dict[str, Any]]]: List of upserted sessions.
707
+
708
+ Raises:
709
+ Exception: If an error occurs during bulk upsert.
710
+ """
711
+ if not sessions:
712
+ return []
713
+
714
+ try:
715
+ table = await self._get_table(table_type="sessions")
716
+ if table is None:
717
+ log_info("Sessions table not available, falling back to individual upserts")
718
+ return [
719
+ result
720
+ for session in sessions
721
+ if session is not None
722
+ for result in [await self.upsert_session(session, deserialize=deserialize)]
723
+ if result is not None
724
+ ]
725
+
726
+ # Group sessions by type for batch processing
727
+ agent_sessions = []
728
+ team_sessions = []
729
+ workflow_sessions = []
730
+
731
+ for session in sessions:
732
+ if isinstance(session, AgentSession):
733
+ agent_sessions.append(session)
734
+ elif isinstance(session, TeamSession):
735
+ team_sessions.append(session)
736
+ elif isinstance(session, WorkflowSession):
737
+ workflow_sessions.append(session)
738
+
739
+ results: List[Union[Session, Dict[str, Any]]] = []
740
+
741
+ async with self.async_session_factory() as sess, sess.begin():
742
+ # Bulk upsert agent sessions
743
+ if agent_sessions:
744
+ agent_data = []
745
+ for session in agent_sessions:
746
+ serialized_session = serialize_session_json_fields(session.to_dict())
747
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
748
+ updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time())
749
+ agent_data.append(
750
+ {
751
+ "session_id": serialized_session.get("session_id"),
752
+ "session_type": SessionType.AGENT.value,
753
+ "agent_id": serialized_session.get("agent_id"),
754
+ "user_id": serialized_session.get("user_id"),
755
+ "agent_data": serialized_session.get("agent_data"),
756
+ "session_data": serialized_session.get("session_data"),
757
+ "metadata": serialized_session.get("metadata"),
758
+ "runs": serialized_session.get("runs"),
759
+ "summary": serialized_session.get("summary"),
760
+ "created_at": serialized_session.get("created_at"),
761
+ "updated_at": updated_at,
762
+ }
763
+ )
764
+
765
+ if agent_data:
766
+ stmt = sqlite.insert(table)
767
+ stmt = stmt.on_conflict_do_update(
768
+ index_elements=["session_id"],
769
+ set_=dict(
770
+ agent_id=stmt.excluded.agent_id,
771
+ user_id=stmt.excluded.user_id,
772
+ agent_data=stmt.excluded.agent_data,
773
+ session_data=stmt.excluded.session_data,
774
+ metadata=stmt.excluded.metadata,
775
+ runs=stmt.excluded.runs,
776
+ summary=stmt.excluded.summary,
777
+ updated_at=stmt.excluded.updated_at,
778
+ ),
779
+ )
780
+ await sess.execute(stmt, agent_data)
781
+
782
+ # Fetch the results for agent sessions
783
+ agent_ids = [session.session_id for session in agent_sessions]
784
+ select_stmt = select(table).where(table.c.session_id.in_(agent_ids))
785
+ result = (await sess.execute(select_stmt)).fetchall()
786
+
787
+ for row in result:
788
+ session_dict = deserialize_session_json_fields(dict(row._mapping))
789
+ if deserialize:
790
+ deserialized_agent_session = AgentSession.from_dict(session_dict)
791
+ if deserialized_agent_session is None:
792
+ continue
793
+ results.append(deserialized_agent_session)
794
+ else:
795
+ results.append(session_dict)
796
+
797
+ # Bulk upsert team sessions
798
+ if team_sessions:
799
+ team_data = []
800
+ for session in team_sessions:
801
+ serialized_session = serialize_session_json_fields(session.to_dict())
802
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
803
+ updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time())
804
+ team_data.append(
805
+ {
806
+ "session_id": serialized_session.get("session_id"),
807
+ "session_type": SessionType.TEAM.value,
808
+ "team_id": serialized_session.get("team_id"),
809
+ "user_id": serialized_session.get("user_id"),
810
+ "runs": serialized_session.get("runs"),
811
+ "summary": serialized_session.get("summary"),
812
+ "created_at": serialized_session.get("created_at"),
813
+ "updated_at": updated_at,
814
+ "team_data": serialized_session.get("team_data"),
815
+ "session_data": serialized_session.get("session_data"),
816
+ "metadata": serialized_session.get("metadata"),
817
+ }
818
+ )
819
+
820
+ if team_data:
821
+ stmt = sqlite.insert(table)
822
+ stmt = stmt.on_conflict_do_update(
823
+ index_elements=["session_id"],
824
+ set_=dict(
825
+ team_id=stmt.excluded.team_id,
826
+ user_id=stmt.excluded.user_id,
827
+ team_data=stmt.excluded.team_data,
828
+ session_data=stmt.excluded.session_data,
829
+ metadata=stmt.excluded.metadata,
830
+ runs=stmt.excluded.runs,
831
+ summary=stmt.excluded.summary,
832
+ updated_at=stmt.excluded.updated_at,
833
+ ),
834
+ )
835
+ await sess.execute(stmt, team_data)
836
+
837
+ # Fetch the results for team sessions
838
+ team_ids = [session.session_id for session in team_sessions]
839
+ select_stmt = select(table).where(table.c.session_id.in_(team_ids))
840
+ result = (await sess.execute(select_stmt)).fetchall()
841
+
842
+ for row in result:
843
+ session_dict = deserialize_session_json_fields(dict(row._mapping))
844
+ if deserialize:
845
+ deserialized_team_session = TeamSession.from_dict(session_dict)
846
+ if deserialized_team_session is None:
847
+ continue
848
+ results.append(deserialized_team_session)
849
+ else:
850
+ results.append(session_dict)
851
+
852
+ # Bulk upsert workflow sessions
853
+ if workflow_sessions:
854
+ workflow_data = []
855
+ for session in workflow_sessions:
856
+ serialized_session = serialize_session_json_fields(session.to_dict())
857
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
858
+ updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time())
859
+ workflow_data.append(
860
+ {
861
+ "session_id": serialized_session.get("session_id"),
862
+ "session_type": SessionType.WORKFLOW.value,
863
+ "workflow_id": serialized_session.get("workflow_id"),
864
+ "user_id": serialized_session.get("user_id"),
865
+ "runs": serialized_session.get("runs"),
866
+ "summary": serialized_session.get("summary"),
867
+ "created_at": serialized_session.get("created_at"),
868
+ "updated_at": updated_at,
869
+ "workflow_data": serialized_session.get("workflow_data"),
870
+ "session_data": serialized_session.get("session_data"),
871
+ "metadata": serialized_session.get("metadata"),
872
+ }
873
+ )
874
+
875
+ if workflow_data:
876
+ stmt = sqlite.insert(table)
877
+ stmt = stmt.on_conflict_do_update(
878
+ index_elements=["session_id"],
879
+ set_=dict(
880
+ workflow_id=stmt.excluded.workflow_id,
881
+ user_id=stmt.excluded.user_id,
882
+ workflow_data=stmt.excluded.workflow_data,
883
+ session_data=stmt.excluded.session_data,
884
+ metadata=stmt.excluded.metadata,
885
+ runs=stmt.excluded.runs,
886
+ summary=stmt.excluded.summary,
887
+ updated_at=stmt.excluded.updated_at,
888
+ ),
889
+ )
890
+ await sess.execute(stmt, workflow_data)
891
+
892
+ # Fetch the results for workflow sessions
893
+ workflow_ids = [session.session_id for session in workflow_sessions]
894
+ select_stmt = select(table).where(table.c.session_id.in_(workflow_ids))
895
+ result = (await sess.execute(select_stmt)).fetchall()
896
+
897
+ for row in result:
898
+ session_dict = deserialize_session_json_fields(dict(row._mapping))
899
+ if deserialize:
900
+ deserialized_workflow_session = WorkflowSession.from_dict(session_dict)
901
+ if deserialized_workflow_session is None:
902
+ continue
903
+ results.append(deserialized_workflow_session)
904
+ else:
905
+ results.append(session_dict)
906
+
907
+ return results
908
+
909
+ except Exception as e:
910
+ log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}")
911
+ # Fallback to individual upserts
912
+ return [
913
+ result
914
+ for session in sessions
915
+ if session is not None
916
+ for result in [await self.upsert_session(session, deserialize=deserialize)]
917
+ if result is not None
918
+ ]
919
+
920
+ # -- Memory methods --
921
+
922
+ async def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None):
923
+ """Delete a user memory from the database.
924
+
925
+ Args:
926
+ memory_id (str): The ID of the memory to delete.
927
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
928
+
929
+ Returns:
930
+ bool: True if deletion was successful, False otherwise.
931
+
932
+ Raises:
933
+ Exception: If an error occurs during deletion.
934
+ """
935
+ try:
936
+ table = await self._get_table(table_type="memories")
937
+ if table is None:
938
+ return
939
+
940
+ async with self.async_session_factory() as sess, sess.begin():
941
+ delete_stmt = table.delete().where(table.c.memory_id == memory_id)
942
+ if user_id is not None:
943
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
944
+ result = await sess.execute(delete_stmt)
945
+
946
+ success = result.rowcount > 0 # type: ignore
947
+ if success:
948
+ log_debug(f"Successfully deleted user memory id: {memory_id}")
949
+ else:
950
+ log_debug(f"No user memory found with id: {memory_id}")
951
+
952
+ except Exception as e:
953
+ log_error(f"Error deleting user memory: {e}")
954
+ raise e
955
+
956
+ async def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None:
957
+ """Delete user memories from the database.
958
+
959
+ Args:
960
+ memory_ids (List[str]): The IDs of the memories to delete.
961
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
962
+
963
+ Raises:
964
+ Exception: If an error occurs during deletion.
965
+ """
966
+ try:
967
+ table = await self._get_table(table_type="memories")
968
+ if table is None:
969
+ return
970
+
971
+ async with self.async_session_factory() as sess, sess.begin():
972
+ delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids))
973
+ if user_id is not None:
974
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
975
+ result = await sess.execute(delete_stmt)
976
+ if result.rowcount == 0: # type: ignore
977
+ log_debug(f"No user memories found with ids: {memory_ids}")
978
+
979
+ except Exception as e:
980
+ log_error(f"Error deleting user memories: {e}")
981
+ raise e
982
+
983
+ async def get_all_memory_topics(self) -> List[str]:
984
+ """Get all memory topics from the database.
985
+
986
+ Returns:
987
+ List[str]: List of memory topics.
988
+ """
989
+ try:
990
+ table = await self._get_table(table_type="memories")
991
+ if table is None:
992
+ return []
993
+
994
+ async with self.async_session_factory() as sess, sess.begin():
995
+ # Select topics from all results
996
+ stmt = select(func.json_array_elements_text(table.c.topics)).select_from(table)
997
+ result = (await sess.execute(stmt)).fetchall()
998
+
999
+ return list(set([record[0] for record in result]))
1000
+
1001
+ except Exception as e:
1002
+ log_debug(f"Exception reading from memory table: {e}")
1003
+ raise e
1004
+
1005
+ async def get_user_memory(
1006
+ self,
1007
+ memory_id: str,
1008
+ deserialize: Optional[bool] = True,
1009
+ user_id: Optional[str] = None,
1010
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
1011
+ """Get a memory from the database.
1012
+
1013
+ Args:
1014
+ memory_id (str): The ID of the memory to get.
1015
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1016
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
1017
+
1018
+ Returns:
1019
+ Optional[Union[UserMemory, Dict[str, Any]]]:
1020
+ - When deserialize=True: UserMemory object
1021
+ - When deserialize=False: Memory dictionary
1022
+
1023
+ Raises:
1024
+ Exception: If an error occurs during retrieval.
1025
+ """
1026
+ try:
1027
+ table = await self._get_table(table_type="memories")
1028
+ if table is None:
1029
+ return None
1030
+
1031
+ async with self.async_session_factory() as sess, sess.begin():
1032
+ stmt = select(table).where(table.c.memory_id == memory_id)
1033
+ if user_id is not None:
1034
+ stmt = stmt.where(table.c.user_id == user_id)
1035
+ result = (await sess.execute(stmt)).fetchone()
1036
+ if result is None:
1037
+ return None
1038
+
1039
+ memory_raw = dict(result._mapping)
1040
+ if not memory_raw or not deserialize:
1041
+ return memory_raw
1042
+
1043
+ return UserMemory.from_dict(memory_raw)
1044
+
1045
+ except Exception as e:
1046
+ log_debug(f"Exception reading from memorytable: {e}")
1047
+ raise e
1048
+
1049
+ async def get_user_memories(
1050
+ self,
1051
+ user_id: Optional[str] = None,
1052
+ agent_id: Optional[str] = None,
1053
+ team_id: Optional[str] = None,
1054
+ topics: Optional[List[str]] = None,
1055
+ search_content: Optional[str] = None,
1056
+ limit: Optional[int] = None,
1057
+ page: Optional[int] = None,
1058
+ sort_by: Optional[str] = None,
1059
+ sort_order: Optional[str] = None,
1060
+ deserialize: Optional[bool] = True,
1061
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1062
+ """Get all memories from the database as UserMemory objects.
1063
+
1064
+ Args:
1065
+ user_id (Optional[str]): The ID of the user to filter by.
1066
+ agent_id (Optional[str]): The ID of the agent to filter by.
1067
+ team_id (Optional[str]): The ID of the team to filter by.
1068
+ topics (Optional[List[str]]): The topics to filter by.
1069
+ search_content (Optional[str]): The content to search for.
1070
+ limit (Optional[int]): The maximum number of memories to return.
1071
+ page (Optional[int]): The page number.
1072
+ sort_by (Optional[str]): The column to sort by.
1073
+ sort_order (Optional[str]): The order to sort by.
1074
+ deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True.
1075
+
1076
+
1077
+ Returns:
1078
+ Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1079
+ - When deserialize=True: List of UserMemory objects
1080
+ - When deserialize=False: List of UserMemory dictionaries and total count
1081
+
1082
+ Raises:
1083
+ Exception: If an error occurs during retrieval.
1084
+ """
1085
+ try:
1086
+ table = await self._get_table(table_type="memories")
1087
+ if table is None:
1088
+ return [] if deserialize else ([], 0)
1089
+
1090
+ async with self.async_session_factory() as sess, sess.begin():
1091
+ stmt = select(table)
1092
+
1093
+ # Filtering
1094
+ if user_id is not None:
1095
+ stmt = stmt.where(table.c.user_id == user_id)
1096
+ if agent_id is not None:
1097
+ stmt = stmt.where(table.c.agent_id == agent_id)
1098
+ if team_id is not None:
1099
+ stmt = stmt.where(table.c.team_id == team_id)
1100
+ if topics is not None:
1101
+ topic_conditions = [text(f"topics::text LIKE '%\"{topic}\"%'") for topic in topics]
1102
+ stmt = stmt.where(and_(*topic_conditions))
1103
+ if search_content is not None:
1104
+ stmt = stmt.where(table.c.memory.ilike(f"%{search_content}%"))
1105
+
1106
+ # Get total count after applying filtering
1107
+ count_stmt = select(func.count()).select_from(stmt.alias())
1108
+ total_count = (await sess.execute(count_stmt)).scalar() or 0
1109
+
1110
+ # Sorting
1111
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1112
+ # Paginating
1113
+ if limit is not None:
1114
+ stmt = stmt.limit(limit)
1115
+ if page is not None:
1116
+ stmt = stmt.offset((page - 1) * limit)
1117
+
1118
+ result = (await sess.execute(stmt)).fetchall()
1119
+ if not result:
1120
+ return [] if deserialize else ([], 0)
1121
+
1122
+ memories_raw = [dict(record._mapping) for record in result]
1123
+
1124
+ if not deserialize:
1125
+ return memories_raw, total_count
1126
+
1127
+ return [UserMemory.from_dict(record) for record in memories_raw]
1128
+
1129
+ except Exception as e:
1130
+ log_error(f"Error reading from memory table: {e}")
1131
+ raise e
1132
+
1133
+ async def get_user_memory_stats(
1134
+ self,
1135
+ limit: Optional[int] = None,
1136
+ page: Optional[int] = None,
1137
+ ) -> Tuple[List[Dict[str, Any]], int]:
1138
+ """Get user memories stats.
1139
+
1140
+ Args:
1141
+ limit (Optional[int]): The maximum number of user stats to return.
1142
+ page (Optional[int]): The page number.
1143
+
1144
+ Returns:
1145
+ Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count.
1146
+
1147
+ Example:
1148
+ (
1149
+ [
1150
+ {
1151
+ "user_id": "123",
1152
+ "total_memories": 10,
1153
+ "last_memory_updated_at": 1714560000,
1154
+ },
1155
+ ],
1156
+ total_count: 1,
1157
+ )
1158
+ """
1159
+ try:
1160
+ table = await self._get_table(table_type="memories")
1161
+ if table is None:
1162
+ return [], 0
1163
+
1164
+ async with self.async_session_factory() as sess, sess.begin():
1165
+ stmt = (
1166
+ select(
1167
+ table.c.user_id,
1168
+ func.count(table.c.memory_id).label("total_memories"),
1169
+ func.max(table.c.updated_at).label("last_memory_updated_at"),
1170
+ )
1171
+ .where(table.c.user_id.is_not(None))
1172
+ .group_by(table.c.user_id)
1173
+ .order_by(func.max(table.c.updated_at).desc())
1174
+ )
1175
+
1176
+ count_stmt = select(func.count()).select_from(stmt.alias())
1177
+ total_count = (await sess.execute(count_stmt)).scalar() or 0
1178
+
1179
+ # Pagination
1180
+ if limit is not None:
1181
+ stmt = stmt.limit(limit)
1182
+ if page is not None:
1183
+ stmt = stmt.offset((page - 1) * limit)
1184
+
1185
+ result = (await sess.execute(stmt)).fetchall()
1186
+ if not result:
1187
+ return [], 0
1188
+
1189
+ return [
1190
+ {
1191
+ "user_id": record.user_id, # type: ignore
1192
+ "total_memories": record.total_memories,
1193
+ "last_memory_updated_at": record.last_memory_updated_at,
1194
+ }
1195
+ for record in result
1196
+ ], total_count
1197
+
1198
+ except Exception as e:
1199
+ log_error(f"Error getting user memory stats: {e}")
1200
+ raise e
1201
+
1202
+ async def upsert_user_memory(
1203
+ self, memory: UserMemory, deserialize: Optional[bool] = True
1204
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
1205
+ """Upsert a user memory in the database.
1206
+
1207
+ Args:
1208
+ memory (UserMemory): The user memory to upsert.
1209
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1210
+
1211
+ Returns:
1212
+ Optional[Union[UserMemory, Dict[str, Any]]]:
1213
+ - When deserialize=True: UserMemory object
1214
+ - When deserialize=False: UserMemory dictionary
1215
+
1216
+ Raises:
1217
+ Exception: If an error occurs during upsert.
1218
+ """
1219
+ try:
1220
+ table = await self._get_table(table_type="memories")
1221
+ if table is None:
1222
+ return None
1223
+
1224
+ if memory.memory_id is None:
1225
+ memory.memory_id = str(uuid4())
1226
+
1227
+ async with self.async_session_factory() as sess, sess.begin():
1228
+ stmt = sqlite.insert(table).values(
1229
+ user_id=memory.user_id,
1230
+ agent_id=memory.agent_id,
1231
+ team_id=memory.team_id,
1232
+ memory_id=memory.memory_id,
1233
+ memory=memory.memory,
1234
+ topics=memory.topics,
1235
+ input=memory.input,
1236
+ updated_at=int(time.time()),
1237
+ )
1238
+ stmt = stmt.on_conflict_do_update( # type: ignore
1239
+ index_elements=["memory_id"],
1240
+ set_=dict(
1241
+ memory=memory.memory,
1242
+ topics=memory.topics,
1243
+ input=memory.input,
1244
+ updated_at=int(time.time()),
1245
+ ),
1246
+ ).returning(table)
1247
+
1248
+ result = await sess.execute(stmt)
1249
+ row = result.fetchone()
1250
+
1251
+ if row is None:
1252
+ return None
1253
+
1254
+ memory_raw = dict(row._mapping)
1255
+ if not memory_raw or not deserialize:
1256
+ return memory_raw
1257
+
1258
+ return UserMemory.from_dict(memory_raw)
1259
+
1260
+ except Exception as e:
1261
+ log_error(f"Error upserting user memory: {e}")
1262
+ raise e
1263
+
1264
+ async def upsert_memories(
1265
+ self,
1266
+ memories: List[UserMemory],
1267
+ deserialize: Optional[bool] = True,
1268
+ preserve_updated_at: bool = False,
1269
+ ) -> List[Union[UserMemory, Dict[str, Any]]]:
1270
+ """
1271
+ Bulk upsert multiple user memories for improved performance on large datasets.
1272
+
1273
+ Args:
1274
+ memories (List[UserMemory]): List of memories to upsert.
1275
+ deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True.
1276
+
1277
+ Returns:
1278
+ List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories.
1279
+
1280
+ Raises:
1281
+ Exception: If an error occurs during bulk upsert.
1282
+ """
1283
+ if not memories:
1284
+ return []
1285
+
1286
+ try:
1287
+ table = await self._get_table(table_type="memories")
1288
+ if table is None:
1289
+ log_info("Memories table not available, falling back to individual upserts")
1290
+ return [
1291
+ result
1292
+ for memory in memories
1293
+ if memory is not None
1294
+ for result in [await self.upsert_user_memory(memory, deserialize=deserialize)]
1295
+ if result is not None
1296
+ ]
1297
+ # Prepare bulk data
1298
+ bulk_data = []
1299
+ current_time = int(time.time())
1300
+ for memory in memories:
1301
+ if memory.memory_id is None:
1302
+ memory.memory_id = str(uuid4())
1303
+
1304
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
1305
+ updated_at = memory.updated_at if preserve_updated_at else current_time
1306
+ bulk_data.append(
1307
+ {
1308
+ "user_id": memory.user_id,
1309
+ "agent_id": memory.agent_id,
1310
+ "team_id": memory.team_id,
1311
+ "memory_id": memory.memory_id,
1312
+ "memory": memory.memory,
1313
+ "topics": memory.topics,
1314
+ "updated_at": updated_at,
1315
+ }
1316
+ )
1317
+
1318
+ results: List[Union[UserMemory, Dict[str, Any]]] = []
1319
+
1320
+ async with self.async_session_factory() as sess, sess.begin():
1321
+ # Bulk upsert memories using SQLite ON CONFLICT DO UPDATE
1322
+ stmt = sqlite.insert(table)
1323
+ stmt = stmt.on_conflict_do_update(
1324
+ index_elements=["memory_id"],
1325
+ set_=dict(
1326
+ memory=stmt.excluded.memory,
1327
+ topics=stmt.excluded.topics,
1328
+ input=stmt.excluded.input,
1329
+ agent_id=stmt.excluded.agent_id,
1330
+ team_id=stmt.excluded.team_id,
1331
+ updated_at=stmt.excluded.updated_at,
1332
+ ),
1333
+ )
1334
+ await sess.execute(stmt, bulk_data)
1335
+
1336
+ # Fetch results
1337
+ memory_ids = [memory.memory_id for memory in memories if memory.memory_id]
1338
+ select_stmt = select(table).where(table.c.memory_id.in_(memory_ids))
1339
+ result = (await sess.execute(select_stmt)).fetchall()
1340
+
1341
+ for row in result:
1342
+ memory_dict = dict(row._mapping)
1343
+ if deserialize:
1344
+ results.append(UserMemory.from_dict(memory_dict))
1345
+ else:
1346
+ results.append(memory_dict)
1347
+
1348
+ return results
1349
+
1350
+ except Exception as e:
1351
+ log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}")
1352
+
1353
+ # Fallback to individual upserts
1354
+ return [
1355
+ result
1356
+ for memory in memories
1357
+ if memory is not None
1358
+ for result in [await self.upsert_user_memory(memory, deserialize=deserialize)]
1359
+ if result is not None
1360
+ ]
1361
+
1362
+ async def clear_memories(self) -> None:
1363
+ """Delete all memories from the database.
1364
+
1365
+ Raises:
1366
+ Exception: If an error occurs during deletion.
1367
+ """
1368
+ try:
1369
+ table = await self._get_table(table_type="memories")
1370
+ if table is None:
1371
+ return
1372
+
1373
+ async with self.async_session_factory() as sess, sess.begin():
1374
+ await sess.execute(table.delete())
1375
+
1376
+ except Exception as e:
1377
+ from agno.utils.log import log_warning
1378
+
1379
+ log_warning(f"Exception deleting all memories: {e}")
1380
+ raise e
1381
+
1382
+ # -- Metrics methods --
1383
+
1384
+ async def _get_all_sessions_for_metrics_calculation(
1385
+ self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
1386
+ ) -> List[Dict[str, Any]]:
1387
+ """
1388
+ Get all sessions of all types (agent, team, workflow) as raw dictionaries.
1389
+
1390
+ Args:
1391
+ start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None.
1392
+ end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None.
1393
+
1394
+ Returns:
1395
+ List[Dict[str, Any]]: List of session dictionaries with session_type field.
1396
+
1397
+ Raises:
1398
+ Exception: If an error occurs during retrieval.
1399
+ """
1400
+ try:
1401
+ table = await self._get_table(table_type="sessions")
1402
+ if table is None:
1403
+ return []
1404
+
1405
+ stmt = select(
1406
+ table.c.user_id,
1407
+ table.c.session_data,
1408
+ table.c.runs,
1409
+ table.c.created_at,
1410
+ table.c.session_type,
1411
+ )
1412
+
1413
+ if start_timestamp is not None:
1414
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
1415
+ if end_timestamp is not None:
1416
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
1417
+
1418
+ async with self.async_session_factory() as sess:
1419
+ result = (await sess.execute(stmt)).fetchall()
1420
+ return [dict(record._mapping) for record in result]
1421
+
1422
+ except Exception as e:
1423
+ log_error(f"Error reading from sessions table: {e}")
1424
+ raise e
1425
+
1426
+ async def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]:
1427
+ """Get the first date for which metrics calculation is needed:
1428
+
1429
+ 1. If there are metrics records, return the date of the first day without a complete metrics record.
1430
+ 2. If there are no metrics records, return the date of the first recorded session.
1431
+ 3. If there are no metrics records and no sessions records, return None.
1432
+
1433
+ Args:
1434
+ table (Table): The table to get the starting date for.
1435
+
1436
+ Returns:
1437
+ Optional[date]: The starting date for which metrics calculation is needed.
1438
+ """
1439
+ async with self.async_session_factory() as sess:
1440
+ stmt = select(table).order_by(table.c.date.desc()).limit(1)
1441
+ result = (await sess.execute(stmt)).fetchone()
1442
+
1443
+ # 1. Return the date of the first day without a complete metrics record.
1444
+ if result is not None:
1445
+ if result.completed:
1446
+ return result._mapping["date"] + timedelta(days=1)
1447
+ else:
1448
+ return result._mapping["date"]
1449
+
1450
+ # 2. No metrics records. Return the date of the first recorded session.
1451
+ first_session, _ = await self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False)
1452
+ first_session_date = first_session[0]["created_at"] if first_session else None # type: ignore
1453
+
1454
+ # 3. No metrics records and no sessions records. Return None.
1455
+ if not first_session_date:
1456
+ return None
1457
+
1458
+ return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date()
1459
+
1460
+ async def calculate_metrics(self) -> Optional[list[dict]]:
1461
+ """Calculate metrics for all dates without complete metrics.
1462
+
1463
+ Returns:
1464
+ Optional[list[dict]]: The calculated metrics.
1465
+
1466
+ Raises:
1467
+ Exception: If an error occurs during metrics calculation.
1468
+ """
1469
+ try:
1470
+ table = await self._get_table(table_type="metrics")
1471
+ if table is None:
1472
+ return None
1473
+
1474
+ starting_date = await self._get_metrics_calculation_starting_date(table)
1475
+ if starting_date is None:
1476
+ log_info("No session data found. Won't calculate metrics.")
1477
+ return None
1478
+
1479
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
1480
+ if not dates_to_process:
1481
+ log_info("Metrics already calculated for all relevant dates.")
1482
+ return None
1483
+
1484
+ start_timestamp = int(
1485
+ datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp()
1486
+ )
1487
+ end_timestamp = int(
1488
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time())
1489
+ .replace(tzinfo=timezone.utc)
1490
+ .timestamp()
1491
+ )
1492
+
1493
+ sessions = await self._get_all_sessions_for_metrics_calculation(
1494
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
1495
+ )
1496
+ all_sessions_data = fetch_all_sessions_data(
1497
+ sessions=sessions,
1498
+ dates_to_process=dates_to_process,
1499
+ start_timestamp=start_timestamp,
1500
+ )
1501
+ if not all_sessions_data:
1502
+ log_info("No new session data found. Won't calculate metrics.")
1503
+ return None
1504
+
1505
+ results = []
1506
+ metrics_records = []
1507
+
1508
+ for date_to_process in dates_to_process:
1509
+ date_key = date_to_process.isoformat()
1510
+ sessions_for_date = all_sessions_data.get(date_key, {})
1511
+
1512
+ # Skip dates with no sessions
1513
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
1514
+ continue
1515
+
1516
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
1517
+ metrics_records.append(metrics_record)
1518
+
1519
+ if metrics_records:
1520
+ async with self.async_session_factory() as sess, sess.begin():
1521
+ results = await abulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records)
1522
+
1523
+ log_debug("Updated metrics calculations")
1524
+
1525
+ return results
1526
+
1527
+ except Exception as e:
1528
+ log_error(f"Error refreshing metrics: {e}")
1529
+ raise e
1530
+
1531
+ async def get_metrics(
1532
+ self,
1533
+ starting_date: Optional[date] = None,
1534
+ ending_date: Optional[date] = None,
1535
+ ) -> Tuple[List[dict], Optional[int]]:
1536
+ """Get all metrics matching the given date range.
1537
+
1538
+ Args:
1539
+ starting_date (Optional[date]): The starting date to filter metrics by.
1540
+ ending_date (Optional[date]): The ending date to filter metrics by.
1541
+
1542
+ Returns:
1543
+ Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update.
1544
+
1545
+ Raises:
1546
+ Exception: If an error occurs during retrieval.
1547
+ """
1548
+ try:
1549
+ table = await self._get_table(table_type="metrics")
1550
+ if table is None:
1551
+ return [], None
1552
+
1553
+ async with self.async_session_factory() as sess, sess.begin():
1554
+ stmt = select(table)
1555
+ if starting_date:
1556
+ stmt = stmt.where(table.c.date >= starting_date)
1557
+ if ending_date:
1558
+ stmt = stmt.where(table.c.date <= ending_date)
1559
+ result = (await sess.execute(stmt)).fetchall()
1560
+ if not result:
1561
+ return [], None
1562
+
1563
+ # Get the latest updated_at
1564
+ latest_stmt = select(func.max(table.c.updated_at))
1565
+ latest_updated_at = (await sess.execute(latest_stmt)).scalar()
1566
+
1567
+ return [dict(row._mapping) for row in result], latest_updated_at
1568
+
1569
+ except Exception as e:
1570
+ log_error(f"Error getting metrics: {e}")
1571
+ raise e
1572
+
1573
+ # -- Knowledge methods --
1574
+
1575
+ async def delete_knowledge_content(self, id: str):
1576
+ """Delete a knowledge row from the database.
1577
+
1578
+ Args:
1579
+ id (str): The ID of the knowledge row to delete.
1580
+
1581
+ Raises:
1582
+ Exception: If an error occurs during deletion.
1583
+ """
1584
+ table = await self._get_table(table_type="knowledge")
1585
+ if table is None:
1586
+ return
1587
+
1588
+ try:
1589
+ async with self.async_session_factory() as sess, sess.begin():
1590
+ stmt = table.delete().where(table.c.id == id)
1591
+ await sess.execute(stmt)
1592
+
1593
+ except Exception as e:
1594
+ log_error(f"Error deleting knowledge content: {e}")
1595
+ raise e
1596
+
1597
+ async def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1598
+ """Get a knowledge row from the database.
1599
+
1600
+ Args:
1601
+ id (str): The ID of the knowledge row to get.
1602
+
1603
+ Returns:
1604
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1605
+
1606
+ Raises:
1607
+ Exception: If an error occurs during retrieval.
1608
+ """
1609
+ table = await self._get_table(table_type="knowledge")
1610
+ if table is None:
1611
+ return None
1612
+
1613
+ try:
1614
+ async with self.async_session_factory() as sess, sess.begin():
1615
+ stmt = select(table).where(table.c.id == id)
1616
+ result = (await sess.execute(stmt)).fetchone()
1617
+ if result is None:
1618
+ return None
1619
+
1620
+ return KnowledgeRow.model_validate(result._mapping)
1621
+
1622
+ except Exception as e:
1623
+ log_error(f"Error getting knowledge content: {e}")
1624
+ raise e
1625
+
1626
+ async def get_knowledge_contents(
1627
+ self,
1628
+ limit: Optional[int] = None,
1629
+ page: Optional[int] = None,
1630
+ sort_by: Optional[str] = None,
1631
+ sort_order: Optional[str] = None,
1632
+ ) -> Tuple[List[KnowledgeRow], int]:
1633
+ """Get all knowledge contents from the database.
1634
+
1635
+ Args:
1636
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1637
+ page (Optional[int]): The page number.
1638
+ sort_by (Optional[str]): The column to sort by.
1639
+ sort_order (Optional[str]): The order to sort by.
1640
+
1641
+ Returns:
1642
+ Tuple[List[KnowledgeRow], int]: The knowledge contents and total count.
1643
+
1644
+ Raises:
1645
+ Exception: If an error occurs during retrieval.
1646
+ """
1647
+ table = await self._get_table(table_type="knowledge")
1648
+ if table is None:
1649
+ return [], 0
1650
+
1651
+ try:
1652
+ async with self.async_session_factory() as sess, sess.begin():
1653
+ stmt = select(table)
1654
+
1655
+ # Apply sorting
1656
+ if sort_by is not None:
1657
+ stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1))
1658
+
1659
+ # Get total count before applying limit and pagination
1660
+ count_stmt = select(func.count()).select_from(stmt.alias())
1661
+ total_count = (await sess.execute(count_stmt)).scalar() or 0
1662
+
1663
+ # Apply pagination after count
1664
+ if limit is not None:
1665
+ stmt = stmt.limit(limit)
1666
+ if page is not None:
1667
+ stmt = stmt.offset((page - 1) * limit)
1668
+
1669
+ result = (await sess.execute(stmt)).fetchall()
1670
+ return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count
1671
+
1672
+ except Exception as e:
1673
+ log_error(f"Error getting knowledge contents: {e}")
1674
+ raise e
1675
+
1676
+ async def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1677
+ """Upsert knowledge content in the database.
1678
+
1679
+ Args:
1680
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1681
+
1682
+ Returns:
1683
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1684
+ """
1685
+ try:
1686
+ table = await self._get_table(table_type="knowledge")
1687
+ if table is None:
1688
+ return None
1689
+
1690
+ async with self.async_session_factory() as sess, sess.begin():
1691
+ update_fields = {
1692
+ k: v
1693
+ for k, v in {
1694
+ "name": knowledge_row.name,
1695
+ "description": knowledge_row.description,
1696
+ "metadata": knowledge_row.metadata,
1697
+ "type": knowledge_row.type,
1698
+ "size": knowledge_row.size,
1699
+ "linked_to": knowledge_row.linked_to,
1700
+ "access_count": knowledge_row.access_count,
1701
+ "status": knowledge_row.status,
1702
+ "status_message": knowledge_row.status_message,
1703
+ "created_at": knowledge_row.created_at,
1704
+ "updated_at": knowledge_row.updated_at,
1705
+ "external_id": knowledge_row.external_id,
1706
+ }.items()
1707
+ # Filtering out None fields if updating
1708
+ if v is not None
1709
+ }
1710
+
1711
+ stmt = (
1712
+ sqlite.insert(table)
1713
+ .values(knowledge_row.model_dump())
1714
+ .on_conflict_do_update(index_elements=["id"], set_=update_fields)
1715
+ )
1716
+ await sess.execute(stmt)
1717
+
1718
+ return knowledge_row
1719
+
1720
+ except Exception as e:
1721
+ log_error(f"Error upserting knowledge content: {e}")
1722
+ raise e
1723
+
1724
+ # -- Eval methods --
1725
+
1726
+ async def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1727
+ """Create an EvalRunRecord in the database.
1728
+
1729
+ Args:
1730
+ eval_run (EvalRunRecord): The eval run to create.
1731
+
1732
+ Returns:
1733
+ Optional[EvalRunRecord]: The created eval run, or None if the operation fails.
1734
+
1735
+ Raises:
1736
+ Exception: If an error occurs during creation.
1737
+ """
1738
+ try:
1739
+ table = await self._get_table(table_type="evals")
1740
+ if table is None:
1741
+ return None
1742
+
1743
+ async with self.async_session_factory() as sess, sess.begin():
1744
+ current_time = int(time.time())
1745
+ stmt = sqlite.insert(table).values(
1746
+ {
1747
+ "created_at": current_time,
1748
+ "updated_at": current_time,
1749
+ **eval_run.model_dump(),
1750
+ }
1751
+ )
1752
+ await sess.execute(stmt)
1753
+
1754
+ log_debug(f"Created eval run with id '{eval_run.run_id}'")
1755
+
1756
+ return eval_run
1757
+
1758
+ except Exception as e:
1759
+ log_error(f"Error creating eval run: {e}")
1760
+ raise e
1761
+
1762
+ async def delete_eval_run(self, eval_run_id: str) -> None:
1763
+ """Delete an eval run from the database.
1764
+
1765
+ Args:
1766
+ eval_run_id (str): The ID of the eval run to delete.
1767
+ """
1768
+ try:
1769
+ table = await self._get_table(table_type="evals")
1770
+ if table is None:
1771
+ return
1772
+
1773
+ async with self.async_session_factory() as sess, sess.begin():
1774
+ stmt = table.delete().where(table.c.run_id == eval_run_id)
1775
+ result = await sess.execute(stmt)
1776
+ if result.rowcount == 0: # type: ignore
1777
+ log_warning(f"No eval run found with ID: {eval_run_id}")
1778
+ else:
1779
+ log_debug(f"Deleted eval run with ID: {eval_run_id}")
1780
+
1781
+ except Exception as e:
1782
+ log_error(f"Error deleting eval run {eval_run_id}: {e}")
1783
+ raise e
1784
+
1785
+ async def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1786
+ """Delete multiple eval runs from the database.
1787
+
1788
+ Args:
1789
+ eval_run_ids (List[str]): List of eval run IDs to delete.
1790
+ """
1791
+ try:
1792
+ table = await self._get_table(table_type="evals")
1793
+ if table is None:
1794
+ return
1795
+
1796
+ async with self.async_session_factory() as sess, sess.begin():
1797
+ stmt = table.delete().where(table.c.run_id.in_(eval_run_ids))
1798
+ result = await sess.execute(stmt)
1799
+ if result.rowcount == 0: # type: ignore
1800
+ log_debug(f"No eval runs found with IDs: {eval_run_ids}")
1801
+ else:
1802
+ log_debug(f"Deleted {result.rowcount} eval runs") # type: ignore
1803
+
1804
+ except Exception as e:
1805
+ log_error(f"Error deleting eval runs {eval_run_ids}: {e}")
1806
+ raise e
1807
+
1808
+ async def get_eval_run(
1809
+ self, eval_run_id: str, deserialize: Optional[bool] = True
1810
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1811
+ """Get an eval run from the database.
1812
+
1813
+ Args:
1814
+ eval_run_id (str): The ID of the eval run to get.
1815
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1816
+
1817
+ Returns:
1818
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1819
+ - When deserialize=True: EvalRunRecord object
1820
+ - When deserialize=False: EvalRun dictionary
1821
+
1822
+ Raises:
1823
+ Exception: If an error occurs during retrieval.
1824
+ """
1825
+ try:
1826
+ table = await self._get_table(table_type="evals")
1827
+ if table is None:
1828
+ return None
1829
+
1830
+ async with self.async_session_factory() as sess, sess.begin():
1831
+ stmt = select(table).where(table.c.run_id == eval_run_id)
1832
+ result = (await sess.execute(stmt)).fetchone()
1833
+ if result is None:
1834
+ return None
1835
+
1836
+ eval_run_raw = dict(result._mapping)
1837
+ if not eval_run_raw or not deserialize:
1838
+ return eval_run_raw
1839
+
1840
+ return EvalRunRecord.model_validate(eval_run_raw)
1841
+
1842
+ except Exception as e:
1843
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1844
+ raise e
1845
+
1846
+ async def get_eval_runs(
1847
+ self,
1848
+ limit: Optional[int] = None,
1849
+ page: Optional[int] = None,
1850
+ sort_by: Optional[str] = None,
1851
+ sort_order: Optional[str] = None,
1852
+ agent_id: Optional[str] = None,
1853
+ team_id: Optional[str] = None,
1854
+ workflow_id: Optional[str] = None,
1855
+ model_id: Optional[str] = None,
1856
+ filter_type: Optional[EvalFilterType] = None,
1857
+ eval_type: Optional[List[EvalType]] = None,
1858
+ deserialize: Optional[bool] = True,
1859
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1860
+ """Get all eval runs from the database.
1861
+
1862
+ Args:
1863
+ limit (Optional[int]): The maximum number of eval runs to return.
1864
+ page (Optional[int]): The page number.
1865
+ sort_by (Optional[str]): The column to sort by.
1866
+ sort_order (Optional[str]): The order to sort by.
1867
+ agent_id (Optional[str]): The ID of the agent to filter by.
1868
+ team_id (Optional[str]): The ID of the team to filter by.
1869
+ workflow_id (Optional[str]): The ID of the workflow to filter by.
1870
+ model_id (Optional[str]): The ID of the model to filter by.
1871
+ eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by.
1872
+ filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow).
1873
+ deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True.
1874
+ create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist.
1875
+
1876
+ Returns:
1877
+ Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1878
+ - When deserialize=True: List of EvalRunRecord objects
1879
+ - When deserialize=False: List of EvalRun dictionaries and total count
1880
+
1881
+ Raises:
1882
+ Exception: If an error occurs during retrieval.
1883
+ """
1884
+ try:
1885
+ table = await self._get_table(table_type="evals")
1886
+ if table is None:
1887
+ return [] if deserialize else ([], 0)
1888
+
1889
+ async with self.async_session_factory() as sess, sess.begin():
1890
+ stmt = select(table)
1891
+
1892
+ # Filtering
1893
+ if agent_id is not None:
1894
+ stmt = stmt.where(table.c.agent_id == agent_id)
1895
+ if team_id is not None:
1896
+ stmt = stmt.where(table.c.team_id == team_id)
1897
+ if workflow_id is not None:
1898
+ stmt = stmt.where(table.c.workflow_id == workflow_id)
1899
+ if model_id is not None:
1900
+ stmt = stmt.where(table.c.model_id == model_id)
1901
+ if eval_type is not None and len(eval_type) > 0:
1902
+ stmt = stmt.where(table.c.eval_type.in_(eval_type))
1903
+ if filter_type is not None:
1904
+ if filter_type == EvalFilterType.AGENT:
1905
+ stmt = stmt.where(table.c.agent_id.is_not(None))
1906
+ elif filter_type == EvalFilterType.TEAM:
1907
+ stmt = stmt.where(table.c.team_id.is_not(None))
1908
+ elif filter_type == EvalFilterType.WORKFLOW:
1909
+ stmt = stmt.where(table.c.workflow_id.is_not(None))
1910
+
1911
+ # Get total count after applying filtering
1912
+ count_stmt = select(func.count()).select_from(stmt.alias())
1913
+ total_count = (await sess.execute(count_stmt)).scalar() or 0
1914
+
1915
+ # Sorting - apply default sort by created_at desc if no sort parameters provided
1916
+ if sort_by is None:
1917
+ stmt = stmt.order_by(table.c.created_at.desc())
1918
+ else:
1919
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1920
+ # Paginating
1921
+ if limit is not None:
1922
+ stmt = stmt.limit(limit)
1923
+ if page is not None:
1924
+ stmt = stmt.offset((page - 1) * limit)
1925
+
1926
+ result = (await sess.execute(stmt)).fetchall()
1927
+ if not result:
1928
+ return [] if deserialize else ([], 0)
1929
+
1930
+ eval_runs_raw = [dict(row._mapping) for row in result]
1931
+ if not deserialize:
1932
+ return eval_runs_raw, total_count
1933
+
1934
+ return [EvalRunRecord.model_validate(row) for row in eval_runs_raw]
1935
+
1936
+ except Exception as e:
1937
+ log_error(f"Exception getting eval runs: {e}")
1938
+ raise e
1939
+
1940
+ async def rename_eval_run(
1941
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
1942
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1943
+ """Upsert the name of an eval run in the database, returning raw dictionary.
1944
+
1945
+ Args:
1946
+ eval_run_id (str): The ID of the eval run to update.
1947
+ name (str): The new name of the eval run.
1948
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1949
+
1950
+ Returns:
1951
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1952
+ - When deserialize=True: EvalRunRecord object
1953
+ - When deserialize=False: EvalRun dictionary
1954
+
1955
+ Raises:
1956
+ Exception: If an error occurs during update.
1957
+ """
1958
+ try:
1959
+ table = await self._get_table(table_type="evals")
1960
+ if table is None:
1961
+ return None
1962
+
1963
+ async with self.async_session_factory() as sess, sess.begin():
1964
+ stmt = (
1965
+ table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time()))
1966
+ )
1967
+ await sess.execute(stmt)
1968
+
1969
+ eval_run_raw = await self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize)
1970
+
1971
+ log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'")
1972
+
1973
+ if not eval_run_raw or not deserialize:
1974
+ return eval_run_raw
1975
+
1976
+ return EvalRunRecord.model_validate(eval_run_raw)
1977
+
1978
+ except Exception as e:
1979
+ log_error(f"Error renaming eval run {eval_run_id}: {e}")
1980
+ raise e
1981
+
1982
+ # -- Migrations --
1983
+
1984
+ async def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str):
1985
+ """Migrate all content in the given table to the right v2 table"""
1986
+
1987
+ from agno.db.migrations.v1_to_v2 import (
1988
+ get_all_table_content,
1989
+ parse_agent_sessions,
1990
+ parse_memories,
1991
+ parse_team_sessions,
1992
+ parse_workflow_sessions,
1993
+ )
1994
+
1995
+ # Get all content from the old table
1996
+ old_content: list[dict[str, Any]] = get_all_table_content(
1997
+ db=self,
1998
+ db_schema=v1_db_schema,
1999
+ table_name=v1_table_name,
2000
+ )
2001
+ if not old_content:
2002
+ log_info(f"No content to migrate from table {v1_table_name}")
2003
+ return
2004
+
2005
+ # Parse the content into the new format
2006
+ memories: List[UserMemory] = []
2007
+ sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = []
2008
+ if v1_table_type == "agent_sessions":
2009
+ sessions = parse_agent_sessions(old_content)
2010
+ elif v1_table_type == "team_sessions":
2011
+ sessions = parse_team_sessions(old_content)
2012
+ elif v1_table_type == "workflow_sessions":
2013
+ sessions = parse_workflow_sessions(old_content)
2014
+ elif v1_table_type == "memories":
2015
+ memories = parse_memories(old_content)
2016
+ else:
2017
+ raise ValueError(f"Invalid table type: {v1_table_type}")
2018
+
2019
+ # Insert the new content into the new table
2020
+ if v1_table_type == "agent_sessions":
2021
+ for session in sessions:
2022
+ await self.upsert_session(session)
2023
+ log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table_name}")
2024
+
2025
+ elif v1_table_type == "team_sessions":
2026
+ for session in sessions:
2027
+ await self.upsert_session(session)
2028
+ log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table_name}")
2029
+
2030
+ elif v1_table_type == "workflow_sessions":
2031
+ for session in sessions:
2032
+ await self.upsert_session(session)
2033
+ log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table_name}")
2034
+
2035
+ elif v1_table_type == "memories":
2036
+ for memory in memories:
2037
+ await self.upsert_user_memory(memory)
2038
+ log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}")
2039
+
2040
+ # -- Culture methods --
2041
+
2042
+ async def clear_cultural_knowledge(self) -> None:
2043
+ """Delete all cultural artifacts from the database.
2044
+
2045
+ Raises:
2046
+ Exception: If an error occurs during deletion.
2047
+ """
2048
+ try:
2049
+ table = await self._get_table(table_type="culture")
2050
+ if table is None:
2051
+ return
2052
+
2053
+ async with self.async_session_factory() as sess, sess.begin():
2054
+ await sess.execute(table.delete())
2055
+
2056
+ except Exception as e:
2057
+ from agno.utils.log import log_warning
2058
+
2059
+ log_warning(f"Exception deleting all cultural artifacts: {e}")
2060
+ raise e
2061
+
2062
+ async def delete_cultural_knowledge(self, id: str) -> None:
2063
+ """Delete a cultural artifact from the database.
2064
+
2065
+ Args:
2066
+ id (str): The ID of the cultural artifact to delete.
2067
+
2068
+ Raises:
2069
+ Exception: If an error occurs during deletion.
2070
+ """
2071
+ try:
2072
+ table = await self._get_table(table_type="culture")
2073
+ if table is None:
2074
+ return
2075
+
2076
+ async with self.async_session_factory() as sess, sess.begin():
2077
+ delete_stmt = table.delete().where(table.c.id == id)
2078
+ result = await sess.execute(delete_stmt)
2079
+
2080
+ success = result.rowcount > 0 # type: ignore
2081
+ if success:
2082
+ log_debug(f"Successfully deleted cultural artifact id: {id}")
2083
+ else:
2084
+ log_debug(f"No cultural artifact found with id: {id}")
2085
+
2086
+ except Exception as e:
2087
+ log_error(f"Error deleting cultural artifact: {e}")
2088
+ raise e
2089
+
2090
+ async def get_cultural_knowledge(
2091
+ self, id: str, deserialize: Optional[bool] = True
2092
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
2093
+ """Get a cultural artifact from the database.
2094
+
2095
+ Args:
2096
+ id (str): The ID of the cultural artifact to get.
2097
+ deserialize (Optional[bool]): Whether to serialize the cultural artifact. Defaults to True.
2098
+
2099
+ Returns:
2100
+ Optional[CulturalKnowledge]: The cultural artifact, or None if it doesn't exist.
2101
+
2102
+ Raises:
2103
+ Exception: If an error occurs during retrieval.
2104
+ """
2105
+ try:
2106
+ table = await self._get_table(table_type="culture")
2107
+ if table is None:
2108
+ return None
2109
+
2110
+ async with self.async_session_factory() as sess, sess.begin():
2111
+ stmt = select(table).where(table.c.id == id)
2112
+ result = (await sess.execute(stmt)).fetchone()
2113
+ if result is None:
2114
+ return None
2115
+
2116
+ db_row = dict(result._mapping)
2117
+ if not db_row or not deserialize:
2118
+ return db_row
2119
+
2120
+ return deserialize_cultural_knowledge_from_db(db_row)
2121
+
2122
+ except Exception as e:
2123
+ log_error(f"Exception reading from cultural artifacts table: {e}")
2124
+ raise e
2125
+
2126
+ async def get_all_cultural_knowledge(
2127
+ self,
2128
+ name: Optional[str] = None,
2129
+ agent_id: Optional[str] = None,
2130
+ team_id: Optional[str] = None,
2131
+ limit: Optional[int] = None,
2132
+ page: Optional[int] = None,
2133
+ sort_by: Optional[str] = None,
2134
+ sort_order: Optional[str] = None,
2135
+ deserialize: Optional[bool] = True,
2136
+ ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
2137
+ """Get all cultural artifacts from the database as CulturalNotion objects.
2138
+
2139
+ Args:
2140
+ name (Optional[str]): The name of the cultural artifact to filter by.
2141
+ agent_id (Optional[str]): The ID of the agent to filter by.
2142
+ team_id (Optional[str]): The ID of the team to filter by.
2143
+ limit (Optional[int]): The maximum number of cultural artifacts to return.
2144
+ page (Optional[int]): The page number.
2145
+ sort_by (Optional[str]): The column to sort by.
2146
+ sort_order (Optional[str]): The order to sort by.
2147
+ deserialize (Optional[bool]): Whether to serialize the cultural artifacts. Defaults to True.
2148
+
2149
+ Returns:
2150
+ Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
2151
+ - When deserialize=True: List of CulturalNotion objects
2152
+ - When deserialize=False: List of CulturalNotion dictionaries and total count
2153
+
2154
+ Raises:
2155
+ Exception: If an error occurs during retrieval.
2156
+ """
2157
+ try:
2158
+ table = await self._get_table(table_type="culture")
2159
+ if table is None:
2160
+ return [] if deserialize else ([], 0)
2161
+
2162
+ async with self.async_session_factory() as sess, sess.begin():
2163
+ stmt = select(table)
2164
+
2165
+ # Filtering
2166
+ if name is not None:
2167
+ stmt = stmt.where(table.c.name == name)
2168
+ if agent_id is not None:
2169
+ stmt = stmt.where(table.c.agent_id == agent_id)
2170
+ if team_id is not None:
2171
+ stmt = stmt.where(table.c.team_id == team_id)
2172
+
2173
+ # Get total count after applying filtering
2174
+ count_stmt = select(func.count()).select_from(stmt.alias())
2175
+ total_count = (await sess.execute(count_stmt)).scalar() or 0
2176
+
2177
+ # Sorting
2178
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
2179
+ # Paginating
2180
+ if limit is not None:
2181
+ stmt = stmt.limit(limit)
2182
+ if page is not None:
2183
+ stmt = stmt.offset((page - 1) * limit)
2184
+
2185
+ result = (await sess.execute(stmt)).fetchall()
2186
+ if not result:
2187
+ return [] if deserialize else ([], 0)
2188
+
2189
+ db_rows = [dict(record._mapping) for record in result]
2190
+
2191
+ if not deserialize:
2192
+ return db_rows, total_count
2193
+
2194
+ return [deserialize_cultural_knowledge_from_db(row) for row in db_rows]
2195
+
2196
+ except Exception as e:
2197
+ log_error(f"Error reading from cultural artifacts table: {e}")
2198
+ raise e
2199
+
2200
+ async def upsert_cultural_knowledge(
2201
+ self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True
2202
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
2203
+ """Upsert a cultural artifact into the database.
2204
+
2205
+ Args:
2206
+ cultural_knowledge (CulturalKnowledge): The cultural artifact to upsert.
2207
+ deserialize (Optional[bool]): Whether to serialize the cultural artifact. Defaults to True.
2208
+
2209
+ Returns:
2210
+ Optional[Union[CulturalNotion, Dict[str, Any]]]:
2211
+ - When deserialize=True: CulturalNotion object
2212
+ - When deserialize=False: CulturalNotion dictionary
2213
+
2214
+ Raises:
2215
+ Exception: If an error occurs during upsert.
2216
+ """
2217
+ try:
2218
+ table = await self._get_table(table_type="culture")
2219
+ if table is None:
2220
+ return None
2221
+
2222
+ if cultural_knowledge.id is None:
2223
+ cultural_knowledge.id = str(uuid4())
2224
+
2225
+ # Serialize content, categories, and notes into a JSON string for DB storage (SQLite requires strings)
2226
+ content_json_str = serialize_cultural_knowledge_for_db(cultural_knowledge)
2227
+
2228
+ async with self.async_session_factory() as sess, sess.begin():
2229
+ stmt = sqlite.insert(table).values(
2230
+ id=cultural_knowledge.id,
2231
+ name=cultural_knowledge.name,
2232
+ summary=cultural_knowledge.summary,
2233
+ content=content_json_str,
2234
+ metadata=cultural_knowledge.metadata,
2235
+ input=cultural_knowledge.input,
2236
+ created_at=cultural_knowledge.created_at,
2237
+ updated_at=int(time.time()),
2238
+ agent_id=cultural_knowledge.agent_id,
2239
+ team_id=cultural_knowledge.team_id,
2240
+ )
2241
+ stmt = stmt.on_conflict_do_update( # type: ignore
2242
+ index_elements=["id"],
2243
+ set_=dict(
2244
+ name=cultural_knowledge.name,
2245
+ summary=cultural_knowledge.summary,
2246
+ content=content_json_str,
2247
+ metadata=cultural_knowledge.metadata,
2248
+ input=cultural_knowledge.input,
2249
+ updated_at=int(time.time()),
2250
+ agent_id=cultural_knowledge.agent_id,
2251
+ team_id=cultural_knowledge.team_id,
2252
+ ),
2253
+ ).returning(table)
2254
+
2255
+ result = await sess.execute(stmt)
2256
+ row = result.fetchone()
2257
+
2258
+ if row is None:
2259
+ return None
2260
+
2261
+ db_row: Dict[str, Any] = dict(row._mapping)
2262
+ if not db_row or not deserialize:
2263
+ return db_row
2264
+
2265
+ return deserialize_cultural_knowledge_from_db(db_row)
2266
+
2267
+ except Exception as e:
2268
+ log_error(f"Error upserting cultural knowledge: {e}")
2269
+ raise e