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