agno 1.8.1__py3-none-any.whl → 2.0.0a1__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 (580) hide show
  1. agno/__init__.py +8 -0
  2. agno/agent/__init__.py +19 -27
  3. agno/agent/agent.py +2778 -4123
  4. agno/api/agent.py +9 -65
  5. agno/api/api.py +5 -46
  6. agno/api/evals.py +6 -17
  7. agno/api/os.py +17 -0
  8. agno/api/routes.py +6 -41
  9. agno/api/schemas/__init__.py +9 -0
  10. agno/api/schemas/agent.py +5 -21
  11. agno/api/schemas/evals.py +7 -16
  12. agno/api/schemas/os.py +14 -0
  13. agno/api/schemas/team.py +5 -21
  14. agno/api/schemas/utils.py +21 -0
  15. agno/api/schemas/workflows.py +11 -7
  16. agno/api/settings.py +53 -0
  17. agno/api/team.py +9 -64
  18. agno/api/workflow.py +28 -0
  19. agno/cloud/aws/base.py +214 -0
  20. agno/cloud/aws/s3/__init__.py +2 -0
  21. agno/cloud/aws/s3/api_client.py +43 -0
  22. agno/cloud/aws/s3/bucket.py +195 -0
  23. agno/cloud/aws/s3/object.py +57 -0
  24. agno/db/__init__.py +24 -0
  25. agno/db/base.py +245 -0
  26. agno/db/dynamo/__init__.py +3 -0
  27. agno/db/dynamo/dynamo.py +1749 -0
  28. agno/db/dynamo/schemas.py +278 -0
  29. agno/db/dynamo/utils.py +684 -0
  30. agno/db/firestore/__init__.py +3 -0
  31. agno/db/firestore/firestore.py +1438 -0
  32. agno/db/firestore/schemas.py +130 -0
  33. agno/db/firestore/utils.py +278 -0
  34. agno/db/gcs_json/__init__.py +3 -0
  35. agno/db/gcs_json/gcs_json_db.py +1001 -0
  36. agno/db/gcs_json/utils.py +194 -0
  37. agno/db/in_memory/__init__.py +3 -0
  38. agno/db/in_memory/in_memory_db.py +888 -0
  39. agno/db/in_memory/utils.py +172 -0
  40. agno/db/json/__init__.py +3 -0
  41. agno/db/json/json_db.py +1051 -0
  42. agno/db/json/utils.py +196 -0
  43. agno/db/migrations/v1_to_v2.py +162 -0
  44. agno/db/mongo/__init__.py +3 -0
  45. agno/db/mongo/mongo.py +1417 -0
  46. agno/db/mongo/schemas.py +77 -0
  47. agno/db/mongo/utils.py +204 -0
  48. agno/db/mysql/__init__.py +3 -0
  49. agno/db/mysql/mysql.py +1719 -0
  50. agno/db/mysql/schemas.py +124 -0
  51. agno/db/mysql/utils.py +298 -0
  52. agno/db/postgres/__init__.py +3 -0
  53. agno/db/postgres/postgres.py +1720 -0
  54. agno/db/postgres/schemas.py +124 -0
  55. agno/db/postgres/utils.py +281 -0
  56. agno/db/redis/__init__.py +3 -0
  57. agno/db/redis/redis.py +1371 -0
  58. agno/db/redis/schemas.py +109 -0
  59. agno/db/redis/utils.py +288 -0
  60. agno/db/schemas/__init__.py +3 -0
  61. agno/db/schemas/evals.py +33 -0
  62. agno/db/schemas/knowledge.py +40 -0
  63. agno/db/schemas/memory.py +46 -0
  64. agno/db/singlestore/__init__.py +3 -0
  65. agno/db/singlestore/schemas.py +116 -0
  66. agno/db/singlestore/singlestore.py +1722 -0
  67. agno/db/singlestore/utils.py +327 -0
  68. agno/db/sqlite/__init__.py +3 -0
  69. agno/db/sqlite/schemas.py +119 -0
  70. agno/db/sqlite/sqlite.py +1680 -0
  71. agno/db/sqlite/utils.py +269 -0
  72. agno/db/utils.py +88 -0
  73. agno/eval/__init__.py +14 -0
  74. agno/eval/accuracy.py +142 -43
  75. agno/eval/performance.py +88 -23
  76. agno/eval/reliability.py +73 -20
  77. agno/eval/utils.py +23 -13
  78. agno/integrations/discord/__init__.py +3 -0
  79. agno/{app → integrations}/discord/client.py +10 -10
  80. agno/knowledge/__init__.py +2 -2
  81. agno/{document → knowledge}/chunking/agentic.py +2 -2
  82. agno/{document → knowledge}/chunking/document.py +2 -2
  83. agno/{document → knowledge}/chunking/fixed.py +3 -3
  84. agno/{document → knowledge}/chunking/markdown.py +2 -2
  85. agno/{document → knowledge}/chunking/recursive.py +2 -2
  86. agno/{document → knowledge}/chunking/row.py +2 -2
  87. agno/knowledge/chunking/semantic.py +59 -0
  88. agno/knowledge/chunking/strategy.py +121 -0
  89. agno/knowledge/content.py +74 -0
  90. agno/knowledge/document/__init__.py +5 -0
  91. agno/{document → knowledge/document}/base.py +12 -2
  92. agno/knowledge/embedder/__init__.py +5 -0
  93. agno/{embedder → knowledge/embedder}/aws_bedrock.py +127 -1
  94. agno/{embedder → knowledge/embedder}/azure_openai.py +65 -1
  95. agno/{embedder → knowledge/embedder}/base.py +6 -0
  96. agno/{embedder → knowledge/embedder}/cohere.py +72 -1
  97. agno/{embedder → knowledge/embedder}/fastembed.py +17 -1
  98. agno/{embedder → knowledge/embedder}/fireworks.py +1 -1
  99. agno/{embedder → knowledge/embedder}/google.py +74 -1
  100. agno/{embedder → knowledge/embedder}/huggingface.py +36 -2
  101. agno/{embedder → knowledge/embedder}/jina.py +48 -2
  102. agno/knowledge/embedder/langdb.py +22 -0
  103. agno/knowledge/embedder/mistral.py +139 -0
  104. agno/{embedder → knowledge/embedder}/nebius.py +1 -1
  105. agno/{embedder → knowledge/embedder}/ollama.py +54 -3
  106. agno/knowledge/embedder/openai.py +223 -0
  107. agno/{embedder → knowledge/embedder}/sentence_transformer.py +16 -1
  108. agno/{embedder → knowledge/embedder}/together.py +1 -1
  109. agno/{embedder → knowledge/embedder}/voyageai.py +49 -1
  110. agno/knowledge/knowledge.py +1515 -0
  111. agno/knowledge/reader/__init__.py +7 -0
  112. agno/{document → knowledge}/reader/arxiv_reader.py +32 -4
  113. agno/knowledge/reader/base.py +88 -0
  114. agno/{document → knowledge}/reader/csv_reader.py +68 -15
  115. agno/knowledge/reader/docx_reader.py +83 -0
  116. agno/{document → knowledge}/reader/firecrawl_reader.py +42 -21
  117. agno/knowledge/reader/gcs_reader.py +67 -0
  118. agno/{document → knowledge}/reader/json_reader.py +30 -9
  119. agno/{document → knowledge}/reader/markdown_reader.py +36 -9
  120. agno/{document → knowledge}/reader/pdf_reader.py +79 -21
  121. agno/knowledge/reader/reader_factory.py +275 -0
  122. agno/knowledge/reader/s3_reader.py +171 -0
  123. agno/{document → knowledge}/reader/text_reader.py +31 -10
  124. agno/knowledge/reader/url_reader.py +84 -0
  125. agno/knowledge/reader/web_search_reader.py +389 -0
  126. agno/{document → knowledge}/reader/website_reader.py +37 -10
  127. agno/knowledge/reader/wikipedia_reader.py +59 -0
  128. agno/knowledge/reader/youtube_reader.py +78 -0
  129. agno/knowledge/remote_content/remote_content.py +88 -0
  130. agno/{reranker → knowledge/reranker}/base.py +1 -1
  131. agno/{reranker → knowledge/reranker}/cohere.py +2 -2
  132. agno/{reranker → knowledge/reranker}/infinity.py +2 -2
  133. agno/{reranker → knowledge/reranker}/sentence_transformer.py +2 -2
  134. agno/knowledge/types.py +30 -0
  135. agno/knowledge/utils.py +169 -0
  136. agno/memory/__init__.py +2 -10
  137. agno/memory/manager.py +1003 -148
  138. agno/models/aimlapi/__init__.py +2 -2
  139. agno/models/aimlapi/aimlapi.py +6 -6
  140. agno/models/anthropic/claude.py +129 -82
  141. agno/models/aws/bedrock.py +107 -175
  142. agno/models/aws/claude.py +64 -18
  143. agno/models/azure/ai_foundry.py +73 -23
  144. agno/models/base.py +347 -287
  145. agno/models/cerebras/cerebras.py +84 -27
  146. agno/models/cohere/chat.py +106 -98
  147. agno/models/google/gemini.py +100 -42
  148. agno/models/groq/groq.py +97 -35
  149. agno/models/huggingface/huggingface.py +92 -27
  150. agno/models/ibm/watsonx.py +72 -13
  151. agno/models/litellm/chat.py +85 -13
  152. agno/models/message.py +38 -144
  153. agno/models/meta/llama.py +85 -49
  154. agno/models/metrics.py +120 -0
  155. agno/models/mistral/mistral.py +90 -21
  156. agno/models/ollama/__init__.py +0 -2
  157. agno/models/ollama/chat.py +84 -46
  158. agno/models/openai/chat.py +121 -23
  159. agno/models/openai/responses.py +178 -105
  160. agno/models/perplexity/perplexity.py +26 -2
  161. agno/models/portkey/portkey.py +0 -7
  162. agno/models/response.py +14 -8
  163. agno/models/utils.py +20 -0
  164. agno/models/vercel/__init__.py +2 -2
  165. agno/models/vercel/v0.py +1 -1
  166. agno/models/vllm/__init__.py +2 -2
  167. agno/models/vllm/vllm.py +3 -3
  168. agno/models/xai/xai.py +10 -10
  169. agno/os/__init__.py +3 -0
  170. agno/os/app.py +393 -0
  171. agno/os/auth.py +47 -0
  172. agno/os/config.py +103 -0
  173. agno/os/interfaces/agui/__init__.py +3 -0
  174. agno/os/interfaces/agui/agui.py +31 -0
  175. agno/{app/agui/async_router.py → os/interfaces/agui/router.py} +16 -16
  176. agno/{app → os/interfaces}/agui/utils.py +65 -28
  177. agno/os/interfaces/base.py +21 -0
  178. agno/os/interfaces/slack/__init__.py +3 -0
  179. agno/{app/slack/async_router.py → os/interfaces/slack/router.py} +3 -5
  180. agno/os/interfaces/slack/slack.py +33 -0
  181. agno/os/interfaces/whatsapp/__init__.py +3 -0
  182. agno/{app/whatsapp/async_router.py → os/interfaces/whatsapp/router.py} +4 -7
  183. agno/os/interfaces/whatsapp/whatsapp.py +30 -0
  184. agno/os/router.py +843 -0
  185. agno/os/routers/__init__.py +3 -0
  186. agno/os/routers/evals/__init__.py +3 -0
  187. agno/os/routers/evals/evals.py +204 -0
  188. agno/os/routers/evals/schemas.py +142 -0
  189. agno/os/routers/evals/utils.py +161 -0
  190. agno/os/routers/knowledge/__init__.py +3 -0
  191. agno/os/routers/knowledge/knowledge.py +413 -0
  192. agno/os/routers/knowledge/schemas.py +118 -0
  193. agno/os/routers/memory/__init__.py +3 -0
  194. agno/os/routers/memory/memory.py +179 -0
  195. agno/os/routers/memory/schemas.py +58 -0
  196. agno/os/routers/metrics/__init__.py +3 -0
  197. agno/os/routers/metrics/metrics.py +58 -0
  198. agno/os/routers/metrics/schemas.py +47 -0
  199. agno/os/routers/session/__init__.py +3 -0
  200. agno/os/routers/session/session.py +163 -0
  201. agno/os/schema.py +892 -0
  202. agno/{app/playground → os}/settings.py +8 -15
  203. agno/os/utils.py +270 -0
  204. agno/reasoning/azure_ai_foundry.py +4 -4
  205. agno/reasoning/deepseek.py +4 -4
  206. agno/reasoning/default.py +6 -11
  207. agno/reasoning/groq.py +4 -4
  208. agno/reasoning/helpers.py +4 -6
  209. agno/reasoning/ollama.py +4 -4
  210. agno/reasoning/openai.py +4 -4
  211. agno/run/{response.py → agent.py} +144 -72
  212. agno/run/base.py +44 -58
  213. agno/run/cancel.py +83 -0
  214. agno/run/team.py +133 -77
  215. agno/run/workflow.py +537 -12
  216. agno/session/__init__.py +10 -0
  217. agno/session/agent.py +244 -0
  218. agno/session/summary.py +225 -0
  219. agno/session/team.py +262 -0
  220. agno/{storage/session/v2 → session}/workflow.py +47 -24
  221. agno/team/__init__.py +15 -16
  222. agno/team/team.py +2961 -4253
  223. agno/tools/agentql.py +14 -5
  224. agno/tools/airflow.py +9 -4
  225. agno/tools/api.py +7 -3
  226. agno/tools/apify.py +2 -46
  227. agno/tools/arxiv.py +8 -3
  228. agno/tools/aws_lambda.py +7 -5
  229. agno/tools/aws_ses.py +7 -1
  230. agno/tools/baidusearch.py +4 -1
  231. agno/tools/bitbucket.py +4 -4
  232. agno/tools/brandfetch.py +14 -11
  233. agno/tools/bravesearch.py +4 -1
  234. agno/tools/brightdata.py +42 -22
  235. agno/tools/browserbase.py +13 -4
  236. agno/tools/calcom.py +12 -10
  237. agno/tools/calculator.py +10 -27
  238. agno/tools/cartesia.py +18 -13
  239. agno/tools/{clickup_tool.py → clickup.py} +12 -25
  240. agno/tools/confluence.py +8 -8
  241. agno/tools/crawl4ai.py +7 -1
  242. agno/tools/csv_toolkit.py +9 -8
  243. agno/tools/dalle.py +18 -11
  244. agno/tools/daytona.py +13 -16
  245. agno/tools/decorator.py +6 -3
  246. agno/tools/desi_vocal.py +16 -7
  247. agno/tools/discord.py +11 -8
  248. agno/tools/docker.py +30 -42
  249. agno/tools/duckdb.py +34 -53
  250. agno/tools/duckduckgo.py +8 -7
  251. agno/tools/e2b.py +61 -61
  252. agno/tools/eleven_labs.py +35 -28
  253. agno/tools/email.py +4 -1
  254. agno/tools/evm.py +7 -1
  255. agno/tools/exa.py +19 -14
  256. agno/tools/fal.py +29 -29
  257. agno/tools/file.py +9 -8
  258. agno/tools/financial_datasets.py +25 -44
  259. agno/tools/firecrawl.py +22 -22
  260. agno/tools/function.py +68 -17
  261. agno/tools/giphy.py +22 -10
  262. agno/tools/github.py +48 -126
  263. agno/tools/gmail.py +45 -61
  264. agno/tools/google_bigquery.py +7 -6
  265. agno/tools/google_maps.py +11 -26
  266. agno/tools/googlesearch.py +7 -2
  267. agno/tools/googlesheets.py +21 -17
  268. agno/tools/hackernews.py +9 -5
  269. agno/tools/jina.py +5 -4
  270. agno/tools/jira.py +18 -9
  271. agno/tools/knowledge.py +31 -32
  272. agno/tools/linear.py +18 -33
  273. agno/tools/linkup.py +5 -1
  274. agno/tools/local_file_system.py +8 -5
  275. agno/tools/lumalab.py +31 -19
  276. agno/tools/mem0.py +18 -12
  277. agno/tools/memori.py +14 -10
  278. agno/tools/mlx_transcribe.py +3 -2
  279. agno/tools/models/azure_openai.py +32 -14
  280. agno/tools/models/gemini.py +58 -31
  281. agno/tools/models/groq.py +29 -20
  282. agno/tools/models/nebius.py +27 -11
  283. agno/tools/models_labs.py +39 -15
  284. agno/tools/moviepy_video.py +7 -6
  285. agno/tools/neo4j.py +10 -8
  286. agno/tools/newspaper.py +7 -2
  287. agno/tools/newspaper4k.py +8 -3
  288. agno/tools/openai.py +57 -26
  289. agno/tools/openbb.py +12 -11
  290. agno/tools/opencv.py +62 -46
  291. agno/tools/openweather.py +14 -12
  292. agno/tools/pandas.py +11 -3
  293. agno/tools/postgres.py +4 -12
  294. agno/tools/pubmed.py +4 -1
  295. agno/tools/python.py +9 -22
  296. agno/tools/reasoning.py +35 -27
  297. agno/tools/reddit.py +11 -26
  298. agno/tools/replicate.py +54 -41
  299. agno/tools/resend.py +4 -1
  300. agno/tools/scrapegraph.py +15 -14
  301. agno/tools/searxng.py +10 -23
  302. agno/tools/serpapi.py +6 -3
  303. agno/tools/serper.py +13 -4
  304. agno/tools/shell.py +9 -2
  305. agno/tools/slack.py +12 -11
  306. agno/tools/sleep.py +3 -2
  307. agno/tools/spider.py +24 -4
  308. agno/tools/sql.py +7 -6
  309. agno/tools/tavily.py +6 -4
  310. agno/tools/telegram.py +12 -4
  311. agno/tools/todoist.py +11 -31
  312. agno/tools/toolkit.py +1 -1
  313. agno/tools/trafilatura.py +22 -6
  314. agno/tools/trello.py +9 -22
  315. agno/tools/twilio.py +10 -3
  316. agno/tools/user_control_flow.py +6 -1
  317. agno/tools/valyu.py +34 -5
  318. agno/tools/visualization.py +19 -28
  319. agno/tools/webbrowser.py +4 -3
  320. agno/tools/webex.py +11 -7
  321. agno/tools/website.py +15 -46
  322. agno/tools/webtools.py +12 -4
  323. agno/tools/whatsapp.py +5 -9
  324. agno/tools/wikipedia.py +20 -13
  325. agno/tools/x.py +14 -13
  326. agno/tools/yfinance.py +13 -40
  327. agno/tools/youtube.py +26 -20
  328. agno/tools/zendesk.py +7 -2
  329. agno/tools/zep.py +10 -7
  330. agno/tools/zoom.py +10 -9
  331. agno/utils/common.py +1 -19
  332. agno/utils/events.py +95 -118
  333. agno/utils/knowledge.py +29 -0
  334. agno/utils/log.py +2 -2
  335. agno/utils/mcp.py +11 -5
  336. agno/utils/media.py +39 -0
  337. agno/utils/message.py +12 -1
  338. agno/utils/models/claude.py +6 -4
  339. agno/utils/models/mistral.py +8 -7
  340. agno/utils/models/schema_utils.py +3 -3
  341. agno/utils/pprint.py +33 -32
  342. agno/utils/print_response/agent.py +779 -0
  343. agno/utils/print_response/team.py +1565 -0
  344. agno/utils/print_response/workflow.py +1451 -0
  345. agno/utils/prompts.py +14 -14
  346. agno/utils/reasoning.py +87 -0
  347. agno/utils/response.py +42 -42
  348. agno/utils/string.py +8 -22
  349. agno/utils/team.py +50 -0
  350. agno/utils/timer.py +2 -2
  351. agno/vectordb/base.py +33 -21
  352. agno/vectordb/cassandra/cassandra.py +287 -23
  353. agno/vectordb/chroma/chromadb.py +482 -59
  354. agno/vectordb/clickhouse/clickhousedb.py +270 -63
  355. agno/vectordb/couchbase/couchbase.py +309 -29
  356. agno/vectordb/lancedb/lance_db.py +360 -21
  357. agno/vectordb/langchaindb/__init__.py +5 -0
  358. agno/vectordb/langchaindb/langchaindb.py +145 -0
  359. agno/vectordb/lightrag/__init__.py +5 -0
  360. agno/vectordb/lightrag/lightrag.py +374 -0
  361. agno/vectordb/llamaindex/llamaindexdb.py +127 -0
  362. agno/vectordb/milvus/milvus.py +242 -32
  363. agno/vectordb/mongodb/mongodb.py +200 -24
  364. agno/vectordb/pgvector/pgvector.py +319 -37
  365. agno/vectordb/pineconedb/pineconedb.py +221 -27
  366. agno/vectordb/qdrant/qdrant.py +334 -14
  367. agno/vectordb/singlestore/singlestore.py +286 -29
  368. agno/vectordb/surrealdb/surrealdb.py +187 -7
  369. agno/vectordb/upstashdb/upstashdb.py +342 -26
  370. agno/vectordb/weaviate/weaviate.py +227 -165
  371. agno/workflow/__init__.py +17 -13
  372. agno/workflow/{v2/condition.py → condition.py} +135 -32
  373. agno/workflow/{v2/loop.py → loop.py} +115 -28
  374. agno/workflow/{v2/parallel.py → parallel.py} +138 -108
  375. agno/workflow/{v2/router.py → router.py} +133 -32
  376. agno/workflow/{v2/step.py → step.py} +200 -42
  377. agno/workflow/{v2/steps.py → steps.py} +147 -66
  378. agno/workflow/types.py +482 -0
  379. agno/workflow/workflow.py +2394 -696
  380. agno-2.0.0a1.dist-info/METADATA +355 -0
  381. agno-2.0.0a1.dist-info/RECORD +514 -0
  382. agno/agent/metrics.py +0 -107
  383. agno/api/app.py +0 -35
  384. agno/api/playground.py +0 -92
  385. agno/api/schemas/app.py +0 -12
  386. agno/api/schemas/playground.py +0 -22
  387. agno/api/schemas/user.py +0 -35
  388. agno/api/schemas/workspace.py +0 -46
  389. agno/api/user.py +0 -160
  390. agno/api/workflows.py +0 -33
  391. agno/api/workspace.py +0 -175
  392. agno/app/agui/__init__.py +0 -3
  393. agno/app/agui/app.py +0 -17
  394. agno/app/agui/sync_router.py +0 -120
  395. agno/app/base.py +0 -186
  396. agno/app/discord/__init__.py +0 -3
  397. agno/app/fastapi/__init__.py +0 -3
  398. agno/app/fastapi/app.py +0 -107
  399. agno/app/fastapi/async_router.py +0 -457
  400. agno/app/fastapi/sync_router.py +0 -448
  401. agno/app/playground/app.py +0 -228
  402. agno/app/playground/async_router.py +0 -1050
  403. agno/app/playground/deploy.py +0 -249
  404. agno/app/playground/operator.py +0 -183
  405. agno/app/playground/schemas.py +0 -220
  406. agno/app/playground/serve.py +0 -55
  407. agno/app/playground/sync_router.py +0 -1042
  408. agno/app/playground/utils.py +0 -46
  409. agno/app/settings.py +0 -15
  410. agno/app/slack/__init__.py +0 -3
  411. agno/app/slack/app.py +0 -19
  412. agno/app/slack/sync_router.py +0 -92
  413. agno/app/utils.py +0 -54
  414. agno/app/whatsapp/__init__.py +0 -3
  415. agno/app/whatsapp/app.py +0 -15
  416. agno/app/whatsapp/sync_router.py +0 -197
  417. agno/cli/auth_server.py +0 -249
  418. agno/cli/config.py +0 -274
  419. agno/cli/console.py +0 -88
  420. agno/cli/credentials.py +0 -23
  421. agno/cli/entrypoint.py +0 -571
  422. agno/cli/operator.py +0 -357
  423. agno/cli/settings.py +0 -96
  424. agno/cli/ws/ws_cli.py +0 -817
  425. agno/constants.py +0 -13
  426. agno/document/__init__.py +0 -5
  427. agno/document/chunking/semantic.py +0 -45
  428. agno/document/chunking/strategy.py +0 -31
  429. agno/document/reader/__init__.py +0 -5
  430. agno/document/reader/base.py +0 -47
  431. agno/document/reader/docx_reader.py +0 -60
  432. agno/document/reader/gcs/pdf_reader.py +0 -44
  433. agno/document/reader/s3/pdf_reader.py +0 -59
  434. agno/document/reader/s3/text_reader.py +0 -63
  435. agno/document/reader/url_reader.py +0 -59
  436. agno/document/reader/youtube_reader.py +0 -58
  437. agno/embedder/__init__.py +0 -5
  438. agno/embedder/langdb.py +0 -80
  439. agno/embedder/mistral.py +0 -82
  440. agno/embedder/openai.py +0 -78
  441. agno/file/__init__.py +0 -5
  442. agno/file/file.py +0 -16
  443. agno/file/local/csv.py +0 -32
  444. agno/file/local/txt.py +0 -19
  445. agno/infra/app.py +0 -240
  446. agno/infra/base.py +0 -144
  447. agno/infra/context.py +0 -20
  448. agno/infra/db_app.py +0 -52
  449. agno/infra/resource.py +0 -205
  450. agno/infra/resources.py +0 -55
  451. agno/knowledge/agent.py +0 -702
  452. agno/knowledge/arxiv.py +0 -33
  453. agno/knowledge/combined.py +0 -36
  454. agno/knowledge/csv.py +0 -144
  455. agno/knowledge/csv_url.py +0 -124
  456. agno/knowledge/document.py +0 -223
  457. agno/knowledge/docx.py +0 -137
  458. agno/knowledge/firecrawl.py +0 -34
  459. agno/knowledge/gcs/__init__.py +0 -0
  460. agno/knowledge/gcs/base.py +0 -39
  461. agno/knowledge/gcs/pdf.py +0 -125
  462. agno/knowledge/json.py +0 -137
  463. agno/knowledge/langchain.py +0 -71
  464. agno/knowledge/light_rag.py +0 -273
  465. agno/knowledge/llamaindex.py +0 -66
  466. agno/knowledge/markdown.py +0 -154
  467. agno/knowledge/pdf.py +0 -164
  468. agno/knowledge/pdf_bytes.py +0 -42
  469. agno/knowledge/pdf_url.py +0 -148
  470. agno/knowledge/s3/__init__.py +0 -0
  471. agno/knowledge/s3/base.py +0 -64
  472. agno/knowledge/s3/pdf.py +0 -33
  473. agno/knowledge/s3/text.py +0 -34
  474. agno/knowledge/text.py +0 -141
  475. agno/knowledge/url.py +0 -46
  476. agno/knowledge/website.py +0 -179
  477. agno/knowledge/wikipedia.py +0 -32
  478. agno/knowledge/youtube.py +0 -35
  479. agno/memory/agent.py +0 -423
  480. agno/memory/classifier.py +0 -104
  481. agno/memory/db/__init__.py +0 -5
  482. agno/memory/db/base.py +0 -42
  483. agno/memory/db/mongodb.py +0 -189
  484. agno/memory/db/postgres.py +0 -203
  485. agno/memory/db/sqlite.py +0 -193
  486. agno/memory/memory.py +0 -22
  487. agno/memory/row.py +0 -36
  488. agno/memory/summarizer.py +0 -201
  489. agno/memory/summary.py +0 -19
  490. agno/memory/team.py +0 -415
  491. agno/memory/v2/__init__.py +0 -2
  492. agno/memory/v2/db/__init__.py +0 -1
  493. agno/memory/v2/db/base.py +0 -42
  494. agno/memory/v2/db/firestore.py +0 -339
  495. agno/memory/v2/db/mongodb.py +0 -196
  496. agno/memory/v2/db/postgres.py +0 -214
  497. agno/memory/v2/db/redis.py +0 -187
  498. agno/memory/v2/db/schema.py +0 -54
  499. agno/memory/v2/db/sqlite.py +0 -209
  500. agno/memory/v2/manager.py +0 -437
  501. agno/memory/v2/memory.py +0 -1097
  502. agno/memory/v2/schema.py +0 -55
  503. agno/memory/v2/summarizer.py +0 -215
  504. agno/memory/workflow.py +0 -38
  505. agno/models/ollama/tools.py +0 -430
  506. agno/models/qwen/__init__.py +0 -5
  507. agno/playground/__init__.py +0 -10
  508. agno/playground/deploy.py +0 -3
  509. agno/playground/playground.py +0 -3
  510. agno/playground/serve.py +0 -3
  511. agno/playground/settings.py +0 -3
  512. agno/reranker/__init__.py +0 -0
  513. agno/run/v2/__init__.py +0 -0
  514. agno/run/v2/workflow.py +0 -567
  515. agno/storage/__init__.py +0 -0
  516. agno/storage/agent/__init__.py +0 -0
  517. agno/storage/agent/dynamodb.py +0 -1
  518. agno/storage/agent/json.py +0 -1
  519. agno/storage/agent/mongodb.py +0 -1
  520. agno/storage/agent/postgres.py +0 -1
  521. agno/storage/agent/singlestore.py +0 -1
  522. agno/storage/agent/sqlite.py +0 -1
  523. agno/storage/agent/yaml.py +0 -1
  524. agno/storage/base.py +0 -60
  525. agno/storage/dynamodb.py +0 -673
  526. agno/storage/firestore.py +0 -297
  527. agno/storage/gcs_json.py +0 -261
  528. agno/storage/in_memory.py +0 -234
  529. agno/storage/json.py +0 -237
  530. agno/storage/mongodb.py +0 -328
  531. agno/storage/mysql.py +0 -685
  532. agno/storage/postgres.py +0 -682
  533. agno/storage/redis.py +0 -336
  534. agno/storage/session/__init__.py +0 -16
  535. agno/storage/session/agent.py +0 -64
  536. agno/storage/session/team.py +0 -63
  537. agno/storage/session/v2/__init__.py +0 -5
  538. agno/storage/session/workflow.py +0 -61
  539. agno/storage/singlestore.py +0 -606
  540. agno/storage/sqlite.py +0 -646
  541. agno/storage/workflow/__init__.py +0 -0
  542. agno/storage/workflow/mongodb.py +0 -1
  543. agno/storage/workflow/postgres.py +0 -1
  544. agno/storage/workflow/sqlite.py +0 -1
  545. agno/storage/yaml.py +0 -241
  546. agno/tools/thinking.py +0 -73
  547. agno/utils/defaults.py +0 -57
  548. agno/utils/filesystem.py +0 -39
  549. agno/utils/git.py +0 -52
  550. agno/utils/json_io.py +0 -30
  551. agno/utils/load_env.py +0 -19
  552. agno/utils/py_io.py +0 -19
  553. agno/utils/pyproject.py +0 -18
  554. agno/utils/resource_filter.py +0 -31
  555. agno/workflow/v2/__init__.py +0 -21
  556. agno/workflow/v2/types.py +0 -357
  557. agno/workflow/v2/workflow.py +0 -3312
  558. agno/workspace/__init__.py +0 -0
  559. agno/workspace/config.py +0 -325
  560. agno/workspace/enums.py +0 -6
  561. agno/workspace/helpers.py +0 -52
  562. agno/workspace/operator.py +0 -757
  563. agno/workspace/settings.py +0 -158
  564. agno-1.8.1.dist-info/METADATA +0 -982
  565. agno-1.8.1.dist-info/RECORD +0 -566
  566. agno-1.8.1.dist-info/entry_points.txt +0 -3
  567. /agno/{app → db/migrations}/__init__.py +0 -0
  568. /agno/{app/playground/__init__.py → db/schemas/metrics.py} +0 -0
  569. /agno/{cli → integrations}/__init__.py +0 -0
  570. /agno/{cli/ws → knowledge/chunking}/__init__.py +0 -0
  571. /agno/{document/chunking → knowledge/remote_content}/__init__.py +0 -0
  572. /agno/{document/reader/gcs → knowledge/reranker}/__init__.py +0 -0
  573. /agno/{document/reader/s3 → os/interfaces}/__init__.py +0 -0
  574. /agno/{app → os/interfaces}/slack/security.py +0 -0
  575. /agno/{app → os/interfaces}/whatsapp/security.py +0 -0
  576. /agno/{file/local → utils/print_response}/__init__.py +0 -0
  577. /agno/{infra → vectordb/llamaindex}/__init__.py +0 -0
  578. {agno-1.8.1.dist-info → agno-2.0.0a1.dist-info}/WHEEL +0 -0
  579. {agno-1.8.1.dist-info → agno-2.0.0a1.dist-info}/licenses/LICENSE +0 -0
  580. {agno-1.8.1.dist-info → agno-2.0.0a1.dist-info}/top_level.txt +0 -0
agno/db/mongo/mongo.py ADDED
@@ -0,0 +1,1417 @@
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 BaseDb, 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,
13
+ fetch_all_sessions_data,
14
+ get_dates_to_calculate_metrics_for,
15
+ )
16
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
17
+ from agno.db.schemas.knowledge import KnowledgeRow
18
+ from agno.db.schemas.memory import UserMemory
19
+ from agno.db.utils import deserialize_session_json_fields, serialize_session_json_fields
20
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
21
+ from agno.utils.log import log_debug, log_error, log_info
22
+
23
+ try:
24
+ from pymongo import MongoClient, ReturnDocument
25
+ from pymongo.collection import Collection
26
+ from pymongo.database import Database
27
+ from pymongo.errors import OperationFailure
28
+ except ImportError:
29
+ raise ImportError("`pymongo` not installed. Please install it using `pip install pymongo`")
30
+
31
+
32
+ class MongoDb(BaseDb):
33
+ def __init__(
34
+ self,
35
+ db_client: Optional[MongoClient] = None,
36
+ db_name: Optional[str] = None,
37
+ db_url: Optional[str] = None,
38
+ session_collection: Optional[str] = None,
39
+ memory_collection: Optional[str] = None,
40
+ metrics_collection: Optional[str] = None,
41
+ eval_collection: Optional[str] = None,
42
+ knowledge_collection: Optional[str] = None,
43
+ ):
44
+ """
45
+ Interface for interacting with a MongoDB database.
46
+
47
+ Args:
48
+ db_client (Optional[MongoClient]): The MongoDB client to use.
49
+ db_name (Optional[str]): The name of the database to use.
50
+ db_url (Optional[str]): The database URL to connect to.
51
+ session_collection (Optional[str]): Name of the collection to store sessions.
52
+ memory_collection (Optional[str]): Name of the collection to store memories.
53
+ metrics_collection (Optional[str]): Name of the collection to store metrics.
54
+ eval_collection (Optional[str]): Name of the collection to store evaluation runs.
55
+ knowledge_collection (Optional[str]): Name of the collection to store knowledge documents.
56
+
57
+ Raises:
58
+ ValueError: If neither db_url nor db_client is provided.
59
+ """
60
+ super().__init__(
61
+ session_table=session_collection,
62
+ memory_table=memory_collection,
63
+ metrics_table=metrics_collection,
64
+ eval_table=eval_collection,
65
+ knowledge_table=knowledge_collection,
66
+ )
67
+
68
+ _client: Optional[MongoClient] = db_client
69
+ if _client is None and db_url is not None:
70
+ _client = MongoClient(db_url)
71
+ if _client is None:
72
+ raise ValueError("One of db_url or db_client must be provided")
73
+
74
+ self.db_url: Optional[str] = db_url
75
+ self.db_client: MongoClient = _client
76
+ self.db_name: str = db_name if db_name is not None else "agno"
77
+
78
+ self._database: Optional[Database] = None
79
+
80
+ @property
81
+ def database(self) -> Database:
82
+ if self._database is None:
83
+ self._database = self.db_client[self.db_name]
84
+ return self._database
85
+
86
+ # -- DB methods --
87
+
88
+ def _get_collection(
89
+ self, table_type: str, create_collection_if_not_found: Optional[bool] = True
90
+ ) -> Optional[Collection]:
91
+ """Get or create a collection based on table type.
92
+
93
+ Args:
94
+ table_type (str): The type of table to get or create.
95
+
96
+ Returns:
97
+ Collection: The collection object.
98
+ """
99
+ if table_type == "sessions":
100
+ if not hasattr(self, "session_collection"):
101
+ if self.session_table_name is None:
102
+ raise ValueError("Session collection was not provided on initialization")
103
+ self.session_collection = self._get_or_create_collection(
104
+ collection_name=self.session_table_name,
105
+ collection_type="sessions",
106
+ create_collection_if_not_found=create_collection_if_not_found,
107
+ )
108
+ return self.session_collection
109
+
110
+ if table_type == "memories":
111
+ if not hasattr(self, "memory_collection"):
112
+ if self.memory_table_name is None:
113
+ raise ValueError("Memory collection was not provided on initialization")
114
+ self.memory_collection = self._get_or_create_collection(
115
+ collection_name=self.memory_table_name,
116
+ collection_type="memories",
117
+ create_collection_if_not_found=create_collection_if_not_found,
118
+ )
119
+ return self.memory_collection
120
+
121
+ if table_type == "metrics":
122
+ if not hasattr(self, "metrics_collection"):
123
+ if self.metrics_table_name is None:
124
+ raise ValueError("Metrics collection was not provided on initialization")
125
+ self.metrics_collection = self._get_or_create_collection(
126
+ collection_name=self.metrics_table_name,
127
+ collection_type="metrics",
128
+ create_collection_if_not_found=create_collection_if_not_found,
129
+ )
130
+ return self.metrics_collection
131
+
132
+ if table_type == "evals":
133
+ if not hasattr(self, "eval_collection"):
134
+ if self.eval_table_name is None:
135
+ raise ValueError("Eval collection was not provided on initialization")
136
+ self.eval_collection = self._get_or_create_collection(
137
+ collection_name=self.eval_table_name,
138
+ collection_type="evals",
139
+ create_collection_if_not_found=create_collection_if_not_found,
140
+ )
141
+ return self.eval_collection
142
+
143
+ if table_type == "knowledge":
144
+ if not hasattr(self, "knowledge_collection"):
145
+ if self.knowledge_table_name is None:
146
+ raise ValueError("Knowledge collection was not provided on initialization")
147
+ self.knowledge_collection = self._get_or_create_collection(
148
+ collection_name=self.knowledge_table_name,
149
+ collection_type="knowledge",
150
+ create_collection_if_not_found=create_collection_if_not_found,
151
+ )
152
+ return self.knowledge_collection
153
+
154
+ raise ValueError(f"Unknown table type: {table_type}")
155
+
156
+ def _get_or_create_collection(
157
+ self, collection_name: str, collection_type: str, create_collection_if_not_found: Optional[bool] = True
158
+ ) -> Optional[Collection]:
159
+ """Get or create a collection with proper indexes.
160
+
161
+ Args:
162
+ collection_name (str): The name of the collection to get or create.
163
+ collection_type (str): The type of collection to get or create.
164
+ create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
165
+
166
+ Returns:
167
+ Optional[Collection]: The collection object.
168
+ """
169
+ try:
170
+ collection = self.database[collection_name]
171
+
172
+ if not hasattr(self, f"_{collection_name}_initialized"):
173
+ if not create_collection_if_not_found:
174
+ return None
175
+ create_collection_indexes(collection, collection_type)
176
+ setattr(self, f"_{collection_name}_initialized", True)
177
+ log_debug(f"Initialized collection '{collection_name}'")
178
+ else:
179
+ log_debug(f"Collection '{collection_name}' already initialized")
180
+
181
+ return collection
182
+
183
+ except Exception as e:
184
+ log_error(f"Error getting collection {collection_name}: {e}")
185
+ raise
186
+
187
+ # -- Session methods --
188
+
189
+ def delete_session(self, session_id: str) -> bool:
190
+ """Delete a session from the database.
191
+
192
+ Args:
193
+ session_id (str): The ID of the session to delete.
194
+
195
+ Returns:
196
+ bool: True if the session was deleted, False otherwise.
197
+
198
+ Raises:
199
+ Exception: If there is an error deleting the session.
200
+ """
201
+ try:
202
+ collection = self._get_collection(table_type="sessions")
203
+ if collection is None:
204
+ return False
205
+
206
+ result = collection.delete_one({"session_id": session_id})
207
+ if result.deleted_count == 0:
208
+ log_debug(f"No session found to delete with session_id: {session_id}")
209
+ return False
210
+ else:
211
+ log_debug(f"Successfully deleted session with session_id: {session_id}")
212
+ return True
213
+
214
+ except Exception as e:
215
+ log_error(f"Error deleting session: {e}")
216
+ return False
217
+
218
+ def delete_sessions(self, session_ids: List[str]) -> None:
219
+ """Delete multiple sessions from the database.
220
+
221
+ Args:
222
+ session_ids (List[str]): The IDs of the sessions to delete.
223
+ """
224
+ try:
225
+ collection = self._get_collection(table_type="sessions")
226
+ if collection is None:
227
+ return
228
+
229
+ result = collection.delete_many({"session_id": {"$in": session_ids}})
230
+ log_debug(f"Successfully deleted {result.deleted_count} sessions")
231
+
232
+ except Exception as e:
233
+ log_error(f"Error deleting sessions: {e}")
234
+
235
+ def get_session(
236
+ self,
237
+ session_id: str,
238
+ session_type: SessionType,
239
+ user_id: Optional[str] = None,
240
+ deserialize: Optional[bool] = True,
241
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
242
+ """Read a session from the database.
243
+
244
+ Args:
245
+ session_id (str): The ID of the session to get.
246
+ user_id (Optional[str]): The ID of the user to get the session for.
247
+ session_type (Optional[SessionType]): The type of session to get.
248
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
249
+
250
+ Returns:
251
+ Union[Session, Dict[str, Any], None]:
252
+ - When deserialize=True: Session object
253
+ - When deserialize=False: Session dictionary
254
+
255
+ Raises:
256
+ Exception: If there is an error reading the session.
257
+ """
258
+ try:
259
+ collection = self._get_collection(table_type="sessions")
260
+ if collection is None:
261
+ return None
262
+
263
+ query = {"session_id": session_id}
264
+ if user_id is not None:
265
+ query["user_id"] = user_id
266
+ if session_type is not None:
267
+ query["session_type"] = session_type
268
+
269
+ result = collection.find_one(query)
270
+ if result is None:
271
+ return None
272
+
273
+ session = deserialize_session_json_fields(result)
274
+
275
+ if not deserialize:
276
+ return session
277
+
278
+ if session_type == SessionType.AGENT.value:
279
+ return AgentSession.from_dict(session)
280
+ elif session_type == SessionType.TEAM.value:
281
+ return TeamSession.from_dict(session)
282
+ else:
283
+ return WorkflowSession.from_dict(session)
284
+
285
+ except Exception as e:
286
+ log_error(f"Exception reading session: {e}")
287
+ return None
288
+
289
+ def get_sessions(
290
+ self,
291
+ session_type: Optional[SessionType] = None,
292
+ user_id: Optional[str] = None,
293
+ component_id: Optional[str] = None,
294
+ session_name: Optional[str] = None,
295
+ start_timestamp: Optional[int] = None,
296
+ end_timestamp: Optional[int] = None,
297
+ limit: Optional[int] = None,
298
+ page: Optional[int] = None,
299
+ sort_by: Optional[str] = None,
300
+ sort_order: Optional[str] = None,
301
+ deserialize: Optional[bool] = True,
302
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
303
+ """Get all sessions.
304
+
305
+ Args:
306
+ session_type (Optional[SessionType]): The type of session to get.
307
+ user_id (Optional[str]): The ID of the user to get the session for.
308
+ component_id (Optional[str]): The ID of the component to get the session for.
309
+ session_name (Optional[str]): The name of the session to filter by.
310
+ start_timestamp (Optional[int]): The start timestamp to filter sessions by.
311
+ end_timestamp (Optional[int]): The end timestamp to filter sessions by.
312
+ limit (Optional[int]): The limit of the sessions to get.
313
+ page (Optional[int]): The page number to get.
314
+ sort_by (Optional[str]): The field to sort the sessions by.
315
+ sort_order (Optional[str]): The order to sort the sessions by.
316
+ deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True.
317
+ create_table_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
318
+
319
+ Returns:
320
+ Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]:
321
+ - When deserialize=True: List of Session objects
322
+ - When deserialize=False: List of session dictionaries and the total count
323
+
324
+ Raises:
325
+ Exception: If there is an error reading the sessions.
326
+ """
327
+ try:
328
+ collection = self._get_collection(table_type="sessions")
329
+ if collection is None:
330
+ return [] if deserialize else ([], 0)
331
+
332
+ # Filtering
333
+ query: Dict[str, Any] = {}
334
+ if user_id is not None:
335
+ query["user_id"] = user_id
336
+ if session_type is not None:
337
+ query["session_type"] = session_type
338
+ if component_id is not None:
339
+ if session_type == SessionType.AGENT:
340
+ query["agent_id"] = component_id
341
+ elif session_type == SessionType.TEAM:
342
+ query["team_id"] = component_id
343
+ elif session_type == SessionType.WORKFLOW:
344
+ query["workflow_id"] = component_id
345
+ if start_timestamp is not None:
346
+ query["created_at"] = {"$gte": start_timestamp}
347
+ if end_timestamp is not None:
348
+ if "created_at" in query:
349
+ query["created_at"]["$lte"] = end_timestamp
350
+ else:
351
+ query["created_at"] = {"$lte": end_timestamp}
352
+ if session_name is not None:
353
+ query["session_data.session_name"] = {"$regex": session_name, "$options": "i"}
354
+
355
+ # Get total count
356
+ total_count = collection.count_documents(query)
357
+
358
+ cursor = collection.find(query)
359
+
360
+ # Sorting
361
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
362
+ if sort_criteria:
363
+ cursor = cursor.sort(sort_criteria)
364
+
365
+ # Pagination
366
+ query_args = apply_pagination({}, limit, page)
367
+ if query_args.get("skip"):
368
+ cursor = cursor.skip(query_args["skip"])
369
+ if query_args.get("limit"):
370
+ cursor = cursor.limit(query_args["limit"])
371
+
372
+ records = list(cursor)
373
+ if records is None:
374
+ return [] if deserialize else ([], 0)
375
+
376
+ sessions_raw = [deserialize_session_json_fields(record) for record in records]
377
+
378
+ if not deserialize:
379
+ return sessions_raw, total_count
380
+
381
+ sessions: List[Union[AgentSession, TeamSession, WorkflowSession]] = []
382
+ for record in sessions_raw:
383
+ if session_type == SessionType.AGENT.value:
384
+ agent_session = AgentSession.from_dict(record)
385
+ if agent_session is not None:
386
+ sessions.append(agent_session)
387
+ elif session_type == SessionType.TEAM.value:
388
+ team_session = TeamSession.from_dict(record)
389
+ if team_session is not None:
390
+ sessions.append(team_session)
391
+ elif session_type == SessionType.WORKFLOW.value:
392
+ workflow_session = WorkflowSession.from_dict(record)
393
+ if workflow_session is not None:
394
+ sessions.append(workflow_session)
395
+
396
+ return sessions
397
+
398
+ except Exception as e:
399
+ log_error(f"Exception reading sessions: {e}")
400
+ return [] if deserialize else ([], 0)
401
+
402
+ def rename_session(
403
+ self, session_id: str, session_type: SessionType, session_name: str, deserialize: Optional[bool] = True
404
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
405
+ """Rename a session in the database.
406
+
407
+ Args:
408
+ session_id (str): The ID of the session to rename.
409
+ session_type (SessionType): The type of session to rename.
410
+ session_name (str): The new name of the session.
411
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
412
+
413
+ Returns:
414
+ Optional[Union[Session, Dict[str, Any]]]:
415
+ - When deserialize=True: Session object
416
+ - When deserialize=False: Session dictionary
417
+
418
+ Raises:
419
+ Exception: If there is an error renaming the session.
420
+ """
421
+ try:
422
+ collection = self._get_collection(table_type="sessions")
423
+ if collection is None:
424
+ return None
425
+
426
+ try:
427
+ result = collection.find_one_and_update(
428
+ {"session_id": session_id},
429
+ {"$set": {"session_data.session_name": session_name, "updated_at": int(time.time())}},
430
+ return_document=ReturnDocument.AFTER,
431
+ upsert=False,
432
+ )
433
+ except OperationFailure:
434
+ # If the update fails because session_data doesn't contain a session_name yet, we initialize session_data
435
+ result = collection.find_one_and_update(
436
+ {"session_id": session_id},
437
+ {"$set": {"session_data": {"session_name": session_name}, "updated_at": int(time.time())}},
438
+ return_document=ReturnDocument.AFTER,
439
+ upsert=False,
440
+ )
441
+ if not result:
442
+ return None
443
+
444
+ deserialized_session = deserialize_session_json_fields(result)
445
+
446
+ if not deserialize:
447
+ return deserialized_session
448
+
449
+ if session_type == SessionType.AGENT.value:
450
+ return AgentSession.from_dict(deserialized_session)
451
+ elif session_type == SessionType.TEAM.value:
452
+ return TeamSession.from_dict(deserialized_session)
453
+ else:
454
+ return WorkflowSession.from_dict(deserialized_session)
455
+
456
+ except Exception as e:
457
+ log_error(f"Exception renaming session: {e}")
458
+ return None
459
+
460
+ def upsert_session(
461
+ self, session: Session, deserialize: Optional[bool] = True
462
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
463
+ """Insert or update a session in the database.
464
+
465
+ Args:
466
+ session (Session): The session to upsert.
467
+
468
+ Returns:
469
+ Optional[Session]: The upserted session.
470
+
471
+ Raises:
472
+ Exception: If there is an error upserting the session.
473
+ """
474
+ try:
475
+ collection = self._get_collection(table_type="sessions", create_collection_if_not_found=True)
476
+ if collection is None:
477
+ return None
478
+
479
+ serialized_session_dict = serialize_session_json_fields(session.to_dict())
480
+
481
+ if isinstance(session, AgentSession):
482
+ record = {
483
+ "session_id": serialized_session_dict.get("session_id"),
484
+ "session_type": SessionType.AGENT.value,
485
+ "agent_id": serialized_session_dict.get("agent_id"),
486
+ "user_id": serialized_session_dict.get("user_id"),
487
+ "runs": serialized_session_dict.get("runs"),
488
+ "agent_data": serialized_session_dict.get("agent_data"),
489
+ "session_data": serialized_session_dict.get("session_data"),
490
+ "summary": serialized_session_dict.get("summary"),
491
+ "metadata": serialized_session_dict.get("metadata"),
492
+ "created_at": serialized_session_dict.get("created_at"),
493
+ "updated_at": int(time.time()),
494
+ }
495
+
496
+ result = collection.find_one_and_replace(
497
+ filter={"session_id": serialized_session_dict.get("session_id")},
498
+ replacement=record,
499
+ upsert=True,
500
+ return_document=ReturnDocument.AFTER,
501
+ )
502
+ if not result:
503
+ return None
504
+
505
+ session = deserialize_session_json_fields(result) # type: ignore
506
+
507
+ log_debug("Upserted session'")
508
+
509
+ if not deserialize:
510
+ return session
511
+
512
+ return AgentSession.from_dict(session) # type: ignore
513
+
514
+ elif isinstance(session, TeamSession):
515
+ record = {
516
+ "session_id": serialized_session_dict.get("session_id"),
517
+ "session_type": SessionType.TEAM.value,
518
+ "team_id": serialized_session_dict.get("team_id"),
519
+ "user_id": serialized_session_dict.get("user_id"),
520
+ "runs": serialized_session_dict.get("runs"),
521
+ "team_data": serialized_session_dict.get("team_data"),
522
+ "session_data": serialized_session_dict.get("session_data"),
523
+ "summary": serialized_session_dict.get("summary"),
524
+ "metadata": serialized_session_dict.get("metadata"),
525
+ "created_at": serialized_session_dict.get("created_at"),
526
+ "updated_at": int(time.time()),
527
+ }
528
+
529
+ result = collection.find_one_and_replace(
530
+ filter={"session_id": serialized_session_dict.get("session_id")},
531
+ replacement=record,
532
+ upsert=True,
533
+ return_document=ReturnDocument.AFTER,
534
+ )
535
+ if not result:
536
+ return None
537
+
538
+ session = deserialize_session_json_fields(result) # type: ignore
539
+
540
+ log_debug(f"Upserted session with id '{session.session_id}'")
541
+
542
+ if not deserialize:
543
+ return session
544
+
545
+ return TeamSession.from_dict(session) # type: ignore
546
+
547
+ else:
548
+ record = {
549
+ "session_id": serialized_session_dict.get("session_id"),
550
+ "session_type": SessionType.WORKFLOW.value,
551
+ "workflow_id": serialized_session_dict.get("workflow_id"),
552
+ "user_id": serialized_session_dict.get("user_id"),
553
+ "runs": serialized_session_dict.get("runs"),
554
+ "workflow_data": serialized_session_dict.get("workflow_data"),
555
+ "session_data": serialized_session_dict.get("session_data"),
556
+ "summary": serialized_session_dict.get("summary"),
557
+ "metadata": serialized_session_dict.get("metadata"),
558
+ "created_at": serialized_session_dict.get("created_at"),
559
+ "updated_at": int(time.time()),
560
+ }
561
+
562
+ result = collection.find_one_and_replace(
563
+ filter={"session_id": serialized_session_dict.get("session_id")},
564
+ replacement=record,
565
+ upsert=True,
566
+ return_document=ReturnDocument.AFTER,
567
+ )
568
+ if not result:
569
+ return None
570
+
571
+ session = deserialize_session_json_fields(result) # type: ignore
572
+
573
+ log_debug(f"Upserted session with id '{session.session_id}'")
574
+
575
+ if not deserialize:
576
+ return session
577
+
578
+ return WorkflowSession.from_dict(session) # type: ignore
579
+
580
+ except Exception as e:
581
+ log_error(f"Exception upserting session: {e}")
582
+ return None
583
+
584
+ # -- Memory methods --
585
+
586
+ def delete_user_memory(self, memory_id: str):
587
+ """Delete a user memory from the database.
588
+
589
+ Args:
590
+ memory_id (str): The ID of the memory to delete.
591
+
592
+ Returns:
593
+ bool: True if the memory was deleted, False otherwise.
594
+
595
+ Raises:
596
+ Exception: If there is an error deleting the memory.
597
+ """
598
+ try:
599
+ collection = self._get_collection(table_type="memories")
600
+ if collection is None:
601
+ return
602
+
603
+ result = collection.delete_one({"memory_id": memory_id})
604
+
605
+ success = result.deleted_count > 0
606
+ if success:
607
+ log_debug(f"Successfully deleted memory id: {memory_id}")
608
+ else:
609
+ log_debug(f"No memory found with id: {memory_id}")
610
+
611
+ except Exception as e:
612
+ log_error(f"Error deleting memory: {e}")
613
+
614
+ def delete_user_memories(self, memory_ids: List[str]) -> None:
615
+ """Delete user memories from the database.
616
+
617
+ Args:
618
+ memory_ids (List[str]): The IDs of the memories to delete.
619
+
620
+ Raises:
621
+ Exception: If there is an error deleting the memories.
622
+ """
623
+ try:
624
+ collection = self._get_collection(table_type="memories")
625
+ if collection is None:
626
+ return
627
+
628
+ result = collection.delete_many({"memory_id": {"$in": memory_ids}})
629
+
630
+ if result.deleted_count == 0:
631
+ log_debug(f"No memories found with ids: {memory_ids}")
632
+
633
+ except Exception as e:
634
+ log_error(f"Error deleting memories: {e}")
635
+
636
+ def get_all_memory_topics(self) -> List[str]:
637
+ """Get all memory topics from the database.
638
+
639
+ Returns:
640
+ List[str]: The topics.
641
+
642
+ Raises:
643
+ Exception: If there is an error getting the topics.
644
+ """
645
+ try:
646
+ collection = self._get_collection(table_type="memories")
647
+ if collection is None:
648
+ return []
649
+
650
+ topics = collection.distinct("topics")
651
+ return [topic for topic in topics if topic]
652
+
653
+ except Exception as e:
654
+ log_error(f"Exception reading from collection: {e}")
655
+ return []
656
+
657
+ def get_user_memory(self, memory_id: str, deserialize: Optional[bool] = True) -> Optional[UserMemory]:
658
+ """Get a memory from the database.
659
+
660
+ Args:
661
+ memory_id (str): The ID of the memory to get.
662
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
663
+
664
+ Returns:
665
+ Optional[UserMemory]:
666
+ - When deserialize=True: UserMemory object
667
+ - When deserialize=False: Memory dictionary
668
+
669
+ Raises:
670
+ Exception: If there is an error getting the memory.
671
+ """
672
+ try:
673
+ collection = self._get_collection(table_type="memories")
674
+ if collection is None:
675
+ return None
676
+
677
+ result = collection.find_one({"memory_id": memory_id})
678
+ if result is None or not deserialize:
679
+ return result
680
+
681
+ return UserMemory.from_dict(result)
682
+
683
+ except Exception as e:
684
+ log_error(f"Exception reading from collection: {e}")
685
+ return None
686
+
687
+ def get_user_memories(
688
+ self,
689
+ user_id: Optional[str] = None,
690
+ agent_id: Optional[str] = None,
691
+ team_id: Optional[str] = None,
692
+ topics: Optional[List[str]] = None,
693
+ search_content: Optional[str] = None,
694
+ limit: Optional[int] = None,
695
+ page: Optional[int] = None,
696
+ sort_by: Optional[str] = None,
697
+ sort_order: Optional[str] = None,
698
+ deserialize: Optional[bool] = True,
699
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
700
+ """Get all memories from the database as UserMemory objects.
701
+
702
+ Args:
703
+ user_id (Optional[str]): The ID of the user to get the memories for.
704
+ agent_id (Optional[str]): The ID of the agent to get the memories for.
705
+ team_id (Optional[str]): The ID of the team to get the memories for.
706
+ topics (Optional[List[str]]): The topics to filter the memories by.
707
+ search_content (Optional[str]): The content to filter the memories by.
708
+ limit (Optional[int]): The limit of the memories to get.
709
+ page (Optional[int]): The page number to get.
710
+ sort_by (Optional[str]): The field to sort the memories by.
711
+ sort_order (Optional[str]): The order to sort the memories by.
712
+ deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True.
713
+ create_table_if_not_found: Whether to create the collection if it doesn't exist.
714
+
715
+ Returns:
716
+ Tuple[List[Dict[str, Any]], int]: A tuple containing the memories and the total count.
717
+
718
+ Raises:
719
+ Exception: If there is an error getting the memories.
720
+ """
721
+ try:
722
+ collection = self._get_collection(table_type="memories")
723
+ if collection is None:
724
+ return [] if deserialize else ([], 0)
725
+
726
+ query: Dict[str, Any] = {}
727
+ if user_id is not None:
728
+ query["user_id"] = user_id
729
+ if agent_id is not None:
730
+ query["agent_id"] = agent_id
731
+ if team_id is not None:
732
+ query["team_id"] = team_id
733
+ if topics is not None:
734
+ query["topics"] = {"$in": topics}
735
+ if search_content is not None:
736
+ query["memory"] = {"$regex": search_content, "$options": "i"}
737
+
738
+ # Get total count
739
+ total_count = collection.count_documents(query)
740
+
741
+ # Apply sorting
742
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
743
+
744
+ # Apply pagination
745
+ query_args = apply_pagination({}, limit, page)
746
+
747
+ cursor = collection.find(query)
748
+ if sort_criteria:
749
+ cursor = cursor.sort(sort_criteria)
750
+ if query_args.get("skip"):
751
+ cursor = cursor.skip(query_args["skip"])
752
+ if query_args.get("limit"):
753
+ cursor = cursor.limit(query_args["limit"])
754
+
755
+ records = list(cursor)
756
+ if not deserialize:
757
+ return records, total_count
758
+
759
+ return [UserMemory.from_dict(record) for record in records]
760
+
761
+ except Exception as e:
762
+ log_error(f"Exception reading from collection: {e}")
763
+ return []
764
+
765
+ def get_user_memory_stats(
766
+ self,
767
+ limit: Optional[int] = None,
768
+ page: Optional[int] = None,
769
+ ) -> Tuple[List[Dict[str, Any]], int]:
770
+ """Get user memories stats.
771
+
772
+ Args:
773
+ limit (Optional[int]): The limit of the memories to get.
774
+ page (Optional[int]): The page number to get.
775
+
776
+ Returns:
777
+ Tuple[List[Dict[str, Any]], int]: A tuple containing the memories stats and the total count.
778
+
779
+ Raises:
780
+ Exception: If there is an error getting the memories stats.
781
+ """
782
+ try:
783
+ collection = self._get_collection(table_type="memories")
784
+ if collection is None:
785
+ return [], 0
786
+
787
+ pipeline = [
788
+ {"$match": {"user_id": {"$ne": None}}},
789
+ {
790
+ "$group": {
791
+ "_id": "$user_id",
792
+ "total_memories": {"$sum": 1},
793
+ "last_memory_updated_at": {"$max": "$updated_at"},
794
+ }
795
+ },
796
+ {"$sort": {"last_memory_updated_at": -1}},
797
+ ]
798
+
799
+ # Get total count
800
+ count_pipeline = pipeline + [{"$count": "total"}]
801
+ count_result = list(collection.aggregate(count_pipeline)) # type: ignore
802
+ total_count = count_result[0]["total"] if count_result else 0
803
+
804
+ # Apply pagination
805
+ if limit is not None:
806
+ if page is not None:
807
+ pipeline.append({"$skip": (page - 1) * limit})
808
+ pipeline.append({"$limit": limit})
809
+
810
+ results = list(collection.aggregate(pipeline)) # type: ignore
811
+
812
+ formatted_results = [
813
+ {
814
+ "user_id": result["_id"],
815
+ "total_memories": result["total_memories"],
816
+ "last_memory_updated_at": result["last_memory_updated_at"],
817
+ }
818
+ for result in results
819
+ ]
820
+
821
+ return formatted_results, total_count
822
+
823
+ except Exception as e:
824
+ log_error(f"Exception getting user memory stats: {e}")
825
+ return [], 0
826
+
827
+ def upsert_user_memory(
828
+ self, memory: UserMemory, deserialize: Optional[bool] = True
829
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
830
+ """Upsert a user memory in the database.
831
+
832
+ Args:
833
+ memory (UserMemory): The memory to upsert.
834
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
835
+
836
+ Returns:
837
+ Optional[Union[UserMemory, Dict[str, Any]]]:
838
+ - When deserialize=True: UserMemory object
839
+ - When deserialize=False: Memory dictionary
840
+
841
+ Raises:
842
+ Exception: If there is an error upserting the memory.
843
+ """
844
+ try:
845
+ collection = self._get_collection(table_type="memories", create_collection_if_not_found=True)
846
+ if collection is None:
847
+ return None
848
+
849
+ if memory.memory_id is None:
850
+ memory.memory_id = str(uuid4())
851
+
852
+ update_doc = {
853
+ "user_id": memory.user_id,
854
+ "agent_id": memory.agent_id,
855
+ "team_id": memory.team_id,
856
+ "memory_id": memory.memory_id,
857
+ "memory": memory.memory,
858
+ "topics": memory.topics,
859
+ "updated_at": int(time.time()),
860
+ }
861
+
862
+ result = collection.replace_one({"memory_id": memory.memory_id}, update_doc, upsert=True)
863
+
864
+ if result.upserted_id:
865
+ update_doc["_id"] = result.upserted_id
866
+
867
+ if not deserialize:
868
+ return update_doc
869
+
870
+ return UserMemory.from_dict(update_doc)
871
+
872
+ except Exception as e:
873
+ log_error(f"Exception upserting user memory: {e}")
874
+ return None
875
+
876
+ def clear_memories(self) -> None:
877
+ """Delete all memories from the database.
878
+
879
+ Raises:
880
+ Exception: If an error occurs during deletion.
881
+ """
882
+ try:
883
+ collection = self._get_collection(table_type="memories")
884
+ if collection is None:
885
+ return
886
+
887
+ collection.delete_many({})
888
+
889
+ except Exception as e:
890
+ from agno.utils.log import log_warning
891
+
892
+ log_warning(f"Exception deleting all memories: {e}")
893
+
894
+ # -- Metrics methods --
895
+
896
+ def _get_all_sessions_for_metrics_calculation(
897
+ self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
898
+ ) -> List[Dict[str, Any]]:
899
+ """Get all sessions of all types for metrics calculation."""
900
+ try:
901
+ collection = self._get_collection(table_type="sessions")
902
+ if collection is None:
903
+ return []
904
+
905
+ query = {}
906
+ if start_timestamp is not None:
907
+ query["created_at"] = {"$gte": start_timestamp}
908
+ if end_timestamp is not None:
909
+ if "created_at" in query:
910
+ query["created_at"]["$lte"] = end_timestamp
911
+ else:
912
+ query["created_at"] = {"$lte": end_timestamp}
913
+
914
+ projection = {
915
+ "user_id": 1,
916
+ "session_data": 1,
917
+ "runs": 1,
918
+ "created_at": 1,
919
+ "session_type": 1,
920
+ }
921
+
922
+ results = list(collection.find(query, projection))
923
+ return results
924
+
925
+ except Exception as e:
926
+ log_error(f"Exception reading from sessions collection: {e}")
927
+ return []
928
+
929
+ def _get_metrics_calculation_starting_date(self, collection: Collection) -> Optional[date]:
930
+ """Get the first date for which metrics calculation is needed."""
931
+ try:
932
+ result = collection.find_one({}, sort=[("date", -1)], limit=1)
933
+
934
+ if result is not None:
935
+ result_date = datetime.strptime(result["date"], "%Y-%m-%d").date()
936
+ if result.get("completed"):
937
+ return result_date + timedelta(days=1)
938
+ else:
939
+ return result_date
940
+
941
+ # No metrics records. Return the date of the first recorded session.
942
+ first_session_result = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False)
943
+ first_session_date = first_session_result[0][0]["created_at"] if first_session_result[0] else None # type: ignore
944
+
945
+ if first_session_date is None:
946
+ return None
947
+
948
+ return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date()
949
+
950
+ except Exception as e:
951
+ log_error(f"Exception getting metrics calculation starting date: {e}")
952
+ return None
953
+
954
+ def calculate_metrics(self) -> Optional[list[dict]]:
955
+ """Calculate metrics for all dates without complete metrics."""
956
+ try:
957
+ collection = self._get_collection(table_type="metrics", create_collection_if_not_found=True)
958
+ if collection is None:
959
+ return None
960
+
961
+ starting_date = self._get_metrics_calculation_starting_date(collection)
962
+ if starting_date is None:
963
+ log_info("No session data found. Won't calculate metrics.")
964
+ return None
965
+
966
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
967
+ if not dates_to_process:
968
+ log_info("Metrics already calculated for all relevant dates.")
969
+ return None
970
+
971
+ start_timestamp = int(
972
+ datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp()
973
+ )
974
+ end_timestamp = int(
975
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time())
976
+ .replace(tzinfo=timezone.utc)
977
+ .timestamp()
978
+ )
979
+
980
+ sessions = self._get_all_sessions_for_metrics_calculation(
981
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
982
+ )
983
+ all_sessions_data = fetch_all_sessions_data(
984
+ sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp
985
+ )
986
+ if not all_sessions_data:
987
+ log_info("No new session data found. Won't calculate metrics.")
988
+ return None
989
+
990
+ results = []
991
+ metrics_records = []
992
+
993
+ for date_to_process in dates_to_process:
994
+ date_key = date_to_process.isoformat()
995
+ sessions_for_date = all_sessions_data.get(date_key, {})
996
+
997
+ # Skip dates with no sessions
998
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
999
+ continue
1000
+
1001
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
1002
+ metrics_records.append(metrics_record)
1003
+
1004
+ if metrics_records:
1005
+ results = bulk_upsert_metrics(collection, metrics_records)
1006
+
1007
+ return results
1008
+
1009
+ except Exception as e:
1010
+ log_error(f"Error calculating metrics: {e}")
1011
+ raise e
1012
+
1013
+ def get_metrics(
1014
+ self,
1015
+ starting_date: Optional[date] = None,
1016
+ ending_date: Optional[date] = None,
1017
+ ) -> Tuple[List[dict], Optional[int]]:
1018
+ """Get all metrics matching the given date range."""
1019
+ try:
1020
+ collection = self._get_collection(table_type="metrics")
1021
+ if collection is None:
1022
+ return [], None
1023
+
1024
+ query = {}
1025
+ if starting_date:
1026
+ query["date"] = {"$gte": starting_date.isoformat()}
1027
+ if ending_date:
1028
+ if "date" in query:
1029
+ query["date"]["$lte"] = ending_date.isoformat()
1030
+ else:
1031
+ query["date"] = {"$lte": ending_date.isoformat()}
1032
+
1033
+ records = list(collection.find(query))
1034
+ if not records:
1035
+ return [], None
1036
+
1037
+ # Get the latest updated_at
1038
+ latest_updated_at = max(record.get("updated_at", 0) for record in records)
1039
+
1040
+ return records, latest_updated_at
1041
+
1042
+ except Exception as e:
1043
+ log_error(f"Error getting metrics: {e}")
1044
+ return [], None
1045
+
1046
+ # -- Knowledge methods --
1047
+
1048
+ def delete_knowledge_content(self, id: str):
1049
+ """Delete a knowledge row from the database.
1050
+
1051
+ Args:
1052
+ id (str): The ID of the knowledge row to delete.
1053
+
1054
+ Raises:
1055
+ Exception: If an error occurs during deletion.
1056
+ """
1057
+ try:
1058
+ collection = self._get_collection(table_type="knowledge")
1059
+ if collection is None:
1060
+ return
1061
+
1062
+ collection.delete_one({"id": id})
1063
+
1064
+ log_debug(f"Deleted knowledge content with id '{id}'")
1065
+
1066
+ except Exception as e:
1067
+ log_error(f"Error deleting knowledge content: {e}")
1068
+ raise
1069
+
1070
+ def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1071
+ """Get a knowledge row from the database.
1072
+
1073
+ Args:
1074
+ id (str): The ID of the knowledge row to get.
1075
+
1076
+ Returns:
1077
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1078
+
1079
+ Raises:
1080
+ Exception: If an error occurs during retrieval.
1081
+ """
1082
+ try:
1083
+ collection = self._get_collection(table_type="knowledge")
1084
+ if collection is None:
1085
+ return None
1086
+
1087
+ result = collection.find_one({"id": id})
1088
+ if result is None:
1089
+ return None
1090
+
1091
+ return KnowledgeRow.model_validate(result)
1092
+
1093
+ except Exception as e:
1094
+ log_error(f"Error getting knowledge content: {e}")
1095
+ return None
1096
+
1097
+ def get_knowledge_contents(
1098
+ self,
1099
+ limit: Optional[int] = None,
1100
+ page: Optional[int] = None,
1101
+ sort_by: Optional[str] = None,
1102
+ sort_order: Optional[str] = None,
1103
+ ) -> Tuple[List[KnowledgeRow], int]:
1104
+ """Get all knowledge contents from the database.
1105
+
1106
+ Args:
1107
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1108
+ page (Optional[int]): The page number.
1109
+ sort_by (Optional[str]): The column to sort by.
1110
+ sort_order (Optional[str]): The order to sort by.
1111
+ create_table_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
1112
+
1113
+ Returns:
1114
+ Tuple[List[KnowledgeRow], int]: The knowledge contents and total count.
1115
+
1116
+ Raises:
1117
+ Exception: If an error occurs during retrieval.
1118
+ """
1119
+ try:
1120
+ collection = self._get_collection(table_type="knowledge")
1121
+ if collection is None:
1122
+ return [], 0
1123
+
1124
+ query: Dict[str, Any] = {}
1125
+
1126
+ # Get total count
1127
+ total_count = collection.count_documents(query)
1128
+
1129
+ # Apply sorting
1130
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1131
+
1132
+ # Apply pagination
1133
+ query_args = apply_pagination({}, limit, page)
1134
+
1135
+ cursor = collection.find(query)
1136
+ if sort_criteria:
1137
+ cursor = cursor.sort(sort_criteria)
1138
+ if query_args.get("skip"):
1139
+ cursor = cursor.skip(query_args["skip"])
1140
+ if query_args.get("limit"):
1141
+ cursor = cursor.limit(query_args["limit"])
1142
+
1143
+ records = list(cursor)
1144
+ knowledge_rows = [KnowledgeRow.model_validate(record) for record in records]
1145
+
1146
+ return knowledge_rows, total_count
1147
+
1148
+ except Exception as e:
1149
+ log_error(f"Error getting knowledge contents: {e}")
1150
+ return [], 0
1151
+
1152
+ def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1153
+ """Upsert knowledge content in the database.
1154
+
1155
+ Args:
1156
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1157
+
1158
+ Returns:
1159
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1160
+
1161
+ Raises:
1162
+ Exception: If an error occurs during upsert.
1163
+ """
1164
+ try:
1165
+ collection = self._get_collection(table_type="knowledge", create_collection_if_not_found=True)
1166
+ if collection is None:
1167
+ return None
1168
+
1169
+ update_doc = knowledge_row.model_dump()
1170
+ collection.replace_one({"id": knowledge_row.id}, update_doc, upsert=True)
1171
+
1172
+ return knowledge_row
1173
+
1174
+ except Exception as e:
1175
+ log_error(f"Error upserting knowledge content: {e}")
1176
+ return None
1177
+
1178
+ # -- Eval methods --
1179
+
1180
+ def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1181
+ """Create an EvalRunRecord in the database."""
1182
+ try:
1183
+ collection = self._get_collection(table_type="evals", create_collection_if_not_found=True)
1184
+ if collection is None:
1185
+ return None
1186
+
1187
+ current_time = int(time.time())
1188
+ eval_dict = eval_run.model_dump()
1189
+ eval_dict["created_at"] = current_time
1190
+ eval_dict["updated_at"] = current_time
1191
+
1192
+ collection.insert_one(eval_dict)
1193
+
1194
+ log_debug(f"Created eval run with id '{eval_run.run_id}'")
1195
+
1196
+ return eval_run
1197
+
1198
+ except Exception as e:
1199
+ log_error(f"Error creating eval run: {e}")
1200
+ return None
1201
+
1202
+ def delete_eval_run(self, eval_run_id: str) -> None:
1203
+ """Delete an eval run from the database."""
1204
+ try:
1205
+ collection = self._get_collection(table_type="evals")
1206
+ if collection is None:
1207
+ return
1208
+
1209
+ result = collection.delete_one({"run_id": eval_run_id})
1210
+
1211
+ if result.deleted_count == 0:
1212
+ log_debug(f"No eval run found with ID: {eval_run_id}")
1213
+ else:
1214
+ log_debug(f"Deleted eval run with ID: {eval_run_id}")
1215
+
1216
+ except Exception as e:
1217
+ log_error(f"Error deleting eval run {eval_run_id}: {e}")
1218
+ raise
1219
+
1220
+ def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1221
+ """Delete multiple eval runs from the database."""
1222
+ try:
1223
+ collection = self._get_collection(table_type="evals")
1224
+ if collection is None:
1225
+ return
1226
+
1227
+ result = collection.delete_many({"run_id": {"$in": eval_run_ids}})
1228
+
1229
+ if result.deleted_count == 0:
1230
+ log_debug(f"No eval runs found with IDs: {eval_run_ids}")
1231
+ else:
1232
+ log_debug(f"Deleted {result.deleted_count} eval runs")
1233
+
1234
+ except Exception as e:
1235
+ log_error(f"Error deleting eval runs {eval_run_ids}: {e}")
1236
+ raise
1237
+
1238
+ def get_eval_run_raw(self, eval_run_id: str) -> Optional[Dict[str, Any]]:
1239
+ """Get an eval run from the database as a raw dictionary."""
1240
+ try:
1241
+ collection = self._get_collection(table_type="evals")
1242
+ if collection is None:
1243
+ return None
1244
+
1245
+ result = collection.find_one({"run_id": eval_run_id})
1246
+ return result
1247
+
1248
+ except Exception as e:
1249
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1250
+ return None
1251
+
1252
+ def get_eval_run(self, eval_run_id: str, deserialize: Optional[bool] = True) -> Optional[EvalRunRecord]:
1253
+ """Get an eval run from the database.
1254
+
1255
+ Args:
1256
+ eval_run_id (str): The ID of the eval run to get.
1257
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1258
+
1259
+ Returns:
1260
+ Optional[EvalRunRecord]:
1261
+ - When deserialize=True: EvalRunRecord object
1262
+ - When deserialize=False: EvalRun dictionary
1263
+
1264
+ Raises:
1265
+ Exception: If there is an error getting the eval run.
1266
+ """
1267
+ try:
1268
+ collection = self._get_collection(table_type="evals")
1269
+ if collection is None:
1270
+ return None
1271
+
1272
+ eval_run_raw = collection.find_one({"run_id": eval_run_id})
1273
+
1274
+ if not eval_run_raw:
1275
+ return None
1276
+
1277
+ if not deserialize:
1278
+ return eval_run_raw
1279
+
1280
+ return EvalRunRecord.model_validate(eval_run_raw)
1281
+
1282
+ except Exception as e:
1283
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1284
+ return None
1285
+
1286
+ def get_eval_runs(
1287
+ self,
1288
+ limit: Optional[int] = None,
1289
+ page: Optional[int] = None,
1290
+ sort_by: Optional[str] = None,
1291
+ sort_order: Optional[str] = None,
1292
+ agent_id: Optional[str] = None,
1293
+ team_id: Optional[str] = None,
1294
+ workflow_id: Optional[str] = None,
1295
+ model_id: Optional[str] = None,
1296
+ filter_type: Optional[EvalFilterType] = None,
1297
+ eval_type: Optional[List[EvalType]] = None,
1298
+ deserialize: Optional[bool] = True,
1299
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1300
+ """Get all eval runs from the database.
1301
+
1302
+ Args:
1303
+ limit (Optional[int]): The maximum number of eval runs to return.
1304
+ page (Optional[int]): The page number to return.
1305
+ sort_by (Optional[str]): The field to sort by.
1306
+ sort_order (Optional[str]): The order to sort by.
1307
+ agent_id (Optional[str]): The ID of the agent to filter by.
1308
+ team_id (Optional[str]): The ID of the team to filter by.
1309
+ workflow_id (Optional[str]): The ID of the workflow to filter by.
1310
+ model_id (Optional[str]): The ID of the model to filter by.
1311
+ eval_type (Optional[List[EvalType]]): The type of eval to filter by.
1312
+ filter_type (Optional[EvalFilterType]): The type of filter to apply.
1313
+ deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True.
1314
+ create_table_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist.
1315
+
1316
+ Returns:
1317
+ Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1318
+ - When deserialize=True: List of EvalRunRecord objects
1319
+ - When deserialize=False: List of eval run dictionaries and the total count
1320
+
1321
+ Raises:
1322
+ Exception: If there is an error getting the eval runs.
1323
+ """
1324
+ try:
1325
+ collection = self._get_collection(table_type="evals")
1326
+ if collection is None:
1327
+ return [] if deserialize else ([], 0)
1328
+
1329
+ query: Dict[str, Any] = {}
1330
+ if agent_id is not None:
1331
+ query["agent_id"] = agent_id
1332
+ if team_id is not None:
1333
+ query["team_id"] = team_id
1334
+ if workflow_id is not None:
1335
+ query["workflow_id"] = workflow_id
1336
+ if model_id is not None:
1337
+ query["model_id"] = model_id
1338
+ if eval_type is not None and len(eval_type) > 0:
1339
+ query["eval_type"] = {"$in": eval_type}
1340
+ if filter_type is not None:
1341
+ if filter_type == EvalFilterType.AGENT:
1342
+ query["agent_id"] = {"$ne": None}
1343
+ elif filter_type == EvalFilterType.TEAM:
1344
+ query["team_id"] = {"$ne": None}
1345
+ elif filter_type == EvalFilterType.WORKFLOW:
1346
+ query["workflow_id"] = {"$ne": None}
1347
+
1348
+ # Get total count
1349
+ total_count = collection.count_documents(query)
1350
+
1351
+ # Apply default sorting by created_at desc if no sort parameters provided
1352
+ if sort_by is None:
1353
+ sort_criteria = [("created_at", -1)]
1354
+ else:
1355
+ sort_criteria = apply_sorting({}, sort_by, sort_order)
1356
+
1357
+ # Apply pagination
1358
+ query_args = apply_pagination({}, limit, page)
1359
+
1360
+ cursor = collection.find(query)
1361
+ if sort_criteria:
1362
+ cursor = cursor.sort(sort_criteria)
1363
+ if query_args.get("skip"):
1364
+ cursor = cursor.skip(query_args["skip"])
1365
+ if query_args.get("limit"):
1366
+ cursor = cursor.limit(query_args["limit"])
1367
+
1368
+ records = list(cursor)
1369
+ if not records:
1370
+ return [] if deserialize else ([], 0)
1371
+
1372
+ if not deserialize:
1373
+ return records, total_count
1374
+
1375
+ return [EvalRunRecord.model_validate(row) for row in records]
1376
+
1377
+ except Exception as e:
1378
+ log_debug(f"Exception getting eval runs: {e}")
1379
+ return [] if deserialize else ([], 0)
1380
+
1381
+ def rename_eval_run(
1382
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
1383
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1384
+ """Update the name of an eval run in the database.
1385
+
1386
+ Args:
1387
+ eval_run_id (str): The ID of the eval run to update.
1388
+ name (str): The new name of the eval run.
1389
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1390
+
1391
+ Returns:
1392
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1393
+ - When deserialize=True: EvalRunRecord object
1394
+ - When deserialize=False: EvalRun dictionary
1395
+
1396
+ Raises:
1397
+ Exception: If there is an error updating the eval run.
1398
+ """
1399
+ try:
1400
+ collection = self._get_collection(table_type="evals")
1401
+ if collection is None:
1402
+ return None
1403
+
1404
+ result = collection.find_one_and_update(
1405
+ {"run_id": eval_run_id}, {"$set": {"name": name, "updated_at": int(time.time())}}
1406
+ )
1407
+
1408
+ log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'")
1409
+
1410
+ if not result or not deserialize:
1411
+ return result
1412
+
1413
+ return EvalRunRecord.model_validate(result)
1414
+
1415
+ except Exception as e:
1416
+ log_error(f"Error updating eval run name {eval_run_id}: {e}")
1417
+ raise