agno 2.0.0rc2__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 (331) hide show
  1. agno/agent/agent.py +6009 -2874
  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 +595 -187
  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 +3 -0
  105. agno/knowledge/types.py +9 -0
  106. agno/knowledge/utils.py +20 -0
  107. agno/media.py +339 -266
  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 +1011 -566
  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 +110 -37
  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 +143 -4
  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 +60 -6
  142. agno/models/openai/chat.py +102 -43
  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 +81 -5
  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 -175
  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 +266 -112
  205. agno/run/base.py +53 -24
  206. agno/run/team.py +252 -111
  207. agno/run/workflow.py +156 -45
  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 -1692
  213. agno/tools/brightdata.py +3 -3
  214. agno/tools/cartesia.py +3 -5
  215. agno/tools/dalle.py +9 -8
  216. agno/tools/decorator.py +4 -2
  217. agno/tools/desi_vocal.py +2 -2
  218. agno/tools/duckduckgo.py +15 -11
  219. agno/tools/e2b.py +20 -13
  220. agno/tools/eleven_labs.py +26 -28
  221. agno/tools/exa.py +21 -16
  222. agno/tools/fal.py +4 -4
  223. agno/tools/file.py +153 -23
  224. agno/tools/file_generation.py +350 -0
  225. agno/tools/firecrawl.py +4 -4
  226. agno/tools/function.py +257 -37
  227. agno/tools/giphy.py +2 -2
  228. agno/tools/gmail.py +238 -14
  229. agno/tools/google_drive.py +270 -0
  230. agno/tools/googlecalendar.py +36 -8
  231. agno/tools/googlesheets.py +20 -5
  232. agno/tools/jira.py +20 -0
  233. agno/tools/knowledge.py +3 -3
  234. agno/tools/lumalab.py +3 -3
  235. agno/tools/mcp/__init__.py +10 -0
  236. agno/tools/mcp/mcp.py +331 -0
  237. agno/tools/mcp/multi_mcp.py +347 -0
  238. agno/tools/mcp/params.py +24 -0
  239. agno/tools/mcp_toolbox.py +284 -0
  240. agno/tools/mem0.py +11 -17
  241. agno/tools/memori.py +1 -53
  242. agno/tools/memory.py +419 -0
  243. agno/tools/models/azure_openai.py +2 -2
  244. agno/tools/models/gemini.py +3 -3
  245. agno/tools/models/groq.py +3 -5
  246. agno/tools/models/nebius.py +7 -7
  247. agno/tools/models_labs.py +25 -15
  248. agno/tools/notion.py +204 -0
  249. agno/tools/openai.py +4 -9
  250. agno/tools/opencv.py +3 -3
  251. agno/tools/parallel.py +314 -0
  252. agno/tools/replicate.py +7 -7
  253. agno/tools/scrapegraph.py +58 -31
  254. agno/tools/searxng.py +2 -2
  255. agno/tools/serper.py +2 -2
  256. agno/tools/slack.py +18 -3
  257. agno/tools/spider.py +2 -2
  258. agno/tools/tavily.py +146 -0
  259. agno/tools/whatsapp.py +1 -1
  260. agno/tools/workflow.py +278 -0
  261. agno/tools/yfinance.py +12 -11
  262. agno/utils/agent.py +820 -0
  263. agno/utils/audio.py +27 -0
  264. agno/utils/common.py +90 -1
  265. agno/utils/events.py +222 -7
  266. agno/utils/gemini.py +181 -23
  267. agno/utils/hooks.py +57 -0
  268. agno/utils/http.py +111 -0
  269. agno/utils/knowledge.py +12 -5
  270. agno/utils/log.py +1 -0
  271. agno/utils/mcp.py +95 -5
  272. agno/utils/media.py +188 -10
  273. agno/utils/merge_dict.py +22 -1
  274. agno/utils/message.py +60 -0
  275. agno/utils/models/claude.py +40 -11
  276. agno/utils/models/cohere.py +1 -1
  277. agno/utils/models/watsonx.py +1 -1
  278. agno/utils/openai.py +1 -1
  279. agno/utils/print_response/agent.py +105 -21
  280. agno/utils/print_response/team.py +103 -38
  281. agno/utils/print_response/workflow.py +251 -34
  282. agno/utils/reasoning.py +22 -1
  283. agno/utils/serialize.py +32 -0
  284. agno/utils/streamlit.py +16 -10
  285. agno/utils/string.py +41 -0
  286. agno/utils/team.py +98 -9
  287. agno/utils/tools.py +1 -1
  288. agno/vectordb/base.py +23 -4
  289. agno/vectordb/cassandra/cassandra.py +65 -9
  290. agno/vectordb/chroma/chromadb.py +182 -38
  291. agno/vectordb/clickhouse/clickhousedb.py +64 -11
  292. agno/vectordb/couchbase/couchbase.py +105 -10
  293. agno/vectordb/lancedb/lance_db.py +183 -135
  294. agno/vectordb/langchaindb/langchaindb.py +25 -7
  295. agno/vectordb/lightrag/lightrag.py +17 -3
  296. agno/vectordb/llamaindex/__init__.py +3 -0
  297. agno/vectordb/llamaindex/llamaindexdb.py +46 -7
  298. agno/vectordb/milvus/milvus.py +126 -9
  299. agno/vectordb/mongodb/__init__.py +7 -1
  300. agno/vectordb/mongodb/mongodb.py +112 -7
  301. agno/vectordb/pgvector/pgvector.py +142 -21
  302. agno/vectordb/pineconedb/pineconedb.py +80 -8
  303. agno/vectordb/qdrant/qdrant.py +125 -39
  304. agno/vectordb/redis/__init__.py +9 -0
  305. agno/vectordb/redis/redisdb.py +694 -0
  306. agno/vectordb/singlestore/singlestore.py +111 -25
  307. agno/vectordb/surrealdb/surrealdb.py +31 -5
  308. agno/vectordb/upstashdb/upstashdb.py +76 -8
  309. agno/vectordb/weaviate/weaviate.py +86 -15
  310. agno/workflow/__init__.py +2 -0
  311. agno/workflow/agent.py +299 -0
  312. agno/workflow/condition.py +112 -18
  313. agno/workflow/loop.py +69 -10
  314. agno/workflow/parallel.py +266 -118
  315. agno/workflow/router.py +110 -17
  316. agno/workflow/step.py +645 -136
  317. agno/workflow/steps.py +65 -6
  318. agno/workflow/types.py +71 -33
  319. agno/workflow/workflow.py +2113 -300
  320. agno-2.3.0.dist-info/METADATA +618 -0
  321. agno-2.3.0.dist-info/RECORD +577 -0
  322. agno-2.3.0.dist-info/licenses/LICENSE +201 -0
  323. agno/knowledge/reader/url_reader.py +0 -128
  324. agno/tools/googlesearch.py +0 -98
  325. agno/tools/mcp.py +0 -610
  326. agno/utils/models/aws_claude.py +0 -170
  327. agno-2.0.0rc2.dist-info/METADATA +0 -355
  328. agno-2.0.0rc2.dist-info/RECORD +0 -515
  329. agno-2.0.0rc2.dist-info/licenses/LICENSE +0 -375
  330. {agno-2.0.0rc2.dist-info → agno-2.3.0.dist-info}/WHEEL +0 -0
  331. {agno-2.0.0rc2.dist-info → agno-2.3.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2036 @@
1
+ import time
2
+ from datetime import date, datetime, timedelta, timezone
3
+ from typing import Any, Dict, List, Optional, Tuple, Union
4
+ from uuid import uuid4
5
+
6
+ from agno.db.base import AsyncBaseDb, SessionType
7
+ from agno.db.mongo.utils import (
8
+ apply_pagination,
9
+ apply_sorting,
10
+ bulk_upsert_metrics,
11
+ calculate_date_metrics,
12
+ create_collection_indexes_async,
13
+ deserialize_cultural_knowledge_from_db,
14
+ fetch_all_sessions_data,
15
+ get_dates_to_calculate_metrics_for,
16
+ serialize_cultural_knowledge_for_db,
17
+ )
18
+ from agno.db.schemas.culture import CulturalKnowledge
19
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
20
+ from agno.db.schemas.knowledge import KnowledgeRow
21
+ from agno.db.schemas.memory import UserMemory
22
+ from agno.db.utils import deserialize_session_json_fields
23
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
24
+ from agno.utils.log import log_debug, log_error, log_info
25
+ from agno.utils.string import generate_id
26
+
27
+ try:
28
+ import asyncio
29
+
30
+ from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorCollection, AsyncIOMotorDatabase # type: ignore
31
+ except ImportError:
32
+ raise ImportError("`motor` not installed. Please install it using `pip install -U motor`")
33
+
34
+ try:
35
+ from pymongo import ReturnDocument
36
+ from pymongo.errors import OperationFailure
37
+ except ImportError:
38
+ raise ImportError("`pymongo` not installed. Please install it using `pip install -U pymongo`")
39
+
40
+
41
+ class AsyncMongoDb(AsyncBaseDb):
42
+ def __init__(
43
+ self,
44
+ db_client: Optional[AsyncIOMotorClient] = None,
45
+ db_name: Optional[str] = None,
46
+ db_url: Optional[str] = None,
47
+ session_collection: Optional[str] = None,
48
+ memory_collection: Optional[str] = None,
49
+ metrics_collection: Optional[str] = None,
50
+ eval_collection: Optional[str] = None,
51
+ knowledge_collection: Optional[str] = None,
52
+ culture_collection: Optional[str] = None,
53
+ id: Optional[str] = None,
54
+ ):
55
+ """
56
+ Async interface for interacting with a MongoDB database using Motor.
57
+
58
+ Args:
59
+ db_client (Optional[AsyncIOMotorClient]): The MongoDB async client to use.
60
+ db_name (Optional[str]): The name of the database to use.
61
+ db_url (Optional[str]): The database URL to connect to.
62
+ session_collection (Optional[str]): Name of the collection to store sessions.
63
+ memory_collection (Optional[str]): Name of the collection to store memories.
64
+ metrics_collection (Optional[str]): Name of the collection to store metrics.
65
+ eval_collection (Optional[str]): Name of the collection to store evaluation runs.
66
+ knowledge_collection (Optional[str]): Name of the collection to store knowledge documents.
67
+ culture_collection (Optional[str]): Name of the collection to store cultural knowledge.
68
+ id (Optional[str]): ID of the database.
69
+
70
+ Raises:
71
+ ValueError: If neither db_url nor db_client is provided.
72
+ """
73
+ if id is None:
74
+ base_seed = db_url or str(db_client)
75
+ db_name_suffix = db_name if db_name is not None else "agno"
76
+ seed = f"{base_seed}#{db_name_suffix}"
77
+ id = generate_id(seed)
78
+
79
+ super().__init__(
80
+ id=id,
81
+ session_table=session_collection,
82
+ memory_table=memory_collection,
83
+ metrics_table=metrics_collection,
84
+ eval_table=eval_collection,
85
+ knowledge_table=knowledge_collection,
86
+ culture_table=culture_collection,
87
+ )
88
+
89
+ # Store configuration for lazy initialization
90
+ self._provided_client: Optional[AsyncIOMotorClient] = db_client
91
+ self.db_url: Optional[str] = db_url
92
+ self.db_name: str = db_name if db_name is not None else "agno"
93
+
94
+ if self._provided_client is None and self.db_url is None:
95
+ raise ValueError("One of db_url or db_client must be provided")
96
+
97
+ # Client and database will be lazily initialized per event loop
98
+ self._client: Optional[AsyncIOMotorClient] = None
99
+ self._database: Optional[AsyncIOMotorDatabase] = None
100
+ self._event_loop: Optional[asyncio.AbstractEventLoop] = None
101
+
102
+ async def table_exists(self, table_name: str) -> bool:
103
+ """Check if a collection with the given name exists in the MongoDB database.
104
+
105
+ Args:
106
+ table_name: Name of the collection to check
107
+
108
+ Returns:
109
+ bool: True if the collection exists in the database, False otherwise
110
+ """
111
+ collection_names = await self.database.list_collection_names()
112
+ return table_name in collection_names
113
+
114
+ async def _create_all_tables(self):
115
+ """Create all configured MongoDB collections if they don't exist."""
116
+ collections_to_create = [
117
+ ("sessions", self.session_table_name),
118
+ ("memories", self.memory_table_name),
119
+ ("metrics", self.metrics_table_name),
120
+ ("evals", self.eval_table_name),
121
+ ("knowledge", self.knowledge_table_name),
122
+ ("culture", self.culture_table_name),
123
+ ]
124
+
125
+ for collection_type, collection_name in collections_to_create:
126
+ if collection_name and not await self.table_exists(collection_name):
127
+ await self._get_collection(collection_type, create_collection_if_not_found=True)
128
+
129
+ def _ensure_client(self) -> AsyncIOMotorClient:
130
+ """
131
+ Ensure the Motor client is valid for the current event loop.
132
+
133
+ Motor's AsyncIOMotorClient is tied to the event loop it was created in.
134
+ If we detect a new event loop, we need to refresh the client.
135
+
136
+ Returns:
137
+ AsyncIOMotorClient: A valid client for the current event loop.
138
+ """
139
+ try:
140
+ current_loop = asyncio.get_running_loop()
141
+ except RuntimeError:
142
+ # No running loop, return existing client or create new one
143
+ if self._client is None:
144
+ if self._provided_client is not None:
145
+ self._client = self._provided_client
146
+ elif self.db_url is not None:
147
+ self._client = AsyncIOMotorClient(self.db_url)
148
+ log_debug("Created AsyncIOMotorClient outside event loop")
149
+ return self._client # type: ignore
150
+
151
+ # Check if we're in a different event loop
152
+ if self._event_loop is None or self._event_loop is not current_loop:
153
+ # New event loop detected, create new client
154
+ if self._provided_client is not None:
155
+ # User provided a client, use it but warn them
156
+ log_debug(
157
+ "New event loop detected. Using provided AsyncIOMotorClient, "
158
+ "which may cause issues if it was created in a different event loop."
159
+ )
160
+ self._client = self._provided_client
161
+ elif self.db_url is not None:
162
+ # Create a new client for this event loop
163
+ old_loop_id = id(self._event_loop) if self._event_loop else "None"
164
+ new_loop_id = id(current_loop)
165
+ log_debug(f"Event loop changed from {old_loop_id} to {new_loop_id}, creating new AsyncIOMotorClient")
166
+ self._client = AsyncIOMotorClient(self.db_url)
167
+
168
+ self._event_loop = current_loop
169
+ self._database = None # Reset database reference
170
+ # Clear collection caches and initialization flags when switching event loops
171
+ for attr in list(vars(self).keys()):
172
+ if attr.endswith("_collection") or attr.endswith("_initialized"):
173
+ delattr(self, attr)
174
+
175
+ return self._client # type: ignore
176
+
177
+ @property
178
+ def db_client(self) -> AsyncIOMotorClient:
179
+ """Get the MongoDB client, ensuring it's valid for the current event loop."""
180
+ return self._ensure_client()
181
+
182
+ @property
183
+ def database(self) -> AsyncIOMotorDatabase:
184
+ """Get the MongoDB database, ensuring it's valid for the current event loop."""
185
+ try:
186
+ current_loop = asyncio.get_running_loop()
187
+ if self._database is None or self._event_loop != current_loop:
188
+ self._database = self.db_client[self.db_name]
189
+ except RuntimeError:
190
+ # No running loop - fallback to existing database or create new one
191
+ if self._database is None:
192
+ self._database = self.db_client[self.db_name]
193
+ return self._database
194
+
195
+ # -- DB methods --
196
+
197
+ def _should_reset_collection_cache(self) -> bool:
198
+ """Check if collection cache should be reset due to event loop change."""
199
+ try:
200
+ current_loop = asyncio.get_running_loop()
201
+ return self._event_loop is not current_loop
202
+ except RuntimeError:
203
+ return False
204
+
205
+ async def _get_collection(
206
+ self, table_type: str, create_collection_if_not_found: Optional[bool] = True
207
+ ) -> Optional[AsyncIOMotorCollection]:
208
+ """Get or create a collection based on table type.
209
+
210
+ Args:
211
+ table_type (str): The type of table to get or create.
212
+ create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
213
+
214
+ Returns:
215
+ AsyncIOMotorCollection: The collection object.
216
+ """
217
+ # Ensure client is valid for current event loop before accessing collections
218
+ _ = self.db_client # This triggers _ensure_client()
219
+
220
+ # Check if collections need to be reset due to event loop change
221
+ reset_cache = self._should_reset_collection_cache()
222
+
223
+ if table_type == "sessions":
224
+ if reset_cache or not hasattr(self, "session_collection"):
225
+ if self.session_table_name is None:
226
+ raise ValueError("Session collection was not provided on initialization")
227
+ self.session_collection = await self._get_or_create_collection(
228
+ collection_name=self.session_table_name,
229
+ collection_type="sessions",
230
+ create_collection_if_not_found=create_collection_if_not_found,
231
+ )
232
+ return self.session_collection
233
+
234
+ if table_type == "memories":
235
+ if reset_cache or not hasattr(self, "memory_collection"):
236
+ if self.memory_table_name is None:
237
+ raise ValueError("Memory collection was not provided on initialization")
238
+ self.memory_collection = await self._get_or_create_collection(
239
+ collection_name=self.memory_table_name,
240
+ collection_type="memories",
241
+ create_collection_if_not_found=create_collection_if_not_found,
242
+ )
243
+ return self.memory_collection
244
+
245
+ if table_type == "metrics":
246
+ if reset_cache or not hasattr(self, "metrics_collection"):
247
+ if self.metrics_table_name is None:
248
+ raise ValueError("Metrics collection was not provided on initialization")
249
+ self.metrics_collection = await self._get_or_create_collection(
250
+ collection_name=self.metrics_table_name,
251
+ collection_type="metrics",
252
+ create_collection_if_not_found=create_collection_if_not_found,
253
+ )
254
+ return self.metrics_collection
255
+
256
+ if table_type == "evals":
257
+ if reset_cache or not hasattr(self, "eval_collection"):
258
+ if self.eval_table_name is None:
259
+ raise ValueError("Eval collection was not provided on initialization")
260
+ self.eval_collection = await self._get_or_create_collection(
261
+ collection_name=self.eval_table_name,
262
+ collection_type="evals",
263
+ create_collection_if_not_found=create_collection_if_not_found,
264
+ )
265
+ return self.eval_collection
266
+
267
+ if table_type == "knowledge":
268
+ if reset_cache or not hasattr(self, "knowledge_collection"):
269
+ if self.knowledge_table_name is None:
270
+ raise ValueError("Knowledge collection was not provided on initialization")
271
+ self.knowledge_collection = await self._get_or_create_collection(
272
+ collection_name=self.knowledge_table_name,
273
+ collection_type="knowledge",
274
+ create_collection_if_not_found=create_collection_if_not_found,
275
+ )
276
+ return self.knowledge_collection
277
+
278
+ if table_type == "culture":
279
+ if reset_cache or not hasattr(self, "culture_collection"):
280
+ if self.culture_table_name is None:
281
+ raise ValueError("Culture collection was not provided on initialization")
282
+ self.culture_collection = await self._get_or_create_collection(
283
+ collection_name=self.culture_table_name,
284
+ collection_type="culture",
285
+ create_collection_if_not_found=create_collection_if_not_found,
286
+ )
287
+ return self.culture_collection
288
+
289
+ raise ValueError(f"Unknown table type: {table_type}")
290
+
291
+ async def _get_or_create_collection(
292
+ self, collection_name: str, collection_type: str, create_collection_if_not_found: Optional[bool] = True
293
+ ) -> Optional[AsyncIOMotorCollection]:
294
+ """Get or create a collection with proper indexes.
295
+
296
+ Args:
297
+ collection_name (str): The name of the collection to get or create.
298
+ collection_type (str): The type of collection to get or create.
299
+ create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
300
+
301
+ Returns:
302
+ Optional[AsyncIOMotorCollection]: The collection object.
303
+ """
304
+ try:
305
+ collection = self.database[collection_name]
306
+
307
+ if not hasattr(self, f"_{collection_name}_initialized"):
308
+ if not create_collection_if_not_found:
309
+ return None
310
+ # Create indexes asynchronously for Motor collections
311
+ await create_collection_indexes_async(collection, collection_type)
312
+ setattr(self, f"_{collection_name}_initialized", True)
313
+ log_debug(f"Initialized collection '{collection_name}'")
314
+ else:
315
+ log_debug(f"Collection '{collection_name}' already initialized")
316
+
317
+ return collection
318
+
319
+ except Exception as e:
320
+ log_error(f"Error getting collection {collection_name}: {e}")
321
+ raise
322
+
323
+ def get_latest_schema_version(self):
324
+ """Get the latest version of the database schema."""
325
+ pass
326
+
327
+ def upsert_schema_version(self, version: str) -> None:
328
+ """Upsert the schema version into the database."""
329
+ pass
330
+
331
+ # -- Session methods --
332
+
333
+ async def delete_session(self, session_id: str) -> bool:
334
+ """Delete a session from the database.
335
+
336
+ Args:
337
+ session_id (str): The ID of the session to delete.
338
+
339
+ Returns:
340
+ bool: True if the session was deleted, False otherwise.
341
+
342
+ Raises:
343
+ Exception: If there is an error deleting the session.
344
+ """
345
+ try:
346
+ collection = await self._get_collection(table_type="sessions")
347
+ if collection is None:
348
+ return False
349
+
350
+ result = await collection.delete_one({"session_id": session_id})
351
+ if result.deleted_count == 0:
352
+ log_debug(f"No session found to delete with session_id: {session_id}")
353
+ return False
354
+ else:
355
+ log_debug(f"Successfully deleted session with session_id: {session_id}")
356
+ return True
357
+
358
+ except Exception as e:
359
+ log_error(f"Error deleting session: {e}")
360
+ raise e
361
+
362
+ async def delete_sessions(self, session_ids: List[str]) -> None:
363
+ """Delete multiple sessions from the database.
364
+
365
+ Args:
366
+ session_ids (List[str]): The IDs of the sessions to delete.
367
+ """
368
+ try:
369
+ collection = await self._get_collection(table_type="sessions")
370
+ if collection is None:
371
+ return
372
+
373
+ result = await collection.delete_many({"session_id": {"$in": session_ids}})
374
+ log_debug(f"Successfully deleted {result.deleted_count} sessions")
375
+
376
+ except Exception as e:
377
+ log_error(f"Error deleting sessions: {e}")
378
+ raise e
379
+
380
+ async def get_session(
381
+ self,
382
+ session_id: str,
383
+ session_type: SessionType,
384
+ user_id: Optional[str] = None,
385
+ deserialize: Optional[bool] = True,
386
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
387
+ """Read a session from the database.
388
+
389
+ Args:
390
+ session_id (str): The ID of the session to get.
391
+ session_type (SessionType): The type of session to get.
392
+ user_id (Optional[str]): The ID of the user to get the session for.
393
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
394
+
395
+ Returns:
396
+ Union[Session, Dict[str, Any], None]:
397
+ - When deserialize=True: Session object
398
+ - When deserialize=False: Session dictionary
399
+
400
+ Raises:
401
+ Exception: If there is an error reading the session.
402
+ """
403
+ try:
404
+ collection = await self._get_collection(table_type="sessions")
405
+ if collection is None:
406
+ return None
407
+
408
+ query = {"session_id": session_id}
409
+ if user_id is not None:
410
+ query["user_id"] = user_id
411
+ if session_type is not None:
412
+ query["session_type"] = session_type
413
+
414
+ result = await collection.find_one(query)
415
+ if result is None:
416
+ return None
417
+
418
+ session = deserialize_session_json_fields(result)
419
+ if not deserialize:
420
+ return session
421
+
422
+ if session_type == SessionType.AGENT:
423
+ return AgentSession.from_dict(session)
424
+ elif session_type == SessionType.TEAM:
425
+ return TeamSession.from_dict(session)
426
+ elif session_type == SessionType.WORKFLOW:
427
+ return WorkflowSession.from_dict(session)
428
+ else:
429
+ raise ValueError(f"Invalid session type: {session_type}")
430
+
431
+ except Exception as e:
432
+ log_error(f"Exception reading session: {e}")
433
+ raise e
434
+
435
+ async def get_sessions(
436
+ self,
437
+ session_type: Optional[SessionType] = None,
438
+ user_id: Optional[str] = None,
439
+ component_id: Optional[str] = None,
440
+ session_name: Optional[str] = None,
441
+ start_timestamp: Optional[int] = None,
442
+ end_timestamp: Optional[int] = None,
443
+ limit: Optional[int] = None,
444
+ page: Optional[int] = None,
445
+ sort_by: Optional[str] = None,
446
+ sort_order: Optional[str] = None,
447
+ deserialize: Optional[bool] = True,
448
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
449
+ """Get all sessions.
450
+
451
+ Args:
452
+ session_type (Optional[SessionType]): The type of session to get.
453
+ user_id (Optional[str]): The ID of the user to get the session for.
454
+ component_id (Optional[str]): The ID of the component to get the session for.
455
+ session_name (Optional[str]): The name of the session to filter by.
456
+ start_timestamp (Optional[int]): The start timestamp to filter sessions by.
457
+ end_timestamp (Optional[int]): The end timestamp to filter sessions by.
458
+ limit (Optional[int]): The limit of the sessions to get.
459
+ page (Optional[int]): The page number to get.
460
+ sort_by (Optional[str]): The field to sort the sessions by.
461
+ sort_order (Optional[str]): The order to sort the sessions by.
462
+ deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True.
463
+
464
+ Returns:
465
+ Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]:
466
+ - When deserialize=True: List of Session objects
467
+ - When deserialize=False: List of session dictionaries and the total count
468
+
469
+ Raises:
470
+ Exception: If there is an error reading the sessions.
471
+ """
472
+ try:
473
+ collection = await self._get_collection(table_type="sessions")
474
+ if collection is None:
475
+ return [] if deserialize else ([], 0)
476
+
477
+ # Filtering
478
+ query: Dict[str, Any] = {}
479
+ if user_id is not None:
480
+ query["user_id"] = user_id
481
+ if session_type is not None:
482
+ query["session_type"] = session_type
483
+ if component_id is not None:
484
+ if session_type == SessionType.AGENT:
485
+ query["agent_id"] = component_id
486
+ elif session_type == SessionType.TEAM:
487
+ query["team_id"] = component_id
488
+ elif session_type == SessionType.WORKFLOW:
489
+ query["workflow_id"] = component_id
490
+ if start_timestamp is not None:
491
+ query["created_at"] = {"$gte": start_timestamp}
492
+ if end_timestamp is not None:
493
+ if "created_at" in query:
494
+ query["created_at"]["$lte"] = end_timestamp
495
+ else:
496
+ query["created_at"] = {"$lte": end_timestamp}
497
+ if session_name is not None:
498
+ query["session_data.session_name"] = {"$regex": session_name, "$options": "i"}
499
+
500
+ # Get total count
501
+ total_count = await collection.count_documents(query)
502
+
503
+ cursor = collection.find(query)
504
+
505
+ # Sorting
506
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
507
+ if sort_criteria:
508
+ cursor = cursor.sort(sort_criteria)
509
+
510
+ # Pagination
511
+ query_args = apply_pagination({}, limit, page)
512
+ if query_args.get("skip"):
513
+ cursor = cursor.skip(query_args["skip"])
514
+ if query_args.get("limit"):
515
+ cursor = cursor.limit(query_args["limit"])
516
+
517
+ records = await cursor.to_list(length=None)
518
+ if records is None:
519
+ return [] if deserialize else ([], 0)
520
+ sessions_raw = [deserialize_session_json_fields(record) for record in records]
521
+
522
+ if not deserialize:
523
+ return sessions_raw, total_count
524
+
525
+ sessions: List[Union[AgentSession, TeamSession, WorkflowSession]] = []
526
+ for record in sessions_raw:
527
+ if session_type == SessionType.AGENT.value:
528
+ agent_session = AgentSession.from_dict(record)
529
+ if agent_session is not None:
530
+ sessions.append(agent_session)
531
+ elif session_type == SessionType.TEAM.value:
532
+ team_session = TeamSession.from_dict(record)
533
+ if team_session is not None:
534
+ sessions.append(team_session)
535
+ elif session_type == SessionType.WORKFLOW.value:
536
+ workflow_session = WorkflowSession.from_dict(record)
537
+ if workflow_session is not None:
538
+ sessions.append(workflow_session)
539
+
540
+ return sessions
541
+
542
+ except Exception as e:
543
+ log_error(f"Exception reading sessions: {e}")
544
+ raise e
545
+
546
+ async def rename_session(
547
+ self, session_id: str, session_type: SessionType, session_name: str, deserialize: Optional[bool] = True
548
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
549
+ """Rename a session in the database.
550
+
551
+ Args:
552
+ session_id (str): The ID of the session to rename.
553
+ session_type (SessionType): The type of session to rename.
554
+ session_name (str): The new name of the session.
555
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
556
+
557
+ Returns:
558
+ Optional[Union[Session, Dict[str, Any]]]:
559
+ - When deserialize=True: Session object
560
+ - When deserialize=False: Session dictionary
561
+
562
+ Raises:
563
+ Exception: If there is an error renaming the session.
564
+ """
565
+ try:
566
+ collection = await self._get_collection(table_type="sessions")
567
+ if collection is None:
568
+ return None
569
+
570
+ try:
571
+ result = await collection.find_one_and_update(
572
+ {"session_id": session_id},
573
+ {"$set": {"session_data.session_name": session_name, "updated_at": int(time.time())}},
574
+ return_document=ReturnDocument.AFTER,
575
+ upsert=False,
576
+ )
577
+ except OperationFailure:
578
+ # If the update fails because session_data doesn't contain a session_name yet, we initialize session_data
579
+ result = await collection.find_one_and_update(
580
+ {"session_id": session_id},
581
+ {"$set": {"session_data": {"session_name": session_name}, "updated_at": int(time.time())}},
582
+ return_document=ReturnDocument.AFTER,
583
+ upsert=False,
584
+ )
585
+ if not result:
586
+ return None
587
+
588
+ deserialized_session = deserialize_session_json_fields(result)
589
+
590
+ if not deserialize:
591
+ return deserialized_session
592
+
593
+ if session_type == SessionType.AGENT.value:
594
+ return AgentSession.from_dict(deserialized_session)
595
+ elif session_type == SessionType.TEAM.value:
596
+ return TeamSession.from_dict(deserialized_session)
597
+ else:
598
+ return WorkflowSession.from_dict(deserialized_session)
599
+
600
+ except Exception as e:
601
+ log_error(f"Exception renaming session: {e}")
602
+ raise e
603
+
604
+ async def upsert_session(
605
+ self, session: Session, deserialize: Optional[bool] = True
606
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
607
+ """Insert or update a session in the database.
608
+
609
+ Args:
610
+ session (Session): The session to upsert.
611
+ deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True.
612
+
613
+ Returns:
614
+ Optional[Union[Session, Dict[str, Any]]]: The upserted session.
615
+
616
+ Raises:
617
+ Exception: If there is an error upserting the session.
618
+ """
619
+ try:
620
+ collection = await self._get_collection(table_type="sessions", create_collection_if_not_found=True)
621
+ if collection is None:
622
+ return None
623
+
624
+ session_dict = session.to_dict()
625
+
626
+ if isinstance(session, AgentSession):
627
+ record = {
628
+ "session_id": session_dict.get("session_id"),
629
+ "session_type": SessionType.AGENT.value,
630
+ "agent_id": session_dict.get("agent_id"),
631
+ "user_id": session_dict.get("user_id"),
632
+ "runs": session_dict.get("runs"),
633
+ "agent_data": session_dict.get("agent_data"),
634
+ "session_data": session_dict.get("session_data"),
635
+ "summary": session_dict.get("summary"),
636
+ "metadata": session_dict.get("metadata"),
637
+ "created_at": session_dict.get("created_at"),
638
+ "updated_at": int(time.time()),
639
+ }
640
+
641
+ result = await collection.find_one_and_replace(
642
+ filter={"session_id": session_dict.get("session_id")},
643
+ replacement=record,
644
+ upsert=True,
645
+ return_document=ReturnDocument.AFTER,
646
+ )
647
+ if not result:
648
+ return None
649
+
650
+ session = result # type: ignore
651
+
652
+ if not deserialize:
653
+ return session
654
+
655
+ return AgentSession.from_dict(session) # type: ignore
656
+
657
+ elif isinstance(session, TeamSession):
658
+ record = {
659
+ "session_id": session_dict.get("session_id"),
660
+ "session_type": SessionType.TEAM.value,
661
+ "team_id": session_dict.get("team_id"),
662
+ "user_id": session_dict.get("user_id"),
663
+ "runs": session_dict.get("runs"),
664
+ "team_data": session_dict.get("team_data"),
665
+ "session_data": session_dict.get("session_data"),
666
+ "summary": session_dict.get("summary"),
667
+ "metadata": session_dict.get("metadata"),
668
+ "created_at": session_dict.get("created_at"),
669
+ "updated_at": int(time.time()),
670
+ }
671
+
672
+ result = await collection.find_one_and_replace(
673
+ filter={"session_id": session_dict.get("session_id")},
674
+ replacement=record,
675
+ upsert=True,
676
+ return_document=ReturnDocument.AFTER,
677
+ )
678
+ if not result:
679
+ return None
680
+
681
+ # MongoDB stores native objects, no deserialization needed for document fields
682
+ session = result # type: ignore
683
+
684
+ if not deserialize:
685
+ return session
686
+
687
+ return TeamSession.from_dict(session) # type: ignore
688
+
689
+ else:
690
+ record = {
691
+ "session_id": session_dict.get("session_id"),
692
+ "session_type": SessionType.WORKFLOW.value,
693
+ "workflow_id": session_dict.get("workflow_id"),
694
+ "user_id": session_dict.get("user_id"),
695
+ "runs": session_dict.get("runs"),
696
+ "workflow_data": session_dict.get("workflow_data"),
697
+ "session_data": session_dict.get("session_data"),
698
+ "summary": session_dict.get("summary"),
699
+ "metadata": session_dict.get("metadata"),
700
+ "created_at": session_dict.get("created_at"),
701
+ "updated_at": int(time.time()),
702
+ }
703
+
704
+ result = await collection.find_one_and_replace(
705
+ filter={"session_id": session_dict.get("session_id")},
706
+ replacement=record,
707
+ upsert=True,
708
+ return_document=ReturnDocument.AFTER,
709
+ )
710
+ if not result:
711
+ return None
712
+
713
+ session = result # type: ignore
714
+
715
+ if not deserialize:
716
+ return session
717
+
718
+ return WorkflowSession.from_dict(session) # type: ignore
719
+
720
+ except Exception as e:
721
+ log_error(f"Exception upserting session: {e}")
722
+ raise e
723
+
724
+ async def upsert_sessions(
725
+ self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False
726
+ ) -> List[Union[Session, Dict[str, Any]]]:
727
+ """
728
+ Bulk upsert multiple sessions for improved performance on large datasets.
729
+
730
+ Args:
731
+ sessions (List[Session]): List of sessions to upsert.
732
+ deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True.
733
+ preserve_updated_at (bool): If True, preserve the updated_at from the session object.
734
+
735
+ Returns:
736
+ List[Union[Session, Dict[str, Any]]]: List of upserted sessions.
737
+
738
+ Raises:
739
+ Exception: If an error occurs during bulk upsert.
740
+ """
741
+ if not sessions:
742
+ return []
743
+
744
+ try:
745
+ collection = await self._get_collection(table_type="sessions", create_collection_if_not_found=True)
746
+ if collection is None:
747
+ log_info("Sessions collection not available, falling back to individual upserts")
748
+ return [
749
+ result
750
+ for session in sessions
751
+ if session is not None
752
+ for result in [await self.upsert_session(session, deserialize=deserialize)]
753
+ if result is not None
754
+ ]
755
+
756
+ from pymongo import ReplaceOne
757
+
758
+ operations = []
759
+ results: List[Union[Session, Dict[str, Any]]] = []
760
+
761
+ for session in sessions:
762
+ if session is None:
763
+ continue
764
+
765
+ session_dict = session.to_dict()
766
+
767
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
768
+ updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time())
769
+
770
+ if isinstance(session, AgentSession):
771
+ record = {
772
+ "session_id": session_dict.get("session_id"),
773
+ "session_type": SessionType.AGENT.value,
774
+ "agent_id": session_dict.get("agent_id"),
775
+ "user_id": session_dict.get("user_id"),
776
+ "runs": session_dict.get("runs"),
777
+ "agent_data": session_dict.get("agent_data"),
778
+ "session_data": session_dict.get("session_data"),
779
+ "summary": session_dict.get("summary"),
780
+ "metadata": session_dict.get("metadata"),
781
+ "created_at": session_dict.get("created_at"),
782
+ "updated_at": updated_at,
783
+ }
784
+ elif isinstance(session, TeamSession):
785
+ record = {
786
+ "session_id": session_dict.get("session_id"),
787
+ "session_type": SessionType.TEAM.value,
788
+ "team_id": session_dict.get("team_id"),
789
+ "user_id": session_dict.get("user_id"),
790
+ "runs": session_dict.get("runs"),
791
+ "team_data": session_dict.get("team_data"),
792
+ "session_data": session_dict.get("session_data"),
793
+ "summary": session_dict.get("summary"),
794
+ "metadata": session_dict.get("metadata"),
795
+ "created_at": session_dict.get("created_at"),
796
+ "updated_at": updated_at,
797
+ }
798
+ elif isinstance(session, WorkflowSession):
799
+ record = {
800
+ "session_id": session_dict.get("session_id"),
801
+ "session_type": SessionType.WORKFLOW.value,
802
+ "workflow_id": session_dict.get("workflow_id"),
803
+ "user_id": session_dict.get("user_id"),
804
+ "runs": session_dict.get("runs"),
805
+ "workflow_data": session_dict.get("workflow_data"),
806
+ "session_data": session_dict.get("session_data"),
807
+ "summary": session_dict.get("summary"),
808
+ "metadata": session_dict.get("metadata"),
809
+ "created_at": session_dict.get("created_at"),
810
+ "updated_at": updated_at,
811
+ }
812
+ else:
813
+ continue
814
+
815
+ operations.append(
816
+ ReplaceOne(filter={"session_id": record["session_id"]}, replacement=record, upsert=True)
817
+ )
818
+
819
+ if operations:
820
+ # Execute bulk write
821
+ await collection.bulk_write(operations)
822
+
823
+ # Fetch the results
824
+ session_ids = [session.session_id for session in sessions if session and session.session_id]
825
+ cursor = collection.find({"session_id": {"$in": session_ids}})
826
+
827
+ async for doc in cursor:
828
+ session_dict = doc
829
+
830
+ if deserialize:
831
+ session_type = doc.get("session_type")
832
+ if session_type == SessionType.AGENT.value:
833
+ deserialized_agent_session = AgentSession.from_dict(session_dict)
834
+ if deserialized_agent_session is None:
835
+ continue
836
+ results.append(deserialized_agent_session)
837
+
838
+ elif session_type == SessionType.TEAM.value:
839
+ deserialized_team_session = TeamSession.from_dict(session_dict)
840
+ if deserialized_team_session is None:
841
+ continue
842
+ results.append(deserialized_team_session)
843
+
844
+ elif session_type == SessionType.WORKFLOW.value:
845
+ deserialized_workflow_session = WorkflowSession.from_dict(session_dict)
846
+ if deserialized_workflow_session is None:
847
+ continue
848
+ results.append(deserialized_workflow_session)
849
+ else:
850
+ results.append(session_dict)
851
+
852
+ return results
853
+
854
+ except Exception as e:
855
+ log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}")
856
+
857
+ # Fallback to individual upserts
858
+ return [
859
+ result
860
+ for session in sessions
861
+ if session is not None
862
+ for result in [await self.upsert_session(session, deserialize=deserialize)]
863
+ if result is not None
864
+ ]
865
+
866
+ # -- Memory methods --
867
+
868
+ async def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None):
869
+ """Delete a user memory from the database.
870
+
871
+ Args:
872
+ memory_id (str): The ID of the memory to delete.
873
+ user_id (Optional[str]): The ID of the user to verify ownership. If provided, only delete if the memory belongs to this user.
874
+
875
+ Returns:
876
+ bool: True if the memory was deleted, False otherwise.
877
+
878
+ Raises:
879
+ Exception: If there is an error deleting the memory.
880
+ """
881
+ try:
882
+ collection = await self._get_collection(table_type="memories")
883
+ if collection is None:
884
+ return
885
+
886
+ query = {"memory_id": memory_id}
887
+ if user_id is not None:
888
+ query["user_id"] = user_id
889
+
890
+ result = await collection.delete_one(query)
891
+
892
+ success = result.deleted_count > 0
893
+ if success:
894
+ log_debug(f"Successfully deleted memory id: {memory_id}")
895
+ else:
896
+ log_debug(f"No memory found with id: {memory_id}")
897
+
898
+ except Exception as e:
899
+ log_error(f"Error deleting memory: {e}")
900
+ raise e
901
+
902
+ async def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None:
903
+ """Delete user memories from the database.
904
+
905
+ Args:
906
+ memory_ids (List[str]): The IDs of the memories to delete.
907
+ user_id (Optional[str]): The ID of the user to verify ownership. If provided, only delete memories that belong to this user.
908
+
909
+ Raises:
910
+ Exception: If there is an error deleting the memories.
911
+ """
912
+ try:
913
+ collection = await self._get_collection(table_type="memories")
914
+ if collection is None:
915
+ return
916
+
917
+ query: Dict[str, Any] = {"memory_id": {"$in": memory_ids}}
918
+ if user_id is not None:
919
+ query["user_id"] = user_id
920
+
921
+ result = await collection.delete_many(query)
922
+
923
+ if result.deleted_count == 0:
924
+ log_debug(f"No memories found with ids: {memory_ids}")
925
+
926
+ except Exception as e:
927
+ log_error(f"Error deleting memories: {e}")
928
+ raise e
929
+
930
+ async def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]:
931
+ """Get all memory topics from the database.
932
+
933
+ Args:
934
+ user_id (Optional[str]): The ID of the user to filter by. Defaults to None.
935
+
936
+ Returns:
937
+ List[str]: The topics.
938
+
939
+ Raises:
940
+ Exception: If there is an error getting the topics.
941
+ """
942
+ try:
943
+ collection = await self._get_collection(table_type="memories")
944
+ if collection is None:
945
+ return []
946
+
947
+ query = {}
948
+ if user_id is not None:
949
+ query["user_id"] = user_id
950
+
951
+ topics = await collection.distinct("topics", query)
952
+ return [topic for topic in topics if topic]
953
+
954
+ except Exception as e:
955
+ log_error(f"Exception reading from collection: {e}")
956
+ raise e
957
+
958
+ async def get_user_memory(
959
+ self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None
960
+ ) -> Optional[UserMemory]:
961
+ """Get a memory from the database.
962
+
963
+ Args:
964
+ memory_id (str): The ID of the memory to get.
965
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
966
+ user_id (Optional[str]): The ID of the user to verify ownership. If provided, only return the memory if it belongs to this user.
967
+
968
+ Returns:
969
+ Optional[UserMemory]:
970
+ - When deserialize=True: UserMemory object
971
+ - When deserialize=False: Memory dictionary
972
+
973
+ Raises:
974
+ Exception: If there is an error getting the memory.
975
+ """
976
+ try:
977
+ collection = await self._get_collection(table_type="memories")
978
+ if collection is None:
979
+ return None
980
+
981
+ query = {"memory_id": memory_id}
982
+ if user_id is not None:
983
+ query["user_id"] = user_id
984
+
985
+ result = await collection.find_one(query)
986
+ if result is None or not deserialize:
987
+ return result
988
+
989
+ # Remove MongoDB's _id field before creating UserMemory object
990
+ result_filtered = {k: v for k, v in result.items() if k != "_id"}
991
+ return UserMemory.from_dict(result_filtered)
992
+
993
+ except Exception as e:
994
+ log_error(f"Exception reading from collection: {e}")
995
+ raise e
996
+
997
+ async def get_user_memories(
998
+ self,
999
+ user_id: Optional[str] = None,
1000
+ agent_id: Optional[str] = None,
1001
+ team_id: Optional[str] = None,
1002
+ topics: Optional[List[str]] = None,
1003
+ search_content: Optional[str] = None,
1004
+ limit: Optional[int] = None,
1005
+ page: Optional[int] = None,
1006
+ sort_by: Optional[str] = None,
1007
+ sort_order: Optional[str] = None,
1008
+ deserialize: Optional[bool] = True,
1009
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1010
+ """Get all memories from the database as UserMemory objects.
1011
+
1012
+ Args:
1013
+ user_id (Optional[str]): The ID of the user to get the memories for.
1014
+ agent_id (Optional[str]): The ID of the agent to get the memories for.
1015
+ team_id (Optional[str]): The ID of the team to get the memories for.
1016
+ topics (Optional[List[str]]): The topics to filter the memories by.
1017
+ search_content (Optional[str]): The content to filter the memories by.
1018
+ limit (Optional[int]): The limit of the memories to get.
1019
+ page (Optional[int]): The page number to get.
1020
+ sort_by (Optional[str]): The field to sort the memories by.
1021
+ sort_order (Optional[str]): The order to sort the memories by.
1022
+ deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True.
1023
+
1024
+ Returns:
1025
+ Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1026
+ - When deserialize=True: List of UserMemory objects
1027
+ - When deserialize=False: Tuple of (memory dictionaries, total count)
1028
+
1029
+ Raises:
1030
+ Exception: If there is an error getting the memories.
1031
+ """
1032
+ try:
1033
+ collection = await self._get_collection(table_type="memories")
1034
+ if collection is None:
1035
+ return [] if deserialize else ([], 0)
1036
+
1037
+ query: Dict[str, Any] = {}
1038
+ if user_id is not None:
1039
+ query["user_id"] = user_id
1040
+ if agent_id is not None:
1041
+ query["agent_id"] = agent_id
1042
+ if team_id is not None:
1043
+ query["team_id"] = team_id
1044
+ if topics is not None:
1045
+ query["topics"] = {"$in": topics}
1046
+ if search_content is not None:
1047
+ query["memory"] = {"$regex": search_content, "$options": "i"}
1048
+
1049
+ # Get total count
1050
+ total_count = await collection.count_documents(query)
1051
+
1052
+ # Apply sorting
1053
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1054
+
1055
+ # Apply pagination
1056
+ query_args = apply_pagination({}, limit, page)
1057
+
1058
+ cursor = collection.find(query)
1059
+ if sort_criteria:
1060
+ cursor = cursor.sort(sort_criteria)
1061
+ if query_args.get("skip"):
1062
+ cursor = cursor.skip(query_args["skip"])
1063
+ if query_args.get("limit"):
1064
+ cursor = cursor.limit(query_args["limit"])
1065
+
1066
+ records = await cursor.to_list(length=None)
1067
+ if not deserialize:
1068
+ return records, total_count
1069
+
1070
+ # Remove MongoDB's _id field before creating UserMemory objects
1071
+ return [UserMemory.from_dict({k: v for k, v in record.items() if k != "_id"}) for record in records]
1072
+
1073
+ except Exception as e:
1074
+ log_error(f"Exception reading from collection: {e}")
1075
+ raise e
1076
+
1077
+ async def get_user_memory_stats(
1078
+ self,
1079
+ limit: Optional[int] = None,
1080
+ page: Optional[int] = None,
1081
+ user_id: Optional[str] = None,
1082
+ ) -> Tuple[List[Dict[str, Any]], int]:
1083
+ """Get user memories stats.
1084
+
1085
+ Args:
1086
+ limit (Optional[int]): The limit of the memories to get.
1087
+ page (Optional[int]): The page number to get.
1088
+ user_id (Optional[str]): The ID of the user to filter by. Defaults to None.
1089
+
1090
+ Returns:
1091
+ Tuple[List[Dict[str, Any]], int]: A tuple containing the memories stats and the total count.
1092
+
1093
+ Raises:
1094
+ Exception: If there is an error getting the memories stats.
1095
+ """
1096
+ try:
1097
+ collection = await self._get_collection(table_type="memories")
1098
+ if collection is None:
1099
+ return [], 0
1100
+
1101
+ match_stage: Dict[str, Any] = {"user_id": {"$ne": None}}
1102
+ if user_id is not None:
1103
+ match_stage["user_id"] = user_id
1104
+
1105
+ pipeline = [
1106
+ {"$match": match_stage},
1107
+ {
1108
+ "$group": {
1109
+ "_id": "$user_id",
1110
+ "total_memories": {"$sum": 1},
1111
+ "last_memory_updated_at": {"$max": "$updated_at"},
1112
+ }
1113
+ },
1114
+ {"$sort": {"last_memory_updated_at": -1}},
1115
+ ]
1116
+
1117
+ # Get total count
1118
+ count_pipeline = pipeline + [{"$count": "total"}]
1119
+ count_result = await collection.aggregate(count_pipeline).to_list(length=1)
1120
+ total_count = count_result[0]["total"] if count_result else 0
1121
+
1122
+ # Apply pagination
1123
+ if limit is not None:
1124
+ if page is not None:
1125
+ pipeline.append({"$skip": (page - 1) * limit}) # type: ignore
1126
+ pipeline.append({"$limit": limit}) # type: ignore
1127
+
1128
+ results = await collection.aggregate(pipeline).to_list(length=None)
1129
+
1130
+ formatted_results = [
1131
+ {
1132
+ "user_id": result["_id"],
1133
+ "total_memories": result["total_memories"],
1134
+ "last_memory_updated_at": result["last_memory_updated_at"],
1135
+ }
1136
+ for result in results
1137
+ ]
1138
+
1139
+ return formatted_results, total_count
1140
+
1141
+ except Exception as e:
1142
+ log_error(f"Exception getting user memory stats: {e}")
1143
+ raise e
1144
+
1145
+ async def upsert_user_memory(
1146
+ self, memory: UserMemory, deserialize: Optional[bool] = True
1147
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
1148
+ """Upsert a user memory in the database.
1149
+
1150
+ Args:
1151
+ memory (UserMemory): The memory to upsert.
1152
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1153
+
1154
+ Returns:
1155
+ Optional[Union[UserMemory, Dict[str, Any]]]:
1156
+ - When deserialize=True: UserMemory object
1157
+ - When deserialize=False: Memory dictionary
1158
+
1159
+ Raises:
1160
+ Exception: If there is an error upserting the memory.
1161
+ """
1162
+ try:
1163
+ collection = await self._get_collection(table_type="memories", create_collection_if_not_found=True)
1164
+ if collection is None:
1165
+ return None
1166
+
1167
+ if memory.memory_id is None:
1168
+ memory.memory_id = str(uuid4())
1169
+
1170
+ update_doc = {
1171
+ "user_id": memory.user_id,
1172
+ "agent_id": memory.agent_id,
1173
+ "team_id": memory.team_id,
1174
+ "memory_id": memory.memory_id,
1175
+ "memory": memory.memory,
1176
+ "topics": memory.topics,
1177
+ "updated_at": int(time.time()),
1178
+ }
1179
+
1180
+ result = await collection.replace_one({"memory_id": memory.memory_id}, update_doc, upsert=True)
1181
+
1182
+ if result.upserted_id:
1183
+ update_doc["_id"] = result.upserted_id
1184
+
1185
+ if not deserialize:
1186
+ return update_doc
1187
+
1188
+ # Remove MongoDB's _id field before creating UserMemory object
1189
+ update_doc_filtered = {k: v for k, v in update_doc.items() if k != "_id"}
1190
+ return UserMemory.from_dict(update_doc_filtered)
1191
+
1192
+ except Exception as e:
1193
+ log_error(f"Exception upserting user memory: {e}")
1194
+ raise e
1195
+
1196
+ async def upsert_memories(
1197
+ self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False
1198
+ ) -> List[Union[UserMemory, Dict[str, Any]]]:
1199
+ """
1200
+ Bulk upsert multiple user memories for improved performance on large datasets.
1201
+
1202
+ Args:
1203
+ memories (List[UserMemory]): List of memories to upsert.
1204
+ deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True.
1205
+ preserve_updated_at (bool): If True, preserve the updated_at from the memory object.
1206
+
1207
+ Returns:
1208
+ List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories.
1209
+
1210
+ Raises:
1211
+ Exception: If an error occurs during bulk upsert.
1212
+ """
1213
+ if not memories:
1214
+ return []
1215
+
1216
+ try:
1217
+ collection = await self._get_collection(table_type="memories", create_collection_if_not_found=True)
1218
+ if collection is None:
1219
+ log_info("Memories collection not available, falling back to individual upserts")
1220
+ return [
1221
+ result
1222
+ for memory in memories
1223
+ if memory is not None
1224
+ for result in [await self.upsert_user_memory(memory, deserialize=deserialize)]
1225
+ if result is not None
1226
+ ]
1227
+
1228
+ from pymongo import ReplaceOne
1229
+
1230
+ operations = []
1231
+ results: List[Union[UserMemory, Dict[str, Any]]] = []
1232
+
1233
+ current_time = int(time.time())
1234
+ for memory in memories:
1235
+ if memory is None:
1236
+ continue
1237
+
1238
+ if memory.memory_id is None:
1239
+ memory.memory_id = str(uuid4())
1240
+
1241
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
1242
+ updated_at = memory.updated_at if preserve_updated_at else current_time
1243
+
1244
+ record = {
1245
+ "user_id": memory.user_id,
1246
+ "agent_id": memory.agent_id,
1247
+ "team_id": memory.team_id,
1248
+ "memory_id": memory.memory_id,
1249
+ "memory": memory.memory,
1250
+ "topics": memory.topics,
1251
+ "input": memory.input,
1252
+ "feedback": memory.feedback,
1253
+ "created_at": memory.created_at,
1254
+ "updated_at": updated_at,
1255
+ }
1256
+
1257
+ operations.append(ReplaceOne(filter={"memory_id": memory.memory_id}, replacement=record, upsert=True))
1258
+
1259
+ if operations:
1260
+ # Execute bulk write
1261
+ await collection.bulk_write(operations)
1262
+
1263
+ # Fetch the results
1264
+ memory_ids = [memory.memory_id for memory in memories if memory and memory.memory_id]
1265
+ cursor = collection.find({"memory_id": {"$in": memory_ids}})
1266
+
1267
+ async for doc in cursor:
1268
+ if deserialize:
1269
+ # Remove MongoDB's _id field before creating UserMemory object
1270
+ doc_filtered = {k: v for k, v in doc.items() if k != "_id"}
1271
+ results.append(UserMemory.from_dict(doc_filtered))
1272
+ else:
1273
+ results.append(doc)
1274
+
1275
+ return results
1276
+
1277
+ except Exception as e:
1278
+ log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}")
1279
+
1280
+ # Fallback to individual upserts
1281
+ return [
1282
+ result
1283
+ for memory in memories
1284
+ if memory is not None
1285
+ for result in [await self.upsert_user_memory(memory, deserialize=deserialize)]
1286
+ if result is not None
1287
+ ]
1288
+
1289
+ async def clear_memories(self) -> None:
1290
+ """Delete all memories from the database.
1291
+
1292
+ Raises:
1293
+ Exception: If an error occurs during deletion.
1294
+ """
1295
+ try:
1296
+ collection = await self._get_collection(table_type="memories")
1297
+ if collection is None:
1298
+ return
1299
+
1300
+ await collection.delete_many({})
1301
+
1302
+ except Exception as e:
1303
+ log_error(f"Exception deleting all memories: {e}")
1304
+ raise e
1305
+
1306
+ # -- Cultural Knowledge methods --
1307
+ async def clear_cultural_knowledge(self) -> None:
1308
+ """Delete all cultural knowledge from the database.
1309
+
1310
+ Raises:
1311
+ Exception: If an error occurs during deletion.
1312
+ """
1313
+ try:
1314
+ collection = await self._get_collection(table_type="culture")
1315
+ if collection is None:
1316
+ return
1317
+
1318
+ await collection.delete_many({})
1319
+
1320
+ except Exception as e:
1321
+ log_error(f"Exception deleting all cultural knowledge: {e}")
1322
+ raise e
1323
+
1324
+ async def delete_cultural_knowledge(self, id: str) -> None:
1325
+ """Delete cultural knowledge by ID.
1326
+
1327
+ Args:
1328
+ id (str): The ID of the cultural knowledge to delete.
1329
+
1330
+ Raises:
1331
+ Exception: If an error occurs during deletion.
1332
+ """
1333
+ try:
1334
+ collection = await self._get_collection(table_type="culture")
1335
+ if collection is None:
1336
+ return
1337
+
1338
+ await collection.delete_one({"id": id})
1339
+ log_debug(f"Deleted cultural knowledge with ID: {id}")
1340
+
1341
+ except Exception as e:
1342
+ log_error(f"Error deleting cultural knowledge: {e}")
1343
+ raise e
1344
+
1345
+ async def get_cultural_knowledge(
1346
+ self, id: str, deserialize: Optional[bool] = True
1347
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
1348
+ """Get cultural knowledge by ID.
1349
+
1350
+ Args:
1351
+ id (str): The ID of the cultural knowledge to retrieve.
1352
+ deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True.
1353
+
1354
+ Returns:
1355
+ Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise.
1356
+
1357
+ Raises:
1358
+ Exception: If an error occurs during retrieval.
1359
+ """
1360
+ try:
1361
+ collection = await self._get_collection(table_type="culture")
1362
+ if collection is None:
1363
+ return None
1364
+
1365
+ result = await collection.find_one({"id": id})
1366
+ if result is None:
1367
+ return None
1368
+
1369
+ # Remove MongoDB's _id field
1370
+ result_filtered = {k: v for k, v in result.items() if k != "_id"}
1371
+
1372
+ if not deserialize:
1373
+ return result_filtered
1374
+
1375
+ return deserialize_cultural_knowledge_from_db(result_filtered)
1376
+
1377
+ except Exception as e:
1378
+ log_error(f"Error getting cultural knowledge: {e}")
1379
+ raise e
1380
+
1381
+ async def get_all_cultural_knowledge(
1382
+ self,
1383
+ agent_id: Optional[str] = None,
1384
+ team_id: Optional[str] = None,
1385
+ name: Optional[str] = None,
1386
+ limit: Optional[int] = None,
1387
+ page: Optional[int] = None,
1388
+ sort_by: Optional[str] = None,
1389
+ sort_order: Optional[str] = None,
1390
+ deserialize: Optional[bool] = True,
1391
+ ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
1392
+ """Get all cultural knowledge with filtering and pagination.
1393
+
1394
+ Args:
1395
+ agent_id (Optional[str]): Filter by agent ID.
1396
+ team_id (Optional[str]): Filter by team ID.
1397
+ name (Optional[str]): Filter by name (case-insensitive partial match).
1398
+ limit (Optional[int]): Maximum number of results to return.
1399
+ page (Optional[int]): Page number for pagination.
1400
+ sort_by (Optional[str]): Field to sort by.
1401
+ sort_order (Optional[str]): Sort order ('asc' or 'desc').
1402
+ deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True.
1403
+
1404
+ Returns:
1405
+ Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
1406
+ - When deserialize=True: List of CulturalKnowledge objects
1407
+ - When deserialize=False: Tuple with list of dictionaries and total count
1408
+
1409
+ Raises:
1410
+ Exception: If an error occurs during retrieval.
1411
+ """
1412
+ try:
1413
+ collection = await self._get_collection(table_type="culture")
1414
+ if collection is None:
1415
+ if not deserialize:
1416
+ return [], 0
1417
+ return []
1418
+
1419
+ # Build query
1420
+ query: Dict[str, Any] = {}
1421
+ if agent_id is not None:
1422
+ query["agent_id"] = agent_id
1423
+ if team_id is not None:
1424
+ query["team_id"] = team_id
1425
+ if name is not None:
1426
+ query["name"] = {"$regex": name, "$options": "i"}
1427
+
1428
+ # Get total count for pagination
1429
+ total_count = await collection.count_documents(query)
1430
+
1431
+ # Apply sorting
1432
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1433
+
1434
+ # Apply pagination
1435
+ query_args = apply_pagination({}, limit, page)
1436
+
1437
+ cursor = collection.find(query)
1438
+ if sort_criteria:
1439
+ cursor = cursor.sort(sort_criteria)
1440
+ if query_args.get("skip"):
1441
+ cursor = cursor.skip(query_args["skip"])
1442
+ if query_args.get("limit"):
1443
+ cursor = cursor.limit(query_args["limit"])
1444
+
1445
+ # Remove MongoDB's _id field from all results
1446
+ results_filtered = [{k: v for k, v in item.items() if k != "_id"} async for item in cursor]
1447
+
1448
+ if not deserialize:
1449
+ return results_filtered, total_count
1450
+
1451
+ return [deserialize_cultural_knowledge_from_db(item) for item in results_filtered]
1452
+
1453
+ except Exception as e:
1454
+ log_error(f"Error getting all cultural knowledge: {e}")
1455
+ raise e
1456
+
1457
+ async def upsert_cultural_knowledge(
1458
+ self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True
1459
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
1460
+ """Upsert cultural knowledge in MongoDB.
1461
+
1462
+ Args:
1463
+ cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert.
1464
+ deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True.
1465
+
1466
+ Returns:
1467
+ Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge.
1468
+
1469
+ Raises:
1470
+ Exception: If an error occurs during upsert.
1471
+ """
1472
+ try:
1473
+ collection = await self._get_collection(table_type="culture", create_collection_if_not_found=True)
1474
+ if collection is None:
1475
+ return None
1476
+
1477
+ # Serialize content, categories, and notes into a dict for DB storage
1478
+ content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge)
1479
+
1480
+ # Create the document with serialized content
1481
+ update_doc = {
1482
+ "id": cultural_knowledge.id,
1483
+ "name": cultural_knowledge.name,
1484
+ "summary": cultural_knowledge.summary,
1485
+ "content": content_dict if content_dict else None,
1486
+ "metadata": cultural_knowledge.metadata,
1487
+ "input": cultural_knowledge.input,
1488
+ "created_at": cultural_knowledge.created_at,
1489
+ "updated_at": int(time.time()),
1490
+ "agent_id": cultural_knowledge.agent_id,
1491
+ "team_id": cultural_knowledge.team_id,
1492
+ }
1493
+
1494
+ result = await collection.replace_one({"id": cultural_knowledge.id}, update_doc, upsert=True)
1495
+
1496
+ if result.upserted_id:
1497
+ update_doc["_id"] = result.upserted_id
1498
+
1499
+ # Remove MongoDB's _id field
1500
+ doc_filtered = {k: v for k, v in update_doc.items() if k != "_id"}
1501
+
1502
+ if not deserialize:
1503
+ return doc_filtered
1504
+
1505
+ return deserialize_cultural_knowledge_from_db(doc_filtered)
1506
+
1507
+ except Exception as e:
1508
+ log_error(f"Error upserting cultural knowledge: {e}")
1509
+ raise e
1510
+
1511
+ # -- Metrics methods --
1512
+
1513
+ async def _get_all_sessions_for_metrics_calculation(
1514
+ self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
1515
+ ) -> List[Dict[str, Any]]:
1516
+ """Get all sessions of all types for metrics calculation."""
1517
+ try:
1518
+ collection = await self._get_collection(table_type="sessions")
1519
+ if collection is None:
1520
+ return []
1521
+
1522
+ query = {}
1523
+ if start_timestamp is not None:
1524
+ query["created_at"] = {"$gte": start_timestamp}
1525
+ if end_timestamp is not None:
1526
+ if "created_at" in query:
1527
+ query["created_at"]["$lte"] = end_timestamp
1528
+ else:
1529
+ query["created_at"] = {"$lte": end_timestamp}
1530
+
1531
+ projection = {
1532
+ "user_id": 1,
1533
+ "session_data": 1,
1534
+ "runs": 1,
1535
+ "created_at": 1,
1536
+ "session_type": 1,
1537
+ }
1538
+
1539
+ results = await collection.find(query, projection).to_list(length=None)
1540
+ return results
1541
+
1542
+ except Exception as e:
1543
+ log_error(f"Exception reading from sessions collection: {e}")
1544
+ return []
1545
+
1546
+ async def _get_metrics_calculation_starting_date(self, collection: AsyncIOMotorCollection) -> Optional[date]:
1547
+ """Get the first date for which metrics calculation is needed."""
1548
+ try:
1549
+ result = await collection.find_one({}, sort=[("date", -1)], limit=1)
1550
+
1551
+ if result is not None:
1552
+ result_date = datetime.strptime(result["date"], "%Y-%m-%d").date()
1553
+ if result.get("completed"):
1554
+ return result_date + timedelta(days=1)
1555
+ else:
1556
+ return result_date
1557
+
1558
+ # No metrics records. Return the date of the first recorded session.
1559
+ first_session_result = await self.get_sessions(
1560
+ sort_by="created_at", sort_order="asc", limit=1, deserialize=False
1561
+ )
1562
+ first_session_date = first_session_result[0][0]["created_at"] if first_session_result[0] else None # type: ignore
1563
+
1564
+ if first_session_date is None:
1565
+ return None
1566
+
1567
+ return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date()
1568
+
1569
+ except Exception as e:
1570
+ log_error(f"Exception getting metrics calculation starting date: {e}")
1571
+ return None
1572
+
1573
+ async def calculate_metrics(self) -> Optional[list[dict]]:
1574
+ """Calculate metrics for all dates without complete metrics."""
1575
+ try:
1576
+ collection = await self._get_collection(table_type="metrics", create_collection_if_not_found=True)
1577
+ if collection is None:
1578
+ return None
1579
+
1580
+ starting_date = await self._get_metrics_calculation_starting_date(collection)
1581
+ if starting_date is None:
1582
+ log_info("No session data found. Won't calculate metrics.")
1583
+ return None
1584
+
1585
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
1586
+ if not dates_to_process:
1587
+ log_info("Metrics already calculated for all relevant dates.")
1588
+ return None
1589
+
1590
+ start_timestamp = int(
1591
+ datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp()
1592
+ )
1593
+ end_timestamp = int(
1594
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time())
1595
+ .replace(tzinfo=timezone.utc)
1596
+ .timestamp()
1597
+ )
1598
+
1599
+ sessions = await self._get_all_sessions_for_metrics_calculation(
1600
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
1601
+ )
1602
+ all_sessions_data = fetch_all_sessions_data(
1603
+ sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp
1604
+ )
1605
+ if not all_sessions_data:
1606
+ log_info("No new session data found. Won't calculate metrics.")
1607
+ return None
1608
+
1609
+ results = []
1610
+ metrics_records = []
1611
+
1612
+ for date_to_process in dates_to_process:
1613
+ date_key = date_to_process.isoformat()
1614
+ sessions_for_date = all_sessions_data.get(date_key, {})
1615
+
1616
+ # Skip dates with no sessions
1617
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
1618
+ continue
1619
+
1620
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
1621
+ metrics_records.append(metrics_record)
1622
+
1623
+ if metrics_records:
1624
+ results = bulk_upsert_metrics(collection, metrics_records) # type: ignore
1625
+
1626
+ return results
1627
+
1628
+ except Exception as e:
1629
+ log_error(f"Error calculating metrics: {e}")
1630
+ raise e
1631
+
1632
+ async def get_metrics(
1633
+ self,
1634
+ starting_date: Optional[date] = None,
1635
+ ending_date: Optional[date] = None,
1636
+ ) -> Tuple[List[dict], Optional[int]]:
1637
+ """Get all metrics matching the given date range."""
1638
+ try:
1639
+ collection = await self._get_collection(table_type="metrics")
1640
+ if collection is None:
1641
+ return [], None
1642
+
1643
+ query = {}
1644
+ if starting_date:
1645
+ query["date"] = {"$gte": starting_date.isoformat()}
1646
+ if ending_date:
1647
+ if "date" in query:
1648
+ query["date"]["$lte"] = ending_date.isoformat()
1649
+ else:
1650
+ query["date"] = {"$lte": ending_date.isoformat()}
1651
+
1652
+ records = await collection.find(query).to_list(length=None)
1653
+ if not records:
1654
+ return [], None
1655
+
1656
+ # Get the latest updated_at
1657
+ latest_updated_at = max(record.get("updated_at", 0) for record in records)
1658
+
1659
+ return records, latest_updated_at
1660
+
1661
+ except Exception as e:
1662
+ log_error(f"Error getting metrics: {e}")
1663
+ raise e
1664
+
1665
+ # -- Knowledge methods --
1666
+
1667
+ async def delete_knowledge_content(self, id: str):
1668
+ """Delete a knowledge row from the database.
1669
+
1670
+ Args:
1671
+ id (str): The ID of the knowledge row to delete.
1672
+
1673
+ Raises:
1674
+ Exception: If an error occurs during deletion.
1675
+ """
1676
+ try:
1677
+ collection = await self._get_collection(table_type="knowledge")
1678
+ if collection is None:
1679
+ return
1680
+
1681
+ await collection.delete_one({"id": id})
1682
+
1683
+ log_debug(f"Deleted knowledge content with id '{id}'")
1684
+
1685
+ except Exception as e:
1686
+ log_error(f"Error deleting knowledge content: {e}")
1687
+ raise e
1688
+
1689
+ async def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1690
+ """Get a knowledge row from the database.
1691
+
1692
+ Args:
1693
+ id (str): The ID of the knowledge row to get.
1694
+
1695
+ Returns:
1696
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1697
+
1698
+ Raises:
1699
+ Exception: If an error occurs during retrieval.
1700
+ """
1701
+ try:
1702
+ collection = await self._get_collection(table_type="knowledge")
1703
+ if collection is None:
1704
+ return None
1705
+
1706
+ result = await collection.find_one({"id": id})
1707
+ if result is None:
1708
+ return None
1709
+
1710
+ return KnowledgeRow.model_validate(result)
1711
+
1712
+ except Exception as e:
1713
+ log_error(f"Error getting knowledge content: {e}")
1714
+ raise e
1715
+
1716
+ async def get_knowledge_contents(
1717
+ self,
1718
+ limit: Optional[int] = None,
1719
+ page: Optional[int] = None,
1720
+ sort_by: Optional[str] = None,
1721
+ sort_order: Optional[str] = None,
1722
+ ) -> Tuple[List[KnowledgeRow], int]:
1723
+ """Get all knowledge contents from the database.
1724
+
1725
+ Args:
1726
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1727
+ page (Optional[int]): The page number.
1728
+ sort_by (Optional[str]): The column to sort by.
1729
+ sort_order (Optional[str]): The order to sort by.
1730
+
1731
+ Returns:
1732
+ Tuple[List[KnowledgeRow], int]: The knowledge contents and total count.
1733
+
1734
+ Raises:
1735
+ Exception: If an error occurs during retrieval.
1736
+ """
1737
+ try:
1738
+ collection = await self._get_collection(table_type="knowledge")
1739
+ if collection is None:
1740
+ return [], 0
1741
+
1742
+ query: Dict[str, Any] = {}
1743
+
1744
+ # Get total count
1745
+ total_count = await collection.count_documents(query)
1746
+
1747
+ # Apply sorting
1748
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1749
+
1750
+ # Apply pagination
1751
+ query_args = apply_pagination({}, limit, page)
1752
+
1753
+ cursor = collection.find(query)
1754
+ if sort_criteria:
1755
+ cursor = cursor.sort(sort_criteria)
1756
+ if query_args.get("skip"):
1757
+ cursor = cursor.skip(query_args["skip"])
1758
+ if query_args.get("limit"):
1759
+ cursor = cursor.limit(query_args["limit"])
1760
+
1761
+ records = await cursor.to_list(length=None)
1762
+ knowledge_rows = [KnowledgeRow.model_validate(record) for record in records]
1763
+
1764
+ return knowledge_rows, total_count
1765
+
1766
+ except Exception as e:
1767
+ log_error(f"Error getting knowledge contents: {e}")
1768
+ raise e
1769
+
1770
+ async def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1771
+ """Upsert knowledge content in the database.
1772
+
1773
+ Args:
1774
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1775
+
1776
+ Returns:
1777
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1778
+
1779
+ Raises:
1780
+ Exception: If an error occurs during upsert.
1781
+ """
1782
+ try:
1783
+ collection = await self._get_collection(table_type="knowledge", create_collection_if_not_found=True)
1784
+ if collection is None:
1785
+ return None
1786
+
1787
+ update_doc = knowledge_row.model_dump()
1788
+ await collection.replace_one({"id": knowledge_row.id}, update_doc, upsert=True)
1789
+
1790
+ return knowledge_row
1791
+
1792
+ except Exception as e:
1793
+ log_error(f"Error upserting knowledge content: {e}")
1794
+ raise e
1795
+
1796
+ # -- Eval methods --
1797
+
1798
+ async def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1799
+ """Create an EvalRunRecord in the database."""
1800
+ try:
1801
+ collection = await self._get_collection(table_type="evals", create_collection_if_not_found=True)
1802
+ if collection is None:
1803
+ return None
1804
+
1805
+ current_time = int(time.time())
1806
+ eval_dict = eval_run.model_dump()
1807
+ eval_dict["created_at"] = current_time
1808
+ eval_dict["updated_at"] = current_time
1809
+
1810
+ await collection.insert_one(eval_dict)
1811
+
1812
+ log_debug(f"Created eval run with id '{eval_run.run_id}'")
1813
+
1814
+ return eval_run
1815
+
1816
+ except Exception as e:
1817
+ log_error(f"Error creating eval run: {e}")
1818
+ raise e
1819
+
1820
+ async def delete_eval_run(self, eval_run_id: str) -> None:
1821
+ """Delete an eval run from the database."""
1822
+ try:
1823
+ collection = await self._get_collection(table_type="evals")
1824
+ if collection is None:
1825
+ return
1826
+
1827
+ result = await collection.delete_one({"run_id": eval_run_id})
1828
+
1829
+ if result.deleted_count == 0:
1830
+ log_debug(f"No eval run found with ID: {eval_run_id}")
1831
+ else:
1832
+ log_debug(f"Deleted eval run with ID: {eval_run_id}")
1833
+
1834
+ except Exception as e:
1835
+ log_error(f"Error deleting eval run {eval_run_id}: {e}")
1836
+ raise e
1837
+
1838
+ async def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1839
+ """Delete multiple eval runs from the database."""
1840
+ try:
1841
+ collection = await self._get_collection(table_type="evals")
1842
+ if collection is None:
1843
+ return
1844
+
1845
+ result = await collection.delete_many({"run_id": {"$in": eval_run_ids}})
1846
+
1847
+ if result.deleted_count == 0:
1848
+ log_debug(f"No eval runs found with IDs: {eval_run_ids}")
1849
+ else:
1850
+ log_debug(f"Deleted {result.deleted_count} eval runs")
1851
+
1852
+ except Exception as e:
1853
+ log_error(f"Error deleting eval runs {eval_run_ids}: {e}")
1854
+ raise e
1855
+
1856
+ async def get_eval_run_raw(self, eval_run_id: str) -> Optional[Dict[str, Any]]:
1857
+ """Get an eval run from the database as a raw dictionary."""
1858
+ try:
1859
+ collection = await self._get_collection(table_type="evals")
1860
+ if collection is None:
1861
+ return None
1862
+
1863
+ result = await collection.find_one({"run_id": eval_run_id})
1864
+ return result
1865
+
1866
+ except Exception as e:
1867
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1868
+ raise e
1869
+
1870
+ async def get_eval_run(
1871
+ self, eval_run_id: str, deserialize: Optional[bool] = True
1872
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1873
+ """Get an eval run from the database.
1874
+
1875
+ Args:
1876
+ eval_run_id (str): The ID of the eval run to get.
1877
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1878
+
1879
+ Returns:
1880
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1881
+ - When deserialize=True: EvalRunRecord object
1882
+ - When deserialize=False: EvalRun dictionary
1883
+
1884
+ Raises:
1885
+ Exception: If there is an error getting the eval run.
1886
+ """
1887
+ try:
1888
+ collection = await self._get_collection(table_type="evals")
1889
+ if collection is None:
1890
+ return None
1891
+
1892
+ eval_run_raw = await collection.find_one({"run_id": eval_run_id})
1893
+
1894
+ if not eval_run_raw:
1895
+ return None
1896
+
1897
+ if not deserialize:
1898
+ return eval_run_raw
1899
+
1900
+ return EvalRunRecord.model_validate(eval_run_raw)
1901
+
1902
+ except Exception as e:
1903
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1904
+ raise e
1905
+
1906
+ async def get_eval_runs(
1907
+ self,
1908
+ limit: Optional[int] = None,
1909
+ page: Optional[int] = None,
1910
+ sort_by: Optional[str] = None,
1911
+ sort_order: Optional[str] = None,
1912
+ agent_id: Optional[str] = None,
1913
+ team_id: Optional[str] = None,
1914
+ workflow_id: Optional[str] = None,
1915
+ model_id: Optional[str] = None,
1916
+ filter_type: Optional[EvalFilterType] = None,
1917
+ eval_type: Optional[List[EvalType]] = None,
1918
+ deserialize: Optional[bool] = True,
1919
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1920
+ """Get all eval runs from the database.
1921
+
1922
+ Args:
1923
+ limit (Optional[int]): The maximum number of eval runs to return.
1924
+ page (Optional[int]): The page number to return.
1925
+ sort_by (Optional[str]): The field to sort by.
1926
+ sort_order (Optional[str]): The order to sort by.
1927
+ agent_id (Optional[str]): The ID of the agent to filter by.
1928
+ team_id (Optional[str]): The ID of the team to filter by.
1929
+ workflow_id (Optional[str]): The ID of the workflow to filter by.
1930
+ model_id (Optional[str]): The ID of the model to filter by.
1931
+ eval_type (Optional[List[EvalType]]): The type of eval to filter by.
1932
+ filter_type (Optional[EvalFilterType]): The type of filter to apply.
1933
+ deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True.
1934
+
1935
+ Returns:
1936
+ Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1937
+ - When deserialize=True: List of EvalRunRecord objects
1938
+ - When deserialize=False: List of eval run dictionaries and the total count
1939
+
1940
+ Raises:
1941
+ Exception: If there is an error getting the eval runs.
1942
+ """
1943
+ try:
1944
+ collection = await self._get_collection(table_type="evals")
1945
+ if collection is None:
1946
+ return [] if deserialize else ([], 0)
1947
+
1948
+ query: Dict[str, Any] = {}
1949
+ if agent_id is not None:
1950
+ query["agent_id"] = agent_id
1951
+ if team_id is not None:
1952
+ query["team_id"] = team_id
1953
+ if workflow_id is not None:
1954
+ query["workflow_id"] = workflow_id
1955
+ if model_id is not None:
1956
+ query["model_id"] = model_id
1957
+ if eval_type is not None and len(eval_type) > 0:
1958
+ query["eval_type"] = {"$in": eval_type}
1959
+ if filter_type is not None:
1960
+ if filter_type == EvalFilterType.AGENT:
1961
+ query["agent_id"] = {"$ne": None}
1962
+ elif filter_type == EvalFilterType.TEAM:
1963
+ query["team_id"] = {"$ne": None}
1964
+ elif filter_type == EvalFilterType.WORKFLOW:
1965
+ query["workflow_id"] = {"$ne": None}
1966
+
1967
+ # Get total count
1968
+ total_count = await collection.count_documents(query)
1969
+
1970
+ # Apply default sorting by created_at desc if no sort parameters provided
1971
+ if sort_by is None:
1972
+ sort_criteria = [("created_at", -1)]
1973
+ else:
1974
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1975
+
1976
+ # Apply pagination
1977
+ query_args = apply_pagination({}, limit, page)
1978
+
1979
+ cursor = collection.find(query)
1980
+ if sort_criteria:
1981
+ cursor = cursor.sort(sort_criteria)
1982
+ if query_args.get("skip"):
1983
+ cursor = cursor.skip(query_args["skip"])
1984
+ if query_args.get("limit"):
1985
+ cursor = cursor.limit(query_args["limit"])
1986
+
1987
+ records = await cursor.to_list(length=None)
1988
+ if not records:
1989
+ return [] if deserialize else ([], 0)
1990
+
1991
+ if not deserialize:
1992
+ return records, total_count
1993
+
1994
+ return [EvalRunRecord.model_validate(row) for row in records]
1995
+
1996
+ except Exception as e:
1997
+ log_error(f"Exception getting eval runs: {e}")
1998
+ raise e
1999
+
2000
+ async def rename_eval_run(
2001
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
2002
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
2003
+ """Update the name of an eval run in the database.
2004
+
2005
+ Args:
2006
+ eval_run_id (str): The ID of the eval run to update.
2007
+ name (str): The new name of the eval run.
2008
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
2009
+
2010
+ Returns:
2011
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
2012
+ - When deserialize=True: EvalRunRecord object
2013
+ - When deserialize=False: EvalRun dictionary
2014
+
2015
+ Raises:
2016
+ Exception: If there is an error updating the eval run.
2017
+ """
2018
+ try:
2019
+ collection = await self._get_collection(table_type="evals")
2020
+ if collection is None:
2021
+ return None
2022
+
2023
+ result = await collection.find_one_and_update(
2024
+ {"run_id": eval_run_id}, {"$set": {"name": name, "updated_at": int(time.time())}}
2025
+ )
2026
+
2027
+ log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'")
2028
+
2029
+ if not result or not deserialize:
2030
+ return result
2031
+
2032
+ return EvalRunRecord.model_validate(result)
2033
+
2034
+ except Exception as e:
2035
+ log_error(f"Error updating eval run name {eval_run_id}: {e}")
2036
+ raise e