agno 0.1.2__py3-none-any.whl → 2.3.13__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 (723) hide show
  1. agno/__init__.py +8 -0
  2. agno/agent/__init__.py +44 -5
  3. agno/agent/agent.py +10531 -2975
  4. agno/api/agent.py +14 -53
  5. agno/api/api.py +7 -46
  6. agno/api/evals.py +22 -0
  7. agno/api/os.py +17 -0
  8. agno/api/routes.py +6 -25
  9. agno/api/schemas/__init__.py +9 -0
  10. agno/api/schemas/agent.py +6 -9
  11. agno/api/schemas/evals.py +16 -0
  12. agno/api/schemas/os.py +14 -0
  13. agno/api/schemas/team.py +10 -10
  14. agno/api/schemas/utils.py +21 -0
  15. agno/api/schemas/workflows.py +16 -0
  16. agno/api/settings.py +53 -0
  17. agno/api/team.py +22 -26
  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/compression/__init__.py +3 -0
  25. agno/compression/manager.py +247 -0
  26. agno/culture/__init__.py +3 -0
  27. agno/culture/manager.py +956 -0
  28. agno/db/__init__.py +24 -0
  29. agno/db/async_postgres/__init__.py +3 -0
  30. agno/db/base.py +946 -0
  31. agno/db/dynamo/__init__.py +3 -0
  32. agno/db/dynamo/dynamo.py +2781 -0
  33. agno/db/dynamo/schemas.py +442 -0
  34. agno/db/dynamo/utils.py +743 -0
  35. agno/db/firestore/__init__.py +3 -0
  36. agno/db/firestore/firestore.py +2379 -0
  37. agno/db/firestore/schemas.py +181 -0
  38. agno/db/firestore/utils.py +376 -0
  39. agno/db/gcs_json/__init__.py +3 -0
  40. agno/db/gcs_json/gcs_json_db.py +1791 -0
  41. agno/db/gcs_json/utils.py +228 -0
  42. agno/db/in_memory/__init__.py +3 -0
  43. agno/db/in_memory/in_memory_db.py +1312 -0
  44. agno/db/in_memory/utils.py +230 -0
  45. agno/db/json/__init__.py +3 -0
  46. agno/db/json/json_db.py +1777 -0
  47. agno/db/json/utils.py +230 -0
  48. agno/db/migrations/manager.py +199 -0
  49. agno/db/migrations/v1_to_v2.py +635 -0
  50. agno/db/migrations/versions/v2_3_0.py +938 -0
  51. agno/db/mongo/__init__.py +17 -0
  52. agno/db/mongo/async_mongo.py +2760 -0
  53. agno/db/mongo/mongo.py +2597 -0
  54. agno/db/mongo/schemas.py +119 -0
  55. agno/db/mongo/utils.py +276 -0
  56. agno/db/mysql/__init__.py +4 -0
  57. agno/db/mysql/async_mysql.py +2912 -0
  58. agno/db/mysql/mysql.py +2923 -0
  59. agno/db/mysql/schemas.py +186 -0
  60. agno/db/mysql/utils.py +488 -0
  61. agno/db/postgres/__init__.py +4 -0
  62. agno/db/postgres/async_postgres.py +2579 -0
  63. agno/db/postgres/postgres.py +2870 -0
  64. agno/db/postgres/schemas.py +187 -0
  65. agno/db/postgres/utils.py +442 -0
  66. agno/db/redis/__init__.py +3 -0
  67. agno/db/redis/redis.py +2141 -0
  68. agno/db/redis/schemas.py +159 -0
  69. agno/db/redis/utils.py +346 -0
  70. agno/db/schemas/__init__.py +4 -0
  71. agno/db/schemas/culture.py +120 -0
  72. agno/db/schemas/evals.py +34 -0
  73. agno/db/schemas/knowledge.py +40 -0
  74. agno/db/schemas/memory.py +61 -0
  75. agno/db/singlestore/__init__.py +3 -0
  76. agno/db/singlestore/schemas.py +179 -0
  77. agno/db/singlestore/singlestore.py +2877 -0
  78. agno/db/singlestore/utils.py +384 -0
  79. agno/db/sqlite/__init__.py +4 -0
  80. agno/db/sqlite/async_sqlite.py +2911 -0
  81. agno/db/sqlite/schemas.py +181 -0
  82. agno/db/sqlite/sqlite.py +2908 -0
  83. agno/db/sqlite/utils.py +429 -0
  84. agno/db/surrealdb/__init__.py +3 -0
  85. agno/db/surrealdb/metrics.py +292 -0
  86. agno/db/surrealdb/models.py +334 -0
  87. agno/db/surrealdb/queries.py +71 -0
  88. agno/db/surrealdb/surrealdb.py +1908 -0
  89. agno/db/surrealdb/utils.py +147 -0
  90. agno/db/utils.py +118 -0
  91. agno/eval/__init__.py +24 -0
  92. agno/eval/accuracy.py +666 -276
  93. agno/eval/agent_as_judge.py +861 -0
  94. agno/eval/base.py +29 -0
  95. agno/eval/performance.py +779 -0
  96. agno/eval/reliability.py +241 -62
  97. agno/eval/utils.py +120 -0
  98. agno/exceptions.py +143 -1
  99. agno/filters.py +354 -0
  100. agno/guardrails/__init__.py +6 -0
  101. agno/guardrails/base.py +19 -0
  102. agno/guardrails/openai.py +144 -0
  103. agno/guardrails/pii.py +94 -0
  104. agno/guardrails/prompt_injection.py +52 -0
  105. agno/hooks/__init__.py +3 -0
  106. agno/hooks/decorator.py +164 -0
  107. agno/integrations/discord/__init__.py +3 -0
  108. agno/integrations/discord/client.py +203 -0
  109. agno/knowledge/__init__.py +5 -1
  110. agno/{document → knowledge}/chunking/agentic.py +22 -14
  111. agno/{document → knowledge}/chunking/document.py +2 -2
  112. agno/{document → knowledge}/chunking/fixed.py +7 -6
  113. agno/knowledge/chunking/markdown.py +151 -0
  114. agno/{document → knowledge}/chunking/recursive.py +15 -3
  115. agno/knowledge/chunking/row.py +39 -0
  116. agno/knowledge/chunking/semantic.py +91 -0
  117. agno/knowledge/chunking/strategy.py +165 -0
  118. agno/knowledge/content.py +74 -0
  119. agno/knowledge/document/__init__.py +5 -0
  120. agno/{document → knowledge/document}/base.py +12 -2
  121. agno/knowledge/embedder/__init__.py +5 -0
  122. agno/knowledge/embedder/aws_bedrock.py +343 -0
  123. agno/knowledge/embedder/azure_openai.py +210 -0
  124. agno/{embedder → knowledge/embedder}/base.py +8 -0
  125. agno/knowledge/embedder/cohere.py +323 -0
  126. agno/knowledge/embedder/fastembed.py +62 -0
  127. agno/{embedder → knowledge/embedder}/fireworks.py +1 -1
  128. agno/knowledge/embedder/google.py +258 -0
  129. agno/knowledge/embedder/huggingface.py +94 -0
  130. agno/knowledge/embedder/jina.py +182 -0
  131. agno/knowledge/embedder/langdb.py +22 -0
  132. agno/knowledge/embedder/mistral.py +206 -0
  133. agno/knowledge/embedder/nebius.py +13 -0
  134. agno/knowledge/embedder/ollama.py +154 -0
  135. agno/knowledge/embedder/openai.py +195 -0
  136. agno/knowledge/embedder/sentence_transformer.py +63 -0
  137. agno/{embedder → knowledge/embedder}/together.py +1 -1
  138. agno/knowledge/embedder/vllm.py +262 -0
  139. agno/knowledge/embedder/voyageai.py +165 -0
  140. agno/knowledge/knowledge.py +3006 -0
  141. agno/knowledge/reader/__init__.py +7 -0
  142. agno/knowledge/reader/arxiv_reader.py +81 -0
  143. agno/knowledge/reader/base.py +95 -0
  144. agno/knowledge/reader/csv_reader.py +164 -0
  145. agno/knowledge/reader/docx_reader.py +82 -0
  146. agno/knowledge/reader/field_labeled_csv_reader.py +290 -0
  147. agno/knowledge/reader/firecrawl_reader.py +201 -0
  148. agno/knowledge/reader/json_reader.py +88 -0
  149. agno/knowledge/reader/markdown_reader.py +137 -0
  150. agno/knowledge/reader/pdf_reader.py +431 -0
  151. agno/knowledge/reader/pptx_reader.py +101 -0
  152. agno/knowledge/reader/reader_factory.py +313 -0
  153. agno/knowledge/reader/s3_reader.py +89 -0
  154. agno/knowledge/reader/tavily_reader.py +193 -0
  155. agno/knowledge/reader/text_reader.py +127 -0
  156. agno/knowledge/reader/web_search_reader.py +325 -0
  157. agno/knowledge/reader/website_reader.py +455 -0
  158. agno/knowledge/reader/wikipedia_reader.py +91 -0
  159. agno/knowledge/reader/youtube_reader.py +78 -0
  160. agno/knowledge/remote_content/remote_content.py +88 -0
  161. agno/knowledge/reranker/__init__.py +3 -0
  162. agno/{reranker → knowledge/reranker}/base.py +1 -1
  163. agno/{reranker → knowledge/reranker}/cohere.py +2 -2
  164. agno/knowledge/reranker/infinity.py +195 -0
  165. agno/knowledge/reranker/sentence_transformer.py +54 -0
  166. agno/knowledge/types.py +39 -0
  167. agno/knowledge/utils.py +234 -0
  168. agno/media.py +439 -95
  169. agno/memory/__init__.py +16 -3
  170. agno/memory/manager.py +1474 -123
  171. agno/memory/strategies/__init__.py +15 -0
  172. agno/memory/strategies/base.py +66 -0
  173. agno/memory/strategies/summarize.py +196 -0
  174. agno/memory/strategies/types.py +37 -0
  175. agno/models/aimlapi/__init__.py +5 -0
  176. agno/models/aimlapi/aimlapi.py +62 -0
  177. agno/models/anthropic/__init__.py +4 -0
  178. agno/models/anthropic/claude.py +960 -496
  179. agno/models/aws/__init__.py +15 -0
  180. agno/models/aws/bedrock.py +686 -451
  181. agno/models/aws/claude.py +190 -183
  182. agno/models/azure/__init__.py +18 -1
  183. agno/models/azure/ai_foundry.py +489 -0
  184. agno/models/azure/openai_chat.py +89 -40
  185. agno/models/base.py +2477 -550
  186. agno/models/cerebras/__init__.py +12 -0
  187. agno/models/cerebras/cerebras.py +565 -0
  188. agno/models/cerebras/cerebras_openai.py +131 -0
  189. agno/models/cohere/__init__.py +4 -0
  190. agno/models/cohere/chat.py +306 -492
  191. agno/models/cometapi/__init__.py +5 -0
  192. agno/models/cometapi/cometapi.py +74 -0
  193. agno/models/dashscope/__init__.py +5 -0
  194. agno/models/dashscope/dashscope.py +90 -0
  195. agno/models/deepinfra/__init__.py +5 -0
  196. agno/models/deepinfra/deepinfra.py +45 -0
  197. agno/models/deepseek/__init__.py +4 -0
  198. agno/models/deepseek/deepseek.py +110 -9
  199. agno/models/fireworks/__init__.py +4 -0
  200. agno/models/fireworks/fireworks.py +19 -22
  201. agno/models/google/__init__.py +3 -7
  202. agno/models/google/gemini.py +1717 -662
  203. agno/models/google/utils.py +22 -0
  204. agno/models/groq/__init__.py +4 -0
  205. agno/models/groq/groq.py +391 -666
  206. agno/models/huggingface/__init__.py +4 -0
  207. agno/models/huggingface/huggingface.py +266 -538
  208. agno/models/ibm/__init__.py +5 -0
  209. agno/models/ibm/watsonx.py +432 -0
  210. agno/models/internlm/__init__.py +3 -0
  211. agno/models/internlm/internlm.py +20 -3
  212. agno/models/langdb/__init__.py +1 -0
  213. agno/models/langdb/langdb.py +60 -0
  214. agno/models/litellm/__init__.py +14 -0
  215. agno/models/litellm/chat.py +503 -0
  216. agno/models/litellm/litellm_openai.py +42 -0
  217. agno/models/llama_cpp/__init__.py +5 -0
  218. agno/models/llama_cpp/llama_cpp.py +22 -0
  219. agno/models/lmstudio/__init__.py +5 -0
  220. agno/models/lmstudio/lmstudio.py +25 -0
  221. agno/models/message.py +361 -39
  222. agno/models/meta/__init__.py +12 -0
  223. agno/models/meta/llama.py +502 -0
  224. agno/models/meta/llama_openai.py +79 -0
  225. agno/models/metrics.py +120 -0
  226. agno/models/mistral/__init__.py +4 -0
  227. agno/models/mistral/mistral.py +293 -393
  228. agno/models/nebius/__init__.py +3 -0
  229. agno/models/nebius/nebius.py +53 -0
  230. agno/models/nexus/__init__.py +3 -0
  231. agno/models/nexus/nexus.py +22 -0
  232. agno/models/nvidia/__init__.py +4 -0
  233. agno/models/nvidia/nvidia.py +22 -3
  234. agno/models/ollama/__init__.py +4 -2
  235. agno/models/ollama/chat.py +257 -492
  236. agno/models/openai/__init__.py +7 -0
  237. agno/models/openai/chat.py +725 -770
  238. agno/models/openai/like.py +16 -2
  239. agno/models/openai/responses.py +1121 -0
  240. agno/models/openrouter/__init__.py +4 -0
  241. agno/models/openrouter/openrouter.py +62 -5
  242. agno/models/perplexity/__init__.py +5 -0
  243. agno/models/perplexity/perplexity.py +203 -0
  244. agno/models/portkey/__init__.py +3 -0
  245. agno/models/portkey/portkey.py +82 -0
  246. agno/models/requesty/__init__.py +5 -0
  247. agno/models/requesty/requesty.py +69 -0
  248. agno/models/response.py +177 -7
  249. agno/models/sambanova/__init__.py +4 -0
  250. agno/models/sambanova/sambanova.py +23 -4
  251. agno/models/siliconflow/__init__.py +5 -0
  252. agno/models/siliconflow/siliconflow.py +42 -0
  253. agno/models/together/__init__.py +4 -0
  254. agno/models/together/together.py +21 -164
  255. agno/models/utils.py +266 -0
  256. agno/models/vercel/__init__.py +3 -0
  257. agno/models/vercel/v0.py +43 -0
  258. agno/models/vertexai/__init__.py +0 -1
  259. agno/models/vertexai/claude.py +190 -0
  260. agno/models/vllm/__init__.py +3 -0
  261. agno/models/vllm/vllm.py +83 -0
  262. agno/models/xai/__init__.py +2 -0
  263. agno/models/xai/xai.py +111 -7
  264. agno/os/__init__.py +3 -0
  265. agno/os/app.py +1027 -0
  266. agno/os/auth.py +244 -0
  267. agno/os/config.py +126 -0
  268. agno/os/interfaces/__init__.py +1 -0
  269. agno/os/interfaces/a2a/__init__.py +3 -0
  270. agno/os/interfaces/a2a/a2a.py +42 -0
  271. agno/os/interfaces/a2a/router.py +249 -0
  272. agno/os/interfaces/a2a/utils.py +924 -0
  273. agno/os/interfaces/agui/__init__.py +3 -0
  274. agno/os/interfaces/agui/agui.py +47 -0
  275. agno/os/interfaces/agui/router.py +147 -0
  276. agno/os/interfaces/agui/utils.py +574 -0
  277. agno/os/interfaces/base.py +25 -0
  278. agno/os/interfaces/slack/__init__.py +3 -0
  279. agno/os/interfaces/slack/router.py +148 -0
  280. agno/os/interfaces/slack/security.py +30 -0
  281. agno/os/interfaces/slack/slack.py +47 -0
  282. agno/os/interfaces/whatsapp/__init__.py +3 -0
  283. agno/os/interfaces/whatsapp/router.py +210 -0
  284. agno/os/interfaces/whatsapp/security.py +55 -0
  285. agno/os/interfaces/whatsapp/whatsapp.py +36 -0
  286. agno/os/mcp.py +293 -0
  287. agno/os/middleware/__init__.py +9 -0
  288. agno/os/middleware/jwt.py +797 -0
  289. agno/os/router.py +258 -0
  290. agno/os/routers/__init__.py +3 -0
  291. agno/os/routers/agents/__init__.py +3 -0
  292. agno/os/routers/agents/router.py +599 -0
  293. agno/os/routers/agents/schema.py +261 -0
  294. agno/os/routers/evals/__init__.py +3 -0
  295. agno/os/routers/evals/evals.py +450 -0
  296. agno/os/routers/evals/schemas.py +174 -0
  297. agno/os/routers/evals/utils.py +231 -0
  298. agno/os/routers/health.py +31 -0
  299. agno/os/routers/home.py +52 -0
  300. agno/os/routers/knowledge/__init__.py +3 -0
  301. agno/os/routers/knowledge/knowledge.py +1008 -0
  302. agno/os/routers/knowledge/schemas.py +178 -0
  303. agno/os/routers/memory/__init__.py +3 -0
  304. agno/os/routers/memory/memory.py +661 -0
  305. agno/os/routers/memory/schemas.py +88 -0
  306. agno/os/routers/metrics/__init__.py +3 -0
  307. agno/os/routers/metrics/metrics.py +190 -0
  308. agno/os/routers/metrics/schemas.py +47 -0
  309. agno/os/routers/session/__init__.py +3 -0
  310. agno/os/routers/session/session.py +997 -0
  311. agno/os/routers/teams/__init__.py +3 -0
  312. agno/os/routers/teams/router.py +512 -0
  313. agno/os/routers/teams/schema.py +257 -0
  314. agno/os/routers/traces/__init__.py +3 -0
  315. agno/os/routers/traces/schemas.py +414 -0
  316. agno/os/routers/traces/traces.py +499 -0
  317. agno/os/routers/workflows/__init__.py +3 -0
  318. agno/os/routers/workflows/router.py +624 -0
  319. agno/os/routers/workflows/schema.py +75 -0
  320. agno/os/schema.py +534 -0
  321. agno/os/scopes.py +469 -0
  322. agno/{playground → os}/settings.py +7 -15
  323. agno/os/utils.py +973 -0
  324. agno/reasoning/anthropic.py +80 -0
  325. agno/reasoning/azure_ai_foundry.py +67 -0
  326. agno/reasoning/deepseek.py +63 -0
  327. agno/reasoning/default.py +97 -0
  328. agno/reasoning/gemini.py +73 -0
  329. agno/reasoning/groq.py +71 -0
  330. agno/reasoning/helpers.py +24 -1
  331. agno/reasoning/ollama.py +67 -0
  332. agno/reasoning/openai.py +86 -0
  333. agno/reasoning/step.py +2 -1
  334. agno/reasoning/vertexai.py +76 -0
  335. agno/run/__init__.py +6 -0
  336. agno/run/agent.py +822 -0
  337. agno/run/base.py +247 -0
  338. agno/run/cancel.py +81 -0
  339. agno/run/requirement.py +181 -0
  340. agno/run/team.py +767 -0
  341. agno/run/workflow.py +708 -0
  342. agno/session/__init__.py +10 -0
  343. agno/session/agent.py +260 -0
  344. agno/session/summary.py +265 -0
  345. agno/session/team.py +342 -0
  346. agno/session/workflow.py +501 -0
  347. agno/table.py +10 -0
  348. agno/team/__init__.py +37 -0
  349. agno/team/team.py +9536 -0
  350. agno/tools/__init__.py +7 -0
  351. agno/tools/agentql.py +120 -0
  352. agno/tools/airflow.py +22 -12
  353. agno/tools/api.py +122 -0
  354. agno/tools/apify.py +276 -83
  355. agno/tools/{arxiv_toolkit.py → arxiv.py} +20 -12
  356. agno/tools/aws_lambda.py +28 -7
  357. agno/tools/aws_ses.py +66 -0
  358. agno/tools/baidusearch.py +11 -4
  359. agno/tools/bitbucket.py +292 -0
  360. agno/tools/brandfetch.py +213 -0
  361. agno/tools/bravesearch.py +106 -0
  362. agno/tools/brightdata.py +367 -0
  363. agno/tools/browserbase.py +209 -0
  364. agno/tools/calcom.py +32 -23
  365. agno/tools/calculator.py +24 -37
  366. agno/tools/cartesia.py +187 -0
  367. agno/tools/{clickup_tool.py → clickup.py} +17 -28
  368. agno/tools/confluence.py +91 -26
  369. agno/tools/crawl4ai.py +139 -43
  370. agno/tools/csv_toolkit.py +28 -22
  371. agno/tools/dalle.py +36 -22
  372. agno/tools/daytona.py +475 -0
  373. agno/tools/decorator.py +169 -14
  374. agno/tools/desi_vocal.py +23 -11
  375. agno/tools/discord.py +32 -29
  376. agno/tools/docker.py +716 -0
  377. agno/tools/duckdb.py +76 -81
  378. agno/tools/duckduckgo.py +43 -40
  379. agno/tools/e2b.py +703 -0
  380. agno/tools/eleven_labs.py +65 -54
  381. agno/tools/email.py +13 -5
  382. agno/tools/evm.py +129 -0
  383. agno/tools/exa.py +324 -42
  384. agno/tools/fal.py +39 -35
  385. agno/tools/file.py +196 -30
  386. agno/tools/file_generation.py +356 -0
  387. agno/tools/financial_datasets.py +288 -0
  388. agno/tools/firecrawl.py +108 -33
  389. agno/tools/function.py +960 -122
  390. agno/tools/giphy.py +34 -12
  391. agno/tools/github.py +1294 -97
  392. agno/tools/gmail.py +922 -0
  393. agno/tools/google_bigquery.py +117 -0
  394. agno/tools/google_drive.py +271 -0
  395. agno/tools/google_maps.py +253 -0
  396. agno/tools/googlecalendar.py +607 -107
  397. agno/tools/googlesheets.py +377 -0
  398. agno/tools/hackernews.py +20 -12
  399. agno/tools/jina.py +24 -14
  400. agno/tools/jira.py +48 -19
  401. agno/tools/knowledge.py +218 -0
  402. agno/tools/linear.py +82 -43
  403. agno/tools/linkup.py +58 -0
  404. agno/tools/local_file_system.py +15 -7
  405. agno/tools/lumalab.py +41 -26
  406. agno/tools/mcp/__init__.py +10 -0
  407. agno/tools/mcp/mcp.py +331 -0
  408. agno/tools/mcp/multi_mcp.py +347 -0
  409. agno/tools/mcp/params.py +24 -0
  410. agno/tools/mcp_toolbox.py +284 -0
  411. agno/tools/mem0.py +193 -0
  412. agno/tools/memory.py +419 -0
  413. agno/tools/mlx_transcribe.py +11 -9
  414. agno/tools/models/azure_openai.py +190 -0
  415. agno/tools/models/gemini.py +203 -0
  416. agno/tools/models/groq.py +158 -0
  417. agno/tools/models/morph.py +186 -0
  418. agno/tools/models/nebius.py +124 -0
  419. agno/tools/models_labs.py +163 -82
  420. agno/tools/moviepy_video.py +18 -13
  421. agno/tools/nano_banana.py +151 -0
  422. agno/tools/neo4j.py +134 -0
  423. agno/tools/newspaper.py +15 -4
  424. agno/tools/newspaper4k.py +19 -6
  425. agno/tools/notion.py +204 -0
  426. agno/tools/openai.py +181 -17
  427. agno/tools/openbb.py +27 -20
  428. agno/tools/opencv.py +321 -0
  429. agno/tools/openweather.py +233 -0
  430. agno/tools/oxylabs.py +385 -0
  431. agno/tools/pandas.py +25 -15
  432. agno/tools/parallel.py +314 -0
  433. agno/tools/postgres.py +238 -185
  434. agno/tools/pubmed.py +125 -13
  435. agno/tools/python.py +48 -35
  436. agno/tools/reasoning.py +283 -0
  437. agno/tools/reddit.py +207 -29
  438. agno/tools/redshift.py +406 -0
  439. agno/tools/replicate.py +69 -26
  440. agno/tools/resend.py +11 -6
  441. agno/tools/scrapegraph.py +179 -19
  442. agno/tools/searxng.py +23 -31
  443. agno/tools/serpapi.py +15 -10
  444. agno/tools/serper.py +255 -0
  445. agno/tools/shell.py +23 -12
  446. agno/tools/shopify.py +1519 -0
  447. agno/tools/slack.py +56 -14
  448. agno/tools/sleep.py +8 -6
  449. agno/tools/spider.py +35 -11
  450. agno/tools/spotify.py +919 -0
  451. agno/tools/sql.py +34 -19
  452. agno/tools/tavily.py +158 -8
  453. agno/tools/telegram.py +18 -8
  454. agno/tools/todoist.py +218 -0
  455. agno/tools/toolkit.py +134 -9
  456. agno/tools/trafilatura.py +388 -0
  457. agno/tools/trello.py +25 -28
  458. agno/tools/twilio.py +18 -9
  459. agno/tools/user_control_flow.py +78 -0
  460. agno/tools/valyu.py +228 -0
  461. agno/tools/visualization.py +467 -0
  462. agno/tools/webbrowser.py +28 -0
  463. agno/tools/webex.py +76 -0
  464. agno/tools/website.py +23 -19
  465. agno/tools/webtools.py +45 -0
  466. agno/tools/whatsapp.py +286 -0
  467. agno/tools/wikipedia.py +28 -19
  468. agno/tools/workflow.py +285 -0
  469. agno/tools/{twitter.py → x.py} +142 -46
  470. agno/tools/yfinance.py +41 -39
  471. agno/tools/youtube.py +34 -17
  472. agno/tools/zendesk.py +15 -5
  473. agno/tools/zep.py +454 -0
  474. agno/tools/zoom.py +86 -37
  475. agno/tracing/__init__.py +12 -0
  476. agno/tracing/exporter.py +157 -0
  477. agno/tracing/schemas.py +276 -0
  478. agno/tracing/setup.py +111 -0
  479. agno/utils/agent.py +938 -0
  480. agno/utils/audio.py +37 -1
  481. agno/utils/certs.py +27 -0
  482. agno/utils/code_execution.py +11 -0
  483. agno/utils/common.py +103 -20
  484. agno/utils/cryptography.py +22 -0
  485. agno/utils/dttm.py +33 -0
  486. agno/utils/events.py +700 -0
  487. agno/utils/functions.py +107 -37
  488. agno/utils/gemini.py +426 -0
  489. agno/utils/hooks.py +171 -0
  490. agno/utils/http.py +185 -0
  491. agno/utils/json_schema.py +159 -37
  492. agno/utils/knowledge.py +36 -0
  493. agno/utils/location.py +19 -0
  494. agno/utils/log.py +221 -8
  495. agno/utils/mcp.py +214 -0
  496. agno/utils/media.py +335 -14
  497. agno/utils/merge_dict.py +22 -1
  498. agno/utils/message.py +77 -2
  499. agno/utils/models/ai_foundry.py +50 -0
  500. agno/utils/models/claude.py +373 -0
  501. agno/utils/models/cohere.py +94 -0
  502. agno/utils/models/llama.py +85 -0
  503. agno/utils/models/mistral.py +100 -0
  504. agno/utils/models/openai_responses.py +140 -0
  505. agno/utils/models/schema_utils.py +153 -0
  506. agno/utils/models/watsonx.py +41 -0
  507. agno/utils/openai.py +257 -0
  508. agno/utils/pickle.py +1 -1
  509. agno/utils/pprint.py +124 -8
  510. agno/utils/print_response/agent.py +930 -0
  511. agno/utils/print_response/team.py +1914 -0
  512. agno/utils/print_response/workflow.py +1668 -0
  513. agno/utils/prompts.py +111 -0
  514. agno/utils/reasoning.py +108 -0
  515. agno/utils/response.py +163 -0
  516. agno/utils/serialize.py +32 -0
  517. agno/utils/shell.py +4 -4
  518. agno/utils/streamlit.py +487 -0
  519. agno/utils/string.py +204 -51
  520. agno/utils/team.py +139 -0
  521. agno/utils/timer.py +9 -2
  522. agno/utils/tokens.py +657 -0
  523. agno/utils/tools.py +19 -1
  524. agno/utils/whatsapp.py +305 -0
  525. agno/utils/yaml_io.py +3 -3
  526. agno/vectordb/__init__.py +2 -0
  527. agno/vectordb/base.py +87 -9
  528. agno/vectordb/cassandra/__init__.py +5 -1
  529. agno/vectordb/cassandra/cassandra.py +383 -27
  530. agno/vectordb/chroma/__init__.py +4 -0
  531. agno/vectordb/chroma/chromadb.py +748 -83
  532. agno/vectordb/clickhouse/__init__.py +7 -1
  533. agno/vectordb/clickhouse/clickhousedb.py +554 -53
  534. agno/vectordb/couchbase/__init__.py +3 -0
  535. agno/vectordb/couchbase/couchbase.py +1446 -0
  536. agno/vectordb/lancedb/__init__.py +5 -0
  537. agno/vectordb/lancedb/lance_db.py +730 -98
  538. agno/vectordb/langchaindb/__init__.py +5 -0
  539. agno/vectordb/langchaindb/langchaindb.py +163 -0
  540. agno/vectordb/lightrag/__init__.py +5 -0
  541. agno/vectordb/lightrag/lightrag.py +388 -0
  542. agno/vectordb/llamaindex/__init__.py +3 -0
  543. agno/vectordb/llamaindex/llamaindexdb.py +166 -0
  544. agno/vectordb/milvus/__init__.py +3 -0
  545. agno/vectordb/milvus/milvus.py +966 -78
  546. agno/vectordb/mongodb/__init__.py +9 -1
  547. agno/vectordb/mongodb/mongodb.py +1175 -172
  548. agno/vectordb/pgvector/__init__.py +8 -0
  549. agno/vectordb/pgvector/pgvector.py +599 -115
  550. agno/vectordb/pineconedb/__init__.py +5 -1
  551. agno/vectordb/pineconedb/pineconedb.py +406 -43
  552. agno/vectordb/qdrant/__init__.py +4 -0
  553. agno/vectordb/qdrant/qdrant.py +914 -61
  554. agno/vectordb/redis/__init__.py +9 -0
  555. agno/vectordb/redis/redisdb.py +682 -0
  556. agno/vectordb/singlestore/__init__.py +8 -1
  557. agno/vectordb/singlestore/singlestore.py +771 -0
  558. agno/vectordb/surrealdb/__init__.py +3 -0
  559. agno/vectordb/surrealdb/surrealdb.py +663 -0
  560. agno/vectordb/upstashdb/__init__.py +5 -0
  561. agno/vectordb/upstashdb/upstashdb.py +718 -0
  562. agno/vectordb/weaviate/__init__.py +8 -0
  563. agno/vectordb/weaviate/index.py +15 -0
  564. agno/vectordb/weaviate/weaviate.py +1009 -0
  565. agno/workflow/__init__.py +23 -1
  566. agno/workflow/agent.py +299 -0
  567. agno/workflow/condition.py +759 -0
  568. agno/workflow/loop.py +756 -0
  569. agno/workflow/parallel.py +853 -0
  570. agno/workflow/router.py +723 -0
  571. agno/workflow/step.py +1564 -0
  572. agno/workflow/steps.py +613 -0
  573. agno/workflow/types.py +556 -0
  574. agno/workflow/workflow.py +4327 -514
  575. agno-2.3.13.dist-info/METADATA +639 -0
  576. agno-2.3.13.dist-info/RECORD +613 -0
  577. {agno-0.1.2.dist-info → agno-2.3.13.dist-info}/WHEEL +1 -1
  578. agno-2.3.13.dist-info/licenses/LICENSE +201 -0
  579. agno/api/playground.py +0 -91
  580. agno/api/schemas/playground.py +0 -22
  581. agno/api/schemas/user.py +0 -22
  582. agno/api/schemas/workspace.py +0 -46
  583. agno/api/user.py +0 -160
  584. agno/api/workspace.py +0 -151
  585. agno/cli/auth_server.py +0 -118
  586. agno/cli/config.py +0 -275
  587. agno/cli/console.py +0 -88
  588. agno/cli/credentials.py +0 -23
  589. agno/cli/entrypoint.py +0 -571
  590. agno/cli/operator.py +0 -355
  591. agno/cli/settings.py +0 -85
  592. agno/cli/ws/ws_cli.py +0 -817
  593. agno/constants.py +0 -13
  594. agno/document/__init__.py +0 -1
  595. agno/document/chunking/semantic.py +0 -47
  596. agno/document/chunking/strategy.py +0 -31
  597. agno/document/reader/__init__.py +0 -1
  598. agno/document/reader/arxiv_reader.py +0 -41
  599. agno/document/reader/base.py +0 -22
  600. agno/document/reader/csv_reader.py +0 -84
  601. agno/document/reader/docx_reader.py +0 -46
  602. agno/document/reader/firecrawl_reader.py +0 -99
  603. agno/document/reader/json_reader.py +0 -43
  604. agno/document/reader/pdf_reader.py +0 -219
  605. agno/document/reader/s3/pdf_reader.py +0 -46
  606. agno/document/reader/s3/text_reader.py +0 -51
  607. agno/document/reader/text_reader.py +0 -41
  608. agno/document/reader/website_reader.py +0 -175
  609. agno/document/reader/youtube_reader.py +0 -50
  610. agno/embedder/__init__.py +0 -1
  611. agno/embedder/azure_openai.py +0 -86
  612. agno/embedder/cohere.py +0 -72
  613. agno/embedder/fastembed.py +0 -37
  614. agno/embedder/google.py +0 -73
  615. agno/embedder/huggingface.py +0 -54
  616. agno/embedder/mistral.py +0 -80
  617. agno/embedder/ollama.py +0 -57
  618. agno/embedder/openai.py +0 -74
  619. agno/embedder/sentence_transformer.py +0 -38
  620. agno/embedder/voyageai.py +0 -64
  621. agno/eval/perf.py +0 -201
  622. agno/file/__init__.py +0 -1
  623. agno/file/file.py +0 -16
  624. agno/file/local/csv.py +0 -32
  625. agno/file/local/txt.py +0 -19
  626. agno/infra/app.py +0 -240
  627. agno/infra/base.py +0 -144
  628. agno/infra/context.py +0 -20
  629. agno/infra/db_app.py +0 -52
  630. agno/infra/resource.py +0 -205
  631. agno/infra/resources.py +0 -55
  632. agno/knowledge/agent.py +0 -230
  633. agno/knowledge/arxiv.py +0 -22
  634. agno/knowledge/combined.py +0 -22
  635. agno/knowledge/csv.py +0 -28
  636. agno/knowledge/csv_url.py +0 -19
  637. agno/knowledge/document.py +0 -20
  638. agno/knowledge/docx.py +0 -30
  639. agno/knowledge/json.py +0 -28
  640. agno/knowledge/langchain.py +0 -71
  641. agno/knowledge/llamaindex.py +0 -66
  642. agno/knowledge/pdf.py +0 -28
  643. agno/knowledge/pdf_url.py +0 -26
  644. agno/knowledge/s3/base.py +0 -60
  645. agno/knowledge/s3/pdf.py +0 -21
  646. agno/knowledge/s3/text.py +0 -23
  647. agno/knowledge/text.py +0 -30
  648. agno/knowledge/website.py +0 -88
  649. agno/knowledge/wikipedia.py +0 -31
  650. agno/knowledge/youtube.py +0 -22
  651. agno/memory/agent.py +0 -392
  652. agno/memory/classifier.py +0 -104
  653. agno/memory/db/__init__.py +0 -1
  654. agno/memory/db/base.py +0 -42
  655. agno/memory/db/mongodb.py +0 -189
  656. agno/memory/db/postgres.py +0 -203
  657. agno/memory/db/sqlite.py +0 -193
  658. agno/memory/memory.py +0 -15
  659. agno/memory/row.py +0 -36
  660. agno/memory/summarizer.py +0 -192
  661. agno/memory/summary.py +0 -19
  662. agno/memory/workflow.py +0 -38
  663. agno/models/google/gemini_openai.py +0 -26
  664. agno/models/ollama/hermes.py +0 -221
  665. agno/models/ollama/tools.py +0 -362
  666. agno/models/vertexai/gemini.py +0 -595
  667. agno/playground/__init__.py +0 -3
  668. agno/playground/async_router.py +0 -421
  669. agno/playground/deploy.py +0 -249
  670. agno/playground/operator.py +0 -92
  671. agno/playground/playground.py +0 -91
  672. agno/playground/schemas.py +0 -76
  673. agno/playground/serve.py +0 -55
  674. agno/playground/sync_router.py +0 -405
  675. agno/reasoning/agent.py +0 -68
  676. agno/run/response.py +0 -112
  677. agno/storage/agent/__init__.py +0 -0
  678. agno/storage/agent/base.py +0 -38
  679. agno/storage/agent/dynamodb.py +0 -350
  680. agno/storage/agent/json.py +0 -92
  681. agno/storage/agent/mongodb.py +0 -228
  682. agno/storage/agent/postgres.py +0 -367
  683. agno/storage/agent/session.py +0 -79
  684. agno/storage/agent/singlestore.py +0 -303
  685. agno/storage/agent/sqlite.py +0 -357
  686. agno/storage/agent/yaml.py +0 -93
  687. agno/storage/workflow/__init__.py +0 -0
  688. agno/storage/workflow/base.py +0 -40
  689. agno/storage/workflow/mongodb.py +0 -233
  690. agno/storage/workflow/postgres.py +0 -366
  691. agno/storage/workflow/session.py +0 -60
  692. agno/storage/workflow/sqlite.py +0 -359
  693. agno/tools/googlesearch.py +0 -88
  694. agno/utils/defaults.py +0 -57
  695. agno/utils/filesystem.py +0 -39
  696. agno/utils/git.py +0 -52
  697. agno/utils/json_io.py +0 -30
  698. agno/utils/load_env.py +0 -19
  699. agno/utils/py_io.py +0 -19
  700. agno/utils/pyproject.py +0 -18
  701. agno/utils/resource_filter.py +0 -31
  702. agno/vectordb/singlestore/s2vectordb.py +0 -390
  703. agno/vectordb/singlestore/s2vectordb2.py +0 -355
  704. agno/workspace/__init__.py +0 -0
  705. agno/workspace/config.py +0 -325
  706. agno/workspace/enums.py +0 -6
  707. agno/workspace/helpers.py +0 -48
  708. agno/workspace/operator.py +0 -758
  709. agno/workspace/settings.py +0 -63
  710. agno-0.1.2.dist-info/LICENSE +0 -375
  711. agno-0.1.2.dist-info/METADATA +0 -502
  712. agno-0.1.2.dist-info/RECORD +0 -352
  713. agno-0.1.2.dist-info/entry_points.txt +0 -3
  714. /agno/{cli → db/migrations}/__init__.py +0 -0
  715. /agno/{cli/ws → db/migrations/versions}/__init__.py +0 -0
  716. /agno/{document/chunking/__init__.py → db/schemas/metrics.py} +0 -0
  717. /agno/{document/reader/s3 → integrations}/__init__.py +0 -0
  718. /agno/{file/local → knowledge/chunking}/__init__.py +0 -0
  719. /agno/{infra → knowledge/remote_content}/__init__.py +0 -0
  720. /agno/{knowledge/s3 → tools/models}/__init__.py +0 -0
  721. /agno/{reranker → utils/models}/__init__.py +0 -0
  722. /agno/{storage → utils/print_response}/__init__.py +0 -0
  723. {agno-0.1.2.dist-info → agno-2.3.13.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,2579 @@
1
+ import time
2
+ import warnings
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
5
+ from uuid import uuid4
6
+
7
+ if TYPE_CHECKING:
8
+ from agno.tracing.schemas import Span, Trace
9
+
10
+ from agno.db.base import AsyncBaseDb, SessionType
11
+ from agno.db.migrations.manager import MigrationManager
12
+ from agno.db.postgres.schemas import get_table_schema_definition
13
+ from agno.db.postgres.utils import (
14
+ abulk_upsert_metrics,
15
+ acreate_schema,
16
+ ais_table_available,
17
+ ais_valid_table,
18
+ apply_sorting,
19
+ calculate_date_metrics,
20
+ deserialize_cultural_knowledge,
21
+ fetch_all_sessions_data,
22
+ get_dates_to_calculate_metrics_for,
23
+ serialize_cultural_knowledge,
24
+ )
25
+ from agno.db.schemas.culture import CulturalKnowledge
26
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
27
+ from agno.db.schemas.knowledge import KnowledgeRow
28
+ from agno.db.schemas.memory import UserMemory
29
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
30
+ from agno.utils.log import log_debug, log_error, log_info, log_warning
31
+
32
+ try:
33
+ from sqlalchemy import Index, String, Table, UniqueConstraint, and_, case, func, or_, update
34
+ from sqlalchemy.dialects import postgresql
35
+ from sqlalchemy.dialects.postgresql import TIMESTAMP
36
+ from sqlalchemy.exc import ProgrammingError
37
+ from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
38
+ from sqlalchemy.schema import Column, MetaData
39
+ from sqlalchemy.sql.expression import select, text
40
+ except ImportError:
41
+ raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`")
42
+
43
+
44
+ class AsyncPostgresDb(AsyncBaseDb):
45
+ def __init__(
46
+ self,
47
+ id: Optional[str] = None,
48
+ db_url: Optional[str] = None,
49
+ db_engine: Optional[AsyncEngine] = None,
50
+ db_schema: Optional[str] = None,
51
+ session_table: Optional[str] = None,
52
+ memory_table: Optional[str] = None,
53
+ metrics_table: Optional[str] = None,
54
+ eval_table: Optional[str] = None,
55
+ knowledge_table: Optional[str] = None,
56
+ culture_table: Optional[str] = None,
57
+ traces_table: Optional[str] = None,
58
+ spans_table: Optional[str] = None,
59
+ versions_table: Optional[str] = None,
60
+ create_schema: bool = True,
61
+ db_id: Optional[str] = None, # Deprecated, use id instead.
62
+ ):
63
+ """
64
+ Async interface for interacting with a PostgreSQL database.
65
+
66
+ The following order is used to determine the database connection:
67
+ 1. Use the db_engine if provided
68
+ 2. Use the db_url
69
+ 3. Raise an error if neither is provided
70
+
71
+ Args:
72
+ id (Optional[str]): The ID of the database.
73
+ db_url (Optional[str]): The database URL to connect to.
74
+ db_engine (Optional[AsyncEngine]): The SQLAlchemy async database engine to use.
75
+ db_schema (Optional[str]): The database schema to use.
76
+ session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions.
77
+ memory_table (Optional[str]): Name of the table to store memories.
78
+ metrics_table (Optional[str]): Name of the table to store metrics.
79
+ eval_table (Optional[str]): Name of the table to store evaluation runs data.
80
+ knowledge_table (Optional[str]): Name of the table to store knowledge content.
81
+ culture_table (Optional[str]): Name of the table to store cultural knowledge.
82
+ traces_table (Optional[str]): Name of the table to store run traces.
83
+ spans_table (Optional[str]): Name of the table to store span events.
84
+ versions_table (Optional[str]): Name of the table to store schema versions.
85
+ create_schema (bool): Whether to automatically create the database schema if it doesn't exist.
86
+ Set to False if schema is managed externally (e.g., via migrations). Defaults to True.
87
+ db_id: Deprecated, use id instead.
88
+
89
+ Raises:
90
+ ValueError: If neither db_url nor db_engine is provided.
91
+ ValueError: If none of the tables are provided.
92
+ """
93
+ if db_id is not None:
94
+ warnings.warn(
95
+ "The 'db_id' parameter is deprecated and will be removed in future versions. Use 'id' instead.",
96
+ DeprecationWarning,
97
+ stacklevel=2,
98
+ )
99
+
100
+ super().__init__(
101
+ id=id or db_id,
102
+ session_table=session_table,
103
+ memory_table=memory_table,
104
+ metrics_table=metrics_table,
105
+ eval_table=eval_table,
106
+ knowledge_table=knowledge_table,
107
+ culture_table=culture_table,
108
+ traces_table=traces_table,
109
+ spans_table=spans_table,
110
+ versions_table=versions_table,
111
+ )
112
+
113
+ _engine: Optional[AsyncEngine] = db_engine
114
+ if _engine is None and db_url is not None:
115
+ _engine = create_async_engine(db_url)
116
+ if _engine is None:
117
+ raise ValueError("One of db_url or db_engine must be provided")
118
+
119
+ self.db_url: Optional[str] = db_url
120
+ self.db_engine: AsyncEngine = _engine
121
+ self.db_schema: str = db_schema if db_schema is not None else "ai"
122
+ self.metadata: MetaData = MetaData(schema=self.db_schema)
123
+ self.create_schema: bool = create_schema
124
+
125
+ # Initialize database session factory
126
+ self.async_session_factory = async_sessionmaker(
127
+ bind=self.db_engine,
128
+ expire_on_commit=False,
129
+ )
130
+
131
+ # -- DB methods --
132
+ async def table_exists(self, table_name: str) -> bool:
133
+ """Check if a table with the given name exists in the Postgres database.
134
+
135
+ Args:
136
+ table_name: Name of the table to check
137
+
138
+ Returns:
139
+ bool: True if the table exists in the database, False otherwise
140
+ """
141
+ async with self.async_session_factory() as sess:
142
+ return await ais_table_available(session=sess, table_name=table_name, db_schema=self.db_schema)
143
+
144
+ async def _create_all_tables(self):
145
+ """Create all tables for the database."""
146
+ tables_to_create = [
147
+ (self.session_table_name, "sessions"),
148
+ (self.memory_table_name, "memories"),
149
+ (self.metrics_table_name, "metrics"),
150
+ (self.eval_table_name, "evals"),
151
+ (self.knowledge_table_name, "knowledge"),
152
+ (self.versions_table_name, "versions"),
153
+ ]
154
+
155
+ for table_name, table_type in tables_to_create:
156
+ await self._get_or_create_table(
157
+ table_name=table_name, table_type=table_type, create_table_if_not_found=True
158
+ )
159
+
160
+ async def _create_table(self, table_name: str, table_type: str) -> Table:
161
+ """
162
+ Create a table with the appropriate schema based on the table type.
163
+
164
+ Args:
165
+ table_name (str): Name of the table to create
166
+ table_type (str): Type of table (used to get schema definition)
167
+
168
+ Returns:
169
+ Table: SQLAlchemy Table object
170
+ """
171
+ try:
172
+ table_schema = get_table_schema_definition(table_type).copy()
173
+
174
+ columns: List[Column] = []
175
+ indexes: List[str] = []
176
+ unique_constraints: List[str] = []
177
+ schema_unique_constraints = table_schema.pop("_unique_constraints", [])
178
+
179
+ # Get the columns, indexes, and unique constraints from the table schema
180
+ for col_name, col_config in table_schema.items():
181
+ column_args = [col_name, col_config["type"]()]
182
+ column_kwargs = {}
183
+ if col_config.get("primary_key", False):
184
+ column_kwargs["primary_key"] = True
185
+ if "nullable" in col_config:
186
+ column_kwargs["nullable"] = col_config["nullable"]
187
+ if col_config.get("index", False):
188
+ indexes.append(col_name)
189
+ if col_config.get("unique", False):
190
+ column_kwargs["unique"] = True
191
+ unique_constraints.append(col_name)
192
+ columns.append(Column(*column_args, **column_kwargs)) # type: ignore
193
+
194
+ # Create the table object
195
+ table = Table(table_name, self.metadata, *columns, schema=self.db_schema)
196
+
197
+ # Add multi-column unique constraints with table-specific names
198
+ for constraint in schema_unique_constraints:
199
+ constraint_name = f"{table_name}_{constraint['name']}"
200
+ constraint_columns = constraint["columns"]
201
+ table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name))
202
+
203
+ # Add indexes to the table definition
204
+ for idx_col in indexes:
205
+ idx_name = f"idx_{table_name}_{idx_col}"
206
+ table.append_constraint(Index(idx_name, idx_col))
207
+
208
+ if self.create_schema:
209
+ async with self.async_session_factory() as sess, sess.begin():
210
+ await acreate_schema(session=sess, db_schema=self.db_schema)
211
+
212
+ # Create table
213
+ table_created = False
214
+ if not await self.table_exists(table_name):
215
+ async with self.db_engine.begin() as conn:
216
+ await conn.run_sync(table.create, checkfirst=True)
217
+ log_debug(f"Successfully created table '{table_name}'")
218
+ table_created = True
219
+ else:
220
+ log_debug(f"Table '{self.db_schema}.{table_name}' already exists, skipping creation")
221
+
222
+ # Create indexes
223
+ for idx in table.indexes:
224
+ try:
225
+ # Check if index already exists
226
+ async with self.async_session_factory() as sess:
227
+ exists_query = text(
228
+ "SELECT 1 FROM pg_indexes WHERE schemaname = :schema AND indexname = :index_name"
229
+ )
230
+ result = await sess.execute(exists_query, {"schema": self.db_schema, "index_name": idx.name})
231
+ exists = result.scalar() is not None
232
+ if exists:
233
+ log_debug(
234
+ f"Index {idx.name} already exists in {self.db_schema}.{table_name}, skipping creation"
235
+ )
236
+ continue
237
+
238
+ async with self.db_engine.begin() as conn:
239
+ await conn.run_sync(idx.create)
240
+ log_debug(f"Created index: {idx.name} for table {self.db_schema}.{table_name}")
241
+
242
+ except Exception as e:
243
+ log_error(f"Error creating index {idx.name}: {e}")
244
+
245
+ # Store the schema version for the created table
246
+ if table_name != self.versions_table_name and table_created:
247
+ # Also store the schema version for the created table
248
+ latest_schema_version = MigrationManager(self).latest_schema_version
249
+ await self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public)
250
+ log_info(
251
+ f"Successfully stored version {latest_schema_version.public} in database for table {table_name}"
252
+ )
253
+
254
+ return table
255
+
256
+ except Exception as e:
257
+ log_error(f"Could not create table {self.db_schema}.{table_name}: {e}")
258
+ raise
259
+
260
+ async def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Table:
261
+ if table_type == "sessions":
262
+ if not hasattr(self, "session_table"):
263
+ self.session_table = await self._get_or_create_table(
264
+ table_name=self.session_table_name,
265
+ table_type="sessions",
266
+ create_table_if_not_found=create_table_if_not_found,
267
+ )
268
+ return self.session_table
269
+
270
+ if table_type == "memories":
271
+ if not hasattr(self, "memory_table"):
272
+ self.memory_table = await self._get_or_create_table(
273
+ table_name=self.memory_table_name,
274
+ table_type="memories",
275
+ create_table_if_not_found=create_table_if_not_found,
276
+ )
277
+ return self.memory_table
278
+
279
+ if table_type == "metrics":
280
+ if not hasattr(self, "metrics_table"):
281
+ self.metrics_table = await self._get_or_create_table(
282
+ table_name=self.metrics_table_name,
283
+ table_type="metrics",
284
+ create_table_if_not_found=create_table_if_not_found,
285
+ )
286
+ return self.metrics_table
287
+
288
+ if table_type == "evals":
289
+ if not hasattr(self, "eval_table"):
290
+ self.eval_table = await self._get_or_create_table(
291
+ table_name=self.eval_table_name,
292
+ table_type="evals",
293
+ create_table_if_not_found=create_table_if_not_found,
294
+ )
295
+ return self.eval_table
296
+
297
+ if table_type == "knowledge":
298
+ if not hasattr(self, "knowledge_table"):
299
+ self.knowledge_table = await self._get_or_create_table(
300
+ table_name=self.knowledge_table_name,
301
+ table_type="knowledge",
302
+ create_table_if_not_found=create_table_if_not_found,
303
+ )
304
+ return self.knowledge_table
305
+
306
+ if table_type == "culture":
307
+ if not hasattr(self, "culture_table"):
308
+ self.culture_table = await self._get_or_create_table(
309
+ table_name=self.culture_table_name,
310
+ table_type="culture",
311
+ create_table_if_not_found=create_table_if_not_found,
312
+ )
313
+ return self.culture_table
314
+
315
+ if table_type == "versions":
316
+ if not hasattr(self, "versions_table"):
317
+ self.versions_table = await self._get_or_create_table(
318
+ table_name=self.versions_table_name,
319
+ table_type="versions",
320
+ create_table_if_not_found=create_table_if_not_found,
321
+ )
322
+ return self.versions_table
323
+
324
+ if table_type == "traces":
325
+ if not hasattr(self, "traces_table"):
326
+ self.traces_table = await self._get_or_create_table(
327
+ table_name=self.trace_table_name,
328
+ table_type="traces",
329
+ create_table_if_not_found=create_table_if_not_found,
330
+ )
331
+ return self.traces_table
332
+
333
+ if table_type == "spans":
334
+ if not hasattr(self, "spans_table"):
335
+ # Ensure traces table exists first (spans has FK to traces)
336
+ await self._get_table(table_type="traces", create_table_if_not_found=True)
337
+ self.spans_table = await self._get_or_create_table(
338
+ table_name=self.span_table_name,
339
+ table_type="spans",
340
+ create_table_if_not_found=create_table_if_not_found,
341
+ )
342
+ return self.spans_table
343
+
344
+ raise ValueError(f"Unknown table type: {table_type}")
345
+
346
+ async def _get_or_create_table(
347
+ self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False
348
+ ) -> Table:
349
+ """
350
+ Check if the table exists and is valid, else create it.
351
+
352
+ Args:
353
+ table_name (str): Name of the table to get or create
354
+ table_type (str): Type of table (used to get schema definition)
355
+
356
+ Returns:
357
+ Table: SQLAlchemy Table object representing the schema.
358
+ """
359
+
360
+ async with self.async_session_factory() as sess, sess.begin():
361
+ table_is_available = await ais_table_available(
362
+ session=sess, table_name=table_name, db_schema=self.db_schema
363
+ )
364
+
365
+ if (not table_is_available) and create_table_if_not_found:
366
+ return await self._create_table(table_name=table_name, table_type=table_type)
367
+
368
+ if not await ais_valid_table(
369
+ db_engine=self.db_engine,
370
+ table_name=table_name,
371
+ table_type=table_type,
372
+ db_schema=self.db_schema,
373
+ ):
374
+ raise ValueError(f"Table {self.db_schema}.{table_name} has an invalid schema")
375
+
376
+ try:
377
+ async with self.db_engine.connect() as conn:
378
+
379
+ def create_table(connection):
380
+ return Table(table_name, self.metadata, schema=self.db_schema, autoload_with=connection)
381
+
382
+ table = await conn.run_sync(create_table)
383
+
384
+ return table
385
+
386
+ except Exception as e:
387
+ log_error(f"Error loading existing table {self.db_schema}.{table_name}: {e}")
388
+ raise
389
+
390
+ async def get_latest_schema_version(self, table_name: str) -> str:
391
+ """Get the latest version of the database schema."""
392
+ table = await self._get_table(table_type="versions", create_table_if_not_found=True)
393
+ if table is None:
394
+ return "2.0.0"
395
+
396
+ async with self.async_session_factory() as sess:
397
+ stmt = select(table)
398
+ # Latest version for the given table
399
+ stmt = stmt.where(table.c.table_name == table_name)
400
+ stmt = stmt.order_by(table.c.version.desc()).limit(1)
401
+ result = await sess.execute(stmt)
402
+ row = result.fetchone()
403
+ if row is None:
404
+ return "2.0.0"
405
+
406
+ version_dict = dict(row._mapping)
407
+ return version_dict.get("version") or "2.0.0"
408
+
409
+ async def upsert_schema_version(self, table_name: str, version: str) -> None:
410
+ """Upsert the schema version into the database."""
411
+ table = await self._get_table(table_type="versions", create_table_if_not_found=True)
412
+ if table is None:
413
+ return
414
+ current_datetime = datetime.now().isoformat()
415
+ async with self.async_session_factory() as sess, sess.begin():
416
+ stmt = postgresql.insert(table).values(
417
+ table_name=table_name,
418
+ version=version,
419
+ created_at=current_datetime, # Store as ISO format string
420
+ updated_at=current_datetime,
421
+ )
422
+ # Update version if table_name already exists
423
+ stmt = stmt.on_conflict_do_update(
424
+ index_elements=["table_name"],
425
+ set_=dict(version=version, updated_at=current_datetime),
426
+ )
427
+ await sess.execute(stmt)
428
+
429
+ # -- Session methods --
430
+ async def delete_session(self, session_id: str) -> bool:
431
+ """
432
+ Delete a session from the database.
433
+
434
+ Args:
435
+ session_id (str): ID of the session to delete
436
+
437
+ Returns:
438
+ bool: True if the session was deleted, False otherwise.
439
+
440
+ Raises:
441
+ Exception: If an error occurs during deletion.
442
+ """
443
+ try:
444
+ table = await self._get_table(table_type="sessions")
445
+
446
+ async with self.async_session_factory() as sess, sess.begin():
447
+ delete_stmt = table.delete().where(table.c.session_id == session_id)
448
+ result = await sess.execute(delete_stmt)
449
+
450
+ if result.rowcount == 0: # type: ignore
451
+ log_debug(f"No session found to delete with session_id: {session_id} in table {table.name}")
452
+ return False
453
+
454
+ else:
455
+ log_debug(f"Successfully deleted session with session_id: {session_id} in table {table.name}")
456
+ return True
457
+
458
+ except Exception as e:
459
+ log_error(f"Error deleting session: {e}")
460
+ return False
461
+
462
+ async def delete_sessions(self, session_ids: List[str]) -> None:
463
+ """Delete all given sessions from the database.
464
+ Can handle multiple session types in the same run.
465
+
466
+ Args:
467
+ session_ids (List[str]): The IDs of the sessions to delete.
468
+
469
+ Raises:
470
+ Exception: If an error occurs during deletion.
471
+ """
472
+ try:
473
+ table = await self._get_table(table_type="sessions")
474
+
475
+ async with self.async_session_factory() as sess, sess.begin():
476
+ delete_stmt = table.delete().where(table.c.session_id.in_(session_ids))
477
+ result = await sess.execute(delete_stmt)
478
+
479
+ log_debug(f"Successfully deleted {result.rowcount} sessions") # type: ignore
480
+
481
+ except Exception as e:
482
+ log_error(f"Error deleting sessions: {e}")
483
+
484
+ async def get_session(
485
+ self,
486
+ session_id: str,
487
+ session_type: SessionType,
488
+ user_id: Optional[str] = None,
489
+ deserialize: Optional[bool] = True,
490
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
491
+ """
492
+ Read a session from the database.
493
+
494
+ Args:
495
+ session_id (str): ID of the session to read.
496
+ user_id (Optional[str]): User ID to filter by. Defaults to None.
497
+ session_type (Optional[SessionType]): Type of session to read. Defaults to None.
498
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
499
+
500
+ Returns:
501
+ Union[Session, Dict[str, Any], None]:
502
+ - When deserialize=True: Session object
503
+ - When deserialize=False: Session dictionary
504
+
505
+ Raises:
506
+ Exception: If an error occurs during retrieval.
507
+ """
508
+ try:
509
+ table = await self._get_table(table_type="sessions")
510
+
511
+ async with self.async_session_factory() as sess:
512
+ stmt = select(table).where(table.c.session_id == session_id)
513
+
514
+ if user_id is not None:
515
+ stmt = stmt.where(table.c.user_id == user_id)
516
+ result = await sess.execute(stmt)
517
+ row = result.fetchone()
518
+ if row is None:
519
+ return None
520
+
521
+ session = dict(row._mapping)
522
+
523
+ if not deserialize:
524
+ return session
525
+
526
+ if session_type == SessionType.AGENT:
527
+ return AgentSession.from_dict(session)
528
+ elif session_type == SessionType.TEAM:
529
+ return TeamSession.from_dict(session)
530
+ elif session_type == SessionType.WORKFLOW:
531
+ return WorkflowSession.from_dict(session)
532
+ else:
533
+ raise ValueError(f"Invalid session type: {session_type}")
534
+
535
+ except Exception as e:
536
+ log_error(f"Exception reading from session table: {e}")
537
+ return None
538
+
539
+ async def get_sessions(
540
+ self,
541
+ session_type: Optional[SessionType] = None,
542
+ user_id: Optional[str] = None,
543
+ component_id: Optional[str] = None,
544
+ session_name: Optional[str] = None,
545
+ start_timestamp: Optional[int] = None,
546
+ end_timestamp: Optional[int] = None,
547
+ limit: Optional[int] = None,
548
+ page: Optional[int] = None,
549
+ sort_by: Optional[str] = None,
550
+ sort_order: Optional[str] = None,
551
+ deserialize: Optional[bool] = True,
552
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
553
+ """
554
+ Get all sessions in the given table. Can filter by user_id and entity_id.
555
+
556
+ Args:
557
+ user_id (Optional[str]): The ID of the user to filter by.
558
+ component_id (Optional[str]): The ID of the agent / workflow to filter by.
559
+ start_timestamp (Optional[int]): The start timestamp to filter by.
560
+ end_timestamp (Optional[int]): The end timestamp to filter by.
561
+ session_name (Optional[str]): The name of the session to filter by.
562
+ limit (Optional[int]): The maximum number of sessions to return. Defaults to None.
563
+ page (Optional[int]): The page number to return. Defaults to None.
564
+ sort_by (Optional[str]): The field to sort by. Defaults to None.
565
+ sort_order (Optional[str]): The sort order. Defaults to None.
566
+ deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True.
567
+
568
+ Returns:
569
+ Union[List[Session], Tuple[List[Dict], int]]:
570
+ - When deserialize=True: List of Session objects
571
+ - When deserialize=False: Tuple of (session dictionaries, total count)
572
+
573
+ Raises:
574
+ Exception: If an error occurs during retrieval.
575
+ """
576
+ try:
577
+ table = await self._get_table(table_type="sessions")
578
+
579
+ async with self.async_session_factory() as sess, sess.begin():
580
+ stmt = select(table)
581
+
582
+ # Filtering
583
+ if user_id is not None:
584
+ stmt = stmt.where(table.c.user_id == user_id)
585
+ if component_id is not None:
586
+ if session_type == SessionType.AGENT:
587
+ stmt = stmt.where(table.c.agent_id == component_id)
588
+ elif session_type == SessionType.TEAM:
589
+ stmt = stmt.where(table.c.team_id == component_id)
590
+ elif session_type == SessionType.WORKFLOW:
591
+ stmt = stmt.where(table.c.workflow_id == component_id)
592
+ if start_timestamp is not None:
593
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
594
+ if end_timestamp is not None:
595
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
596
+ if session_name is not None:
597
+ stmt = stmt.where(
598
+ func.coalesce(func.json_extract_path_text(table.c.session_data, "session_name"), "").ilike(
599
+ f"%{session_name}%"
600
+ )
601
+ )
602
+ if session_type is not None:
603
+ session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type
604
+ stmt = stmt.where(table.c.session_type == session_type_value)
605
+
606
+ count_stmt = select(func.count()).select_from(stmt.alias())
607
+ total_count = await sess.scalar(count_stmt) or 0
608
+
609
+ # Sorting
610
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
611
+
612
+ # Paginating
613
+ if limit is not None:
614
+ stmt = stmt.limit(limit)
615
+ if page is not None:
616
+ stmt = stmt.offset((page - 1) * limit)
617
+
618
+ result = await sess.execute(stmt)
619
+ records = result.fetchall()
620
+ if records is None:
621
+ return [], 0
622
+
623
+ session = [dict(record._mapping) for record in records]
624
+ if not deserialize:
625
+ return session, total_count
626
+
627
+ if session_type == SessionType.AGENT:
628
+ return [AgentSession.from_dict(record) for record in session] # type: ignore
629
+ elif session_type == SessionType.TEAM:
630
+ return [TeamSession.from_dict(record) for record in session] # type: ignore
631
+ elif session_type == SessionType.WORKFLOW:
632
+ return [WorkflowSession.from_dict(record) for record in session] # type: ignore
633
+ else:
634
+ raise ValueError(f"Invalid session type: {session_type}")
635
+
636
+ except Exception as e:
637
+ log_error(f"Exception reading from session table: {e}")
638
+ return [] if deserialize else ([], 0)
639
+
640
+ async def rename_session(
641
+ self, session_id: str, session_type: SessionType, session_name: str, deserialize: Optional[bool] = True
642
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
643
+ """
644
+ Rename a session in the database.
645
+
646
+ Args:
647
+ session_id (str): The ID of the session to rename.
648
+ session_type (SessionType): The type of session to rename.
649
+ session_name (str): The new name for the session.
650
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
651
+
652
+ Returns:
653
+ Optional[Union[Session, Dict[str, Any]]]:
654
+ - When deserialize=True: Session object
655
+ - When deserialize=False: Session dictionary
656
+
657
+ Raises:
658
+ Exception: If an error occurs during renaming.
659
+ """
660
+ try:
661
+ table = await self._get_table(table_type="sessions")
662
+
663
+ async with self.async_session_factory() as sess, sess.begin():
664
+ stmt = (
665
+ update(table)
666
+ .where(table.c.session_id == session_id)
667
+ .where(table.c.session_type == session_type.value)
668
+ .values(
669
+ session_data=func.cast(
670
+ func.jsonb_set(
671
+ func.cast(table.c.session_data, postgresql.JSONB),
672
+ text("'{session_name}'"),
673
+ func.to_jsonb(session_name),
674
+ ),
675
+ postgresql.JSON,
676
+ )
677
+ )
678
+ .returning(*table.c)
679
+ )
680
+ result = await sess.execute(stmt)
681
+ row = result.fetchone()
682
+ if not row:
683
+ return None
684
+
685
+ log_debug(f"Renamed session with id '{session_id}' to '{session_name}'")
686
+
687
+ session = dict(row._mapping)
688
+ if not deserialize:
689
+ return session
690
+
691
+ # Return the appropriate session type
692
+ if session_type == SessionType.AGENT:
693
+ return AgentSession.from_dict(session)
694
+ elif session_type == SessionType.TEAM:
695
+ return TeamSession.from_dict(session)
696
+ elif session_type == SessionType.WORKFLOW:
697
+ return WorkflowSession.from_dict(session)
698
+ else:
699
+ raise ValueError(f"Invalid session type: {session_type}")
700
+
701
+ except Exception as e:
702
+ log_error(f"Exception renaming session: {e}")
703
+ return None
704
+
705
+ async def upsert_session(
706
+ self, session: Session, deserialize: Optional[bool] = True
707
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
708
+ """
709
+ Insert or update a session in the database.
710
+
711
+ Args:
712
+ session (Session): The session data to upsert.
713
+ deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True.
714
+
715
+ Returns:
716
+ Optional[Union[Session, Dict[str, Any]]]:
717
+ - When deserialize=True: Session object
718
+ - When deserialize=False: Session dictionary
719
+
720
+ Raises:
721
+ Exception: If an error occurs during upsert.
722
+ """
723
+ try:
724
+ table = await self._get_table(table_type="sessions", create_table_if_not_found=True)
725
+ session_dict = session.to_dict()
726
+
727
+ if isinstance(session, AgentSession):
728
+ async with self.async_session_factory() as sess, sess.begin():
729
+ stmt = postgresql.insert(table).values(
730
+ session_id=session_dict.get("session_id"),
731
+ session_type=SessionType.AGENT.value,
732
+ agent_id=session_dict.get("agent_id"),
733
+ user_id=session_dict.get("user_id"),
734
+ runs=session_dict.get("runs"),
735
+ agent_data=session_dict.get("agent_data"),
736
+ session_data=session_dict.get("session_data"),
737
+ summary=session_dict.get("summary"),
738
+ metadata=session_dict.get("metadata"),
739
+ created_at=session_dict.get("created_at"),
740
+ updated_at=session_dict.get("created_at"),
741
+ )
742
+ stmt = stmt.on_conflict_do_update( # type: ignore
743
+ index_elements=["session_id"],
744
+ set_=dict(
745
+ agent_id=session_dict.get("agent_id"),
746
+ user_id=session_dict.get("user_id"),
747
+ agent_data=session_dict.get("agent_data"),
748
+ session_data=session_dict.get("session_data"),
749
+ summary=session_dict.get("summary"),
750
+ metadata=session_dict.get("metadata"),
751
+ runs=session_dict.get("runs"),
752
+ updated_at=int(time.time()),
753
+ ),
754
+ ).returning(table)
755
+ result = await sess.execute(stmt)
756
+ row = result.fetchone()
757
+ if row is None:
758
+ return None
759
+ session_dict = dict(row._mapping)
760
+
761
+ log_debug(f"Upserted agent session with id '{session_dict.get('session_id')}'")
762
+
763
+ if not deserialize:
764
+ return session_dict
765
+ return AgentSession.from_dict(session_dict)
766
+
767
+ elif isinstance(session, TeamSession):
768
+ async with self.async_session_factory() as sess, sess.begin():
769
+ stmt = postgresql.insert(table).values(
770
+ session_id=session_dict.get("session_id"),
771
+ session_type=SessionType.TEAM.value,
772
+ team_id=session_dict.get("team_id"),
773
+ user_id=session_dict.get("user_id"),
774
+ runs=session_dict.get("runs"),
775
+ team_data=session_dict.get("team_data"),
776
+ session_data=session_dict.get("session_data"),
777
+ summary=session_dict.get("summary"),
778
+ metadata=session_dict.get("metadata"),
779
+ created_at=session_dict.get("created_at"),
780
+ updated_at=session_dict.get("created_at"),
781
+ )
782
+ stmt = stmt.on_conflict_do_update( # type: ignore
783
+ index_elements=["session_id"],
784
+ set_=dict(
785
+ team_id=session_dict.get("team_id"),
786
+ user_id=session_dict.get("user_id"),
787
+ team_data=session_dict.get("team_data"),
788
+ session_data=session_dict.get("session_data"),
789
+ summary=session_dict.get("summary"),
790
+ metadata=session_dict.get("metadata"),
791
+ runs=session_dict.get("runs"),
792
+ updated_at=int(time.time()),
793
+ ),
794
+ ).returning(table)
795
+ result = await sess.execute(stmt)
796
+ row = result.fetchone()
797
+ if row is None:
798
+ return None
799
+ session_dict = dict(row._mapping)
800
+
801
+ log_debug(f"Upserted team session with id '{session_dict.get('session_id')}'")
802
+
803
+ if not deserialize:
804
+ return session_dict
805
+ return TeamSession.from_dict(session_dict)
806
+
807
+ elif isinstance(session, WorkflowSession):
808
+ async with self.async_session_factory() as sess, sess.begin():
809
+ stmt = postgresql.insert(table).values(
810
+ session_id=session_dict.get("session_id"),
811
+ session_type=SessionType.WORKFLOW.value,
812
+ workflow_id=session_dict.get("workflow_id"),
813
+ user_id=session_dict.get("user_id"),
814
+ runs=session_dict.get("runs"),
815
+ workflow_data=session_dict.get("workflow_data"),
816
+ session_data=session_dict.get("session_data"),
817
+ summary=session_dict.get("summary"),
818
+ metadata=session_dict.get("metadata"),
819
+ created_at=session_dict.get("created_at"),
820
+ updated_at=session_dict.get("created_at"),
821
+ )
822
+ stmt = stmt.on_conflict_do_update( # type: ignore
823
+ index_elements=["session_id"],
824
+ set_=dict(
825
+ workflow_id=session_dict.get("workflow_id"),
826
+ user_id=session_dict.get("user_id"),
827
+ workflow_data=session_dict.get("workflow_data"),
828
+ session_data=session_dict.get("session_data"),
829
+ summary=session_dict.get("summary"),
830
+ metadata=session_dict.get("metadata"),
831
+ runs=session_dict.get("runs"),
832
+ updated_at=int(time.time()),
833
+ ),
834
+ ).returning(table)
835
+ result = await sess.execute(stmt)
836
+ row = result.fetchone()
837
+ if row is None:
838
+ return None
839
+ session_dict = dict(row._mapping)
840
+
841
+ log_debug(f"Upserted workflow session with id '{session_dict.get('session_id')}'")
842
+
843
+ if not deserialize:
844
+ return session_dict
845
+ return WorkflowSession.from_dict(session_dict)
846
+
847
+ else:
848
+ raise ValueError(f"Invalid session type: {session.session_type}")
849
+
850
+ except Exception as e:
851
+ log_error(f"Exception upserting into sessions table: {e}")
852
+ return None
853
+
854
+ # -- Memory methods --
855
+ async def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None):
856
+ """Delete a user memory from the database.
857
+
858
+ Returns:
859
+ bool: True if deletion was successful, False otherwise.
860
+
861
+ Raises:
862
+ Exception: If an error occurs during deletion.
863
+ """
864
+ try:
865
+ table = await self._get_table(table_type="memories")
866
+
867
+ async with self.async_session_factory() as sess, sess.begin():
868
+ delete_stmt = table.delete().where(table.c.memory_id == memory_id)
869
+ if user_id is not None:
870
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
871
+ result = await sess.execute(delete_stmt)
872
+
873
+ success = result.rowcount > 0 # type: ignore
874
+ if success:
875
+ log_debug(f"Successfully deleted user memory id: {memory_id}")
876
+ else:
877
+ log_debug(f"No user memory found with id: {memory_id}")
878
+
879
+ except Exception as e:
880
+ log_error(f"Error deleting user memory: {e}")
881
+
882
+ async def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None:
883
+ """Delete user memories from the database.
884
+
885
+ Args:
886
+ memory_ids (List[str]): The IDs of the memories to delete.
887
+
888
+ Raises:
889
+ Exception: If an error occurs during deletion.
890
+ """
891
+ try:
892
+ table = await self._get_table(table_type="memories")
893
+
894
+ async with self.async_session_factory() as sess, sess.begin():
895
+ delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids))
896
+
897
+ if user_id is not None:
898
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
899
+
900
+ result = await sess.execute(delete_stmt)
901
+
902
+ if result.rowcount == 0: # type: ignore
903
+ log_debug(f"No user memories found with ids: {memory_ids}")
904
+ else:
905
+ log_debug(f"Successfully deleted {result.rowcount} user memories") # type: ignore
906
+
907
+ except Exception as e:
908
+ log_error(f"Error deleting user memories: {e}")
909
+
910
+ async def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]:
911
+ """Get all memory topics from the database.
912
+
913
+ Args:
914
+ user_id (Optional[str]): The ID of the user to filter by.
915
+
916
+ Returns:
917
+ List[str]: List of memory topics.
918
+ """
919
+ try:
920
+ table = await self._get_table(table_type="memories")
921
+
922
+ async with self.async_session_factory() as sess, sess.begin():
923
+ try:
924
+ stmt = select(func.jsonb_array_elements_text(table.c.topics))
925
+ if user_id is not None:
926
+ stmt = stmt.where(table.c.user_id == user_id)
927
+ result = await sess.execute(stmt)
928
+ except ProgrammingError:
929
+ # Retrying with json_array_elements_text. This works in older versions,
930
+ # where the topics column was of type JSON instead of JSONB
931
+ stmt = select(func.json_array_elements_text(table.c.topics))
932
+ if user_id is not None:
933
+ stmt = stmt.where(table.c.user_id == user_id)
934
+ result = await sess.execute(stmt)
935
+
936
+ records = result.fetchall()
937
+
938
+ return list(set([record[0] for record in records]))
939
+
940
+ except Exception as e:
941
+ log_error(f"Exception reading from memory table: {e}")
942
+ return []
943
+
944
+ async def get_user_memory(
945
+ self,
946
+ memory_id: str,
947
+ deserialize: Optional[bool] = True,
948
+ user_id: Optional[str] = None,
949
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
950
+ """Get a memory from the database.
951
+
952
+ Args:
953
+ memory_id (str): The ID of the memory to get.
954
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
955
+ user_id (Optional[str]): The ID of the user to filter by.
956
+
957
+ Returns:
958
+ Union[UserMemory, Dict[str, Any], None]:
959
+ - When deserialize=True: UserMemory object
960
+ - When deserialize=False: UserMemory dictionary
961
+
962
+ Raises:
963
+ Exception: If an error occurs during retrieval.
964
+ """
965
+ try:
966
+ table = await self._get_table(table_type="memories")
967
+
968
+ async with self.async_session_factory() as sess, sess.begin():
969
+ stmt = select(table).where(table.c.memory_id == memory_id)
970
+ if user_id is not None:
971
+ stmt = stmt.where(table.c.user_id == user_id)
972
+
973
+ result = await sess.execute(stmt)
974
+ row = result.fetchone()
975
+ if not row:
976
+ return None
977
+
978
+ memory_raw = dict(row._mapping)
979
+ if not deserialize:
980
+ return memory_raw
981
+
982
+ return UserMemory.from_dict(memory_raw)
983
+
984
+ except Exception as e:
985
+ log_error(f"Exception reading from memory table: {e}")
986
+ return None
987
+
988
+ async def get_user_memories(
989
+ self,
990
+ user_id: Optional[str] = None,
991
+ agent_id: Optional[str] = None,
992
+ team_id: Optional[str] = None,
993
+ topics: Optional[List[str]] = None,
994
+ search_content: Optional[str] = None,
995
+ limit: Optional[int] = None,
996
+ page: Optional[int] = None,
997
+ sort_by: Optional[str] = None,
998
+ sort_order: Optional[str] = None,
999
+ deserialize: Optional[bool] = True,
1000
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1001
+ """Get all memories from the database as UserMemory objects.
1002
+
1003
+ Args:
1004
+ user_id (Optional[str]): The ID of the user to filter by.
1005
+ agent_id (Optional[str]): The ID of the agent to filter by.
1006
+ team_id (Optional[str]): The ID of the team to filter by.
1007
+ topics (Optional[List[str]]): The topics to filter by.
1008
+ search_content (Optional[str]): The content to search for.
1009
+ limit (Optional[int]): The maximum number of memories to return.
1010
+ page (Optional[int]): The page number.
1011
+ sort_by (Optional[str]): The column to sort by.
1012
+ sort_order (Optional[str]): The order to sort by.
1013
+ deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True.
1014
+
1015
+ Returns:
1016
+ Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1017
+ - When deserialize=True: List of UserMemory objects
1018
+ - When deserialize=False: Tuple of (memory dictionaries, total count)
1019
+
1020
+ Raises:
1021
+ Exception: If an error occurs during retrieval.
1022
+ """
1023
+ try:
1024
+ table = await self._get_table(table_type="memories")
1025
+
1026
+ async with self.async_session_factory() as sess, sess.begin():
1027
+ stmt = select(table)
1028
+ # Filtering
1029
+ if user_id is not None:
1030
+ stmt = stmt.where(table.c.user_id == user_id)
1031
+ if agent_id is not None:
1032
+ stmt = stmt.where(table.c.agent_id == agent_id)
1033
+ if team_id is not None:
1034
+ stmt = stmt.where(table.c.team_id == team_id)
1035
+ if topics is not None:
1036
+ for topic in topics:
1037
+ stmt = stmt.where(func.cast(table.c.topics, String).like(f'%"{topic}"%'))
1038
+ if search_content is not None:
1039
+ stmt = stmt.where(func.cast(table.c.memory, postgresql.TEXT).ilike(f"%{search_content}%"))
1040
+
1041
+ # Get total count after applying filtering
1042
+ count_stmt = select(func.count()).select_from(stmt.alias())
1043
+ total_count = await sess.scalar(count_stmt) or 0
1044
+
1045
+ # Sorting
1046
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1047
+
1048
+ # Paginating
1049
+ if limit is not None:
1050
+ stmt = stmt.limit(limit)
1051
+ if page is not None:
1052
+ stmt = stmt.offset((page - 1) * limit)
1053
+
1054
+ result = await sess.execute(stmt)
1055
+ records = result.fetchall()
1056
+ if not records:
1057
+ return [] if deserialize else ([], 0)
1058
+
1059
+ memories_raw = [dict(record._mapping) for record in records]
1060
+ if not deserialize:
1061
+ return memories_raw, total_count
1062
+
1063
+ return [UserMemory.from_dict(record) for record in memories_raw]
1064
+
1065
+ except Exception as e:
1066
+ log_error(f"Exception reading from memory table: {e}")
1067
+ return [] if deserialize else ([], 0)
1068
+
1069
+ async def clear_memories(self) -> None:
1070
+ """Delete all memories from the database.
1071
+
1072
+ Raises:
1073
+ Exception: If an error occurs during deletion.
1074
+ """
1075
+ try:
1076
+ table = await self._get_table(table_type="memories")
1077
+
1078
+ async with self.async_session_factory() as sess, sess.begin():
1079
+ await sess.execute(table.delete())
1080
+
1081
+ except Exception as e:
1082
+ log_warning(f"Exception deleting all memories: {e}")
1083
+
1084
+ # -- Cultural Knowledge methods --
1085
+ async def clear_cultural_knowledge(self) -> None:
1086
+ """Delete all cultural knowledge from the database.
1087
+
1088
+ Raises:
1089
+ Exception: If an error occurs during deletion.
1090
+ """
1091
+ try:
1092
+ table = await self._get_table(table_type="culture")
1093
+
1094
+ async with self.async_session_factory() as sess, sess.begin():
1095
+ await sess.execute(table.delete())
1096
+
1097
+ except Exception as e:
1098
+ log_error(f"Exception deleting all cultural knowledge: {e}")
1099
+
1100
+ async def delete_cultural_knowledge(self, id: str) -> None:
1101
+ """Delete cultural knowledge by ID.
1102
+
1103
+ Args:
1104
+ id (str): The ID of the cultural knowledge to delete.
1105
+
1106
+ Raises:
1107
+ Exception: If an error occurs during deletion.
1108
+ """
1109
+ try:
1110
+ table = await self._get_table(table_type="culture")
1111
+
1112
+ async with self.async_session_factory() as sess, sess.begin():
1113
+ stmt = table.delete().where(table.c.id == id)
1114
+ await sess.execute(stmt)
1115
+
1116
+ except Exception as e:
1117
+ log_error(f"Exception deleting cultural knowledge: {e}")
1118
+
1119
+ async def get_cultural_knowledge(
1120
+ self, id: str, deserialize: Optional[bool] = True
1121
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
1122
+ """Get cultural knowledge by ID.
1123
+
1124
+ Args:
1125
+ id (str): The ID of the cultural knowledge to retrieve.
1126
+ deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True.
1127
+
1128
+ Returns:
1129
+ Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise.
1130
+
1131
+ Raises:
1132
+ Exception: If an error occurs during retrieval.
1133
+ """
1134
+ try:
1135
+ table = await self._get_table(table_type="culture")
1136
+
1137
+ async with self.async_session_factory() as sess:
1138
+ stmt = select(table).where(table.c.id == id)
1139
+ result = await sess.execute(stmt)
1140
+ row = result.fetchone()
1141
+
1142
+ if row is None:
1143
+ return None
1144
+
1145
+ db_row = dict(row._mapping)
1146
+
1147
+ if not deserialize:
1148
+ return db_row
1149
+
1150
+ return deserialize_cultural_knowledge(db_row)
1151
+
1152
+ except Exception as e:
1153
+ log_error(f"Exception reading cultural knowledge: {e}")
1154
+ return None
1155
+
1156
+ async def get_all_cultural_knowledge(
1157
+ self,
1158
+ agent_id: Optional[str] = None,
1159
+ team_id: Optional[str] = None,
1160
+ name: Optional[str] = None,
1161
+ limit: Optional[int] = None,
1162
+ page: Optional[int] = None,
1163
+ sort_by: Optional[str] = None,
1164
+ sort_order: Optional[str] = None,
1165
+ deserialize: Optional[bool] = True,
1166
+ ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
1167
+ """Get all cultural knowledge with filtering and pagination.
1168
+
1169
+ Args:
1170
+ agent_id (Optional[str]): Filter by agent ID.
1171
+ team_id (Optional[str]): Filter by team ID.
1172
+ name (Optional[str]): Filter by name (case-insensitive partial match).
1173
+ limit (Optional[int]): Maximum number of results to return.
1174
+ page (Optional[int]): Page number for pagination.
1175
+ sort_by (Optional[str]): Field to sort by.
1176
+ sort_order (Optional[str]): Sort order ('asc' or 'desc').
1177
+ deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True.
1178
+
1179
+ Returns:
1180
+ Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
1181
+ - When deserialize=True: List of CulturalKnowledge objects
1182
+ - When deserialize=False: Tuple with list of dictionaries and total count
1183
+
1184
+ Raises:
1185
+ Exception: If an error occurs during retrieval.
1186
+ """
1187
+ try:
1188
+ table = await self._get_table(table_type="culture", create_table_if_not_found=True)
1189
+
1190
+ async with self.async_session_factory() as sess:
1191
+ # Build query with filters
1192
+ stmt = select(table)
1193
+ if agent_id is not None:
1194
+ stmt = stmt.where(table.c.agent_id == agent_id)
1195
+ if team_id is not None:
1196
+ stmt = stmt.where(table.c.team_id == team_id)
1197
+ if name is not None:
1198
+ stmt = stmt.where(table.c.name.ilike(f"%{name}%"))
1199
+
1200
+ # Get total count
1201
+ count_stmt = select(func.count()).select_from(stmt.alias())
1202
+ total_count_result = await sess.execute(count_stmt)
1203
+ total_count = total_count_result.scalar() or 0
1204
+
1205
+ # Apply sorting
1206
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1207
+
1208
+ # Apply pagination
1209
+ if limit is not None:
1210
+ stmt = stmt.limit(limit)
1211
+ if page is not None:
1212
+ stmt = stmt.offset((page - 1) * limit)
1213
+
1214
+ # Execute query
1215
+ result = await sess.execute(stmt)
1216
+ rows = result.fetchall()
1217
+
1218
+ db_rows = [dict(row._mapping) for row in rows]
1219
+
1220
+ if not deserialize:
1221
+ return db_rows, total_count
1222
+
1223
+ return [deserialize_cultural_knowledge(row) for row in db_rows]
1224
+
1225
+ except Exception as e:
1226
+ log_error(f"Exception reading all cultural knowledge: {e}")
1227
+ return [] if deserialize else ([], 0)
1228
+
1229
+ async def upsert_cultural_knowledge(
1230
+ self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True
1231
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
1232
+ """Upsert cultural knowledge in the database.
1233
+
1234
+ Args:
1235
+ cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert.
1236
+ deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True.
1237
+
1238
+ Returns:
1239
+ Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge.
1240
+
1241
+ Raises:
1242
+ Exception: If an error occurs during upsert.
1243
+ """
1244
+ try:
1245
+ table = await self._get_table(table_type="culture", create_table_if_not_found=True)
1246
+
1247
+ # Generate ID if not present
1248
+ if cultural_knowledge.id is None:
1249
+ cultural_knowledge.id = str(uuid4())
1250
+
1251
+ # Serialize content, categories, and notes into a JSON dict for DB storage
1252
+ content_dict = serialize_cultural_knowledge(cultural_knowledge)
1253
+
1254
+ async with self.async_session_factory() as sess, sess.begin():
1255
+ # Use PostgreSQL-specific insert with on_conflict_do_update
1256
+ insert_stmt = postgresql.insert(table).values(
1257
+ id=cultural_knowledge.id,
1258
+ name=cultural_knowledge.name,
1259
+ summary=cultural_knowledge.summary,
1260
+ content=content_dict if content_dict else None,
1261
+ metadata=cultural_knowledge.metadata,
1262
+ input=cultural_knowledge.input,
1263
+ created_at=cultural_knowledge.created_at,
1264
+ updated_at=int(time.time()),
1265
+ agent_id=cultural_knowledge.agent_id,
1266
+ team_id=cultural_knowledge.team_id,
1267
+ )
1268
+
1269
+ # Update all fields except id on conflict
1270
+ update_dict = {
1271
+ "name": cultural_knowledge.name,
1272
+ "summary": cultural_knowledge.summary,
1273
+ "content": content_dict if content_dict else None,
1274
+ "metadata": cultural_knowledge.metadata,
1275
+ "input": cultural_knowledge.input,
1276
+ "updated_at": int(time.time()),
1277
+ "agent_id": cultural_knowledge.agent_id,
1278
+ "team_id": cultural_knowledge.team_id,
1279
+ }
1280
+ upsert_stmt = insert_stmt.on_conflict_do_update(index_elements=["id"], set_=update_dict).returning(
1281
+ table
1282
+ )
1283
+
1284
+ result = await sess.execute(upsert_stmt)
1285
+ row = result.fetchone()
1286
+
1287
+ if row is None:
1288
+ return None
1289
+
1290
+ db_row = dict(row._mapping)
1291
+
1292
+ if not deserialize:
1293
+ return db_row
1294
+
1295
+ # Deserialize from DB format to model format
1296
+ return deserialize_cultural_knowledge(db_row)
1297
+
1298
+ except Exception as e:
1299
+ log_warning(f"Exception upserting cultural knowledge: {e}")
1300
+ raise e
1301
+
1302
+ async def get_user_memory_stats(
1303
+ self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None
1304
+ ) -> Tuple[List[Dict[str, Any]], int]:
1305
+ """Get user memories stats.
1306
+
1307
+ Args:
1308
+ limit (Optional[int]): The maximum number of user stats to return.
1309
+ page (Optional[int]): The page number.
1310
+ user_id (Optional[str]): User ID for filtering.
1311
+
1312
+ Returns:
1313
+ Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count.
1314
+
1315
+ Example:
1316
+ (
1317
+ [
1318
+ {
1319
+ "user_id": "123",
1320
+ "total_memories": 10,
1321
+ "last_memory_updated_at": 1714560000,
1322
+ },
1323
+ ],
1324
+ total_count: 1,
1325
+ )
1326
+ """
1327
+ try:
1328
+ table = await self._get_table(table_type="memories")
1329
+
1330
+ async with self.async_session_factory() as sess, sess.begin():
1331
+ stmt = select(
1332
+ table.c.user_id,
1333
+ func.count(table.c.memory_id).label("total_memories"),
1334
+ func.max(table.c.updated_at).label("last_memory_updated_at"),
1335
+ )
1336
+
1337
+ if user_id is not None:
1338
+ stmt = stmt.where(table.c.user_id == user_id)
1339
+ else:
1340
+ stmt = stmt.where(table.c.user_id.is_not(None))
1341
+ stmt = stmt.group_by(table.c.user_id)
1342
+ stmt = stmt.order_by(func.max(table.c.updated_at).desc())
1343
+
1344
+ count_stmt = select(func.count()).select_from(stmt.alias())
1345
+ total_count = await sess.scalar(count_stmt) or 0
1346
+
1347
+ # Pagination
1348
+ if limit is not None:
1349
+ stmt = stmt.limit(limit)
1350
+ if page is not None:
1351
+ stmt = stmt.offset((page - 1) * limit)
1352
+
1353
+ result = await sess.execute(stmt)
1354
+ records = result.fetchall()
1355
+ if not records:
1356
+ return [], 0
1357
+
1358
+ return [
1359
+ {
1360
+ "user_id": record.user_id, # type: ignore
1361
+ "total_memories": record.total_memories,
1362
+ "last_memory_updated_at": record.last_memory_updated_at,
1363
+ }
1364
+ for record in records
1365
+ ], total_count
1366
+
1367
+ except Exception as e:
1368
+ log_error(f"Exception getting user memory stats: {e}")
1369
+ return [], 0
1370
+
1371
+ async def upsert_user_memory(
1372
+ self, memory: UserMemory, deserialize: Optional[bool] = True
1373
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
1374
+ """Upsert a user memory in the database.
1375
+
1376
+ Args:
1377
+ memory (UserMemory): The user memory to upsert.
1378
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1379
+
1380
+ Returns:
1381
+ Optional[Union[UserMemory, Dict[str, Any]]]:
1382
+ - When deserialize=True: UserMemory object
1383
+ - When deserialize=False: UserMemory dictionary
1384
+
1385
+ Raises:
1386
+ Exception: If an error occurs during upsert.
1387
+ """
1388
+ try:
1389
+ table = await self._get_table(table_type="memories", create_table_if_not_found=True)
1390
+
1391
+ current_time = int(time.time())
1392
+
1393
+ async with self.async_session_factory() as sess:
1394
+ async with sess.begin():
1395
+ if memory.memory_id is None:
1396
+ memory.memory_id = str(uuid4())
1397
+
1398
+ stmt = postgresql.insert(table).values(
1399
+ memory_id=memory.memory_id,
1400
+ memory=memory.memory,
1401
+ input=memory.input,
1402
+ user_id=memory.user_id,
1403
+ agent_id=memory.agent_id,
1404
+ team_id=memory.team_id,
1405
+ topics=memory.topics,
1406
+ feedback=memory.feedback,
1407
+ created_at=memory.created_at,
1408
+ updated_at=memory.created_at,
1409
+ )
1410
+ stmt = stmt.on_conflict_do_update( # type: ignore
1411
+ index_elements=["memory_id"],
1412
+ set_=dict(
1413
+ memory=memory.memory,
1414
+ topics=memory.topics,
1415
+ input=memory.input,
1416
+ agent_id=memory.agent_id,
1417
+ team_id=memory.team_id,
1418
+ feedback=memory.feedback,
1419
+ updated_at=current_time,
1420
+ # Preserve created_at on update - don't overwrite existing value
1421
+ created_at=table.c.created_at,
1422
+ ),
1423
+ ).returning(table)
1424
+
1425
+ result = await sess.execute(stmt)
1426
+ row = result.fetchone()
1427
+ if row is None:
1428
+ return None
1429
+
1430
+ memory_raw = dict(row._mapping)
1431
+
1432
+ log_debug(f"Upserted user memory with id '{memory.memory_id}'")
1433
+
1434
+ if not memory_raw or not deserialize:
1435
+ return memory_raw
1436
+
1437
+ return UserMemory.from_dict(memory_raw)
1438
+
1439
+ except Exception as e:
1440
+ log_error(f"Exception upserting user memory: {e}")
1441
+ return None
1442
+
1443
+ # -- Metrics methods --
1444
+ async def _get_all_sessions_for_metrics_calculation(
1445
+ self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
1446
+ ) -> List[Dict[str, Any]]:
1447
+ """
1448
+ Get all sessions of all types (agent, team, workflow) as raw dictionaries.
1449
+
1450
+ Args:
1451
+ start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None.
1452
+ end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None.
1453
+
1454
+ Returns:
1455
+ List[Dict[str, Any]]: List of session dictionaries with session_type field.
1456
+
1457
+ Raises:
1458
+ Exception: If an error occurs during retrieval.
1459
+ """
1460
+ try:
1461
+ table = await self._get_table(table_type="sessions")
1462
+
1463
+ stmt = select(
1464
+ table.c.user_id,
1465
+ table.c.session_data,
1466
+ table.c.runs,
1467
+ table.c.created_at,
1468
+ table.c.session_type,
1469
+ )
1470
+
1471
+ if start_timestamp is not None:
1472
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
1473
+ if end_timestamp is not None:
1474
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
1475
+
1476
+ async with self.async_session_factory() as sess:
1477
+ result = await sess.execute(stmt)
1478
+ records = result.fetchall()
1479
+
1480
+ return [dict(record._mapping) for record in records]
1481
+
1482
+ except Exception as e:
1483
+ log_error(f"Exception reading from sessions table: {e}")
1484
+ return []
1485
+
1486
+ async def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]:
1487
+ """Get the first date for which metrics calculation is needed:
1488
+
1489
+ 1. If there are metrics records, return the date of the first day without a complete metrics record.
1490
+ 2. If there are no metrics records, return the date of the first recorded session.
1491
+ 3. If there are no metrics records and no sessions records, return None.
1492
+
1493
+ Args:
1494
+ table (Table): The table to get the starting date for.
1495
+
1496
+ Returns:
1497
+ Optional[date]: The starting date for which metrics calculation is needed.
1498
+ """
1499
+ async with self.async_session_factory() as sess:
1500
+ stmt = select(table).order_by(table.c.date.desc()).limit(1)
1501
+ result = await sess.execute(stmt)
1502
+ row = result.fetchone()
1503
+
1504
+ # 1. Return the date of the first day without a complete metrics record.
1505
+ if row is not None:
1506
+ if row.completed:
1507
+ return row._mapping["date"] + timedelta(days=1)
1508
+ else:
1509
+ return row._mapping["date"]
1510
+
1511
+ # 2. No metrics records. Return the date of the first recorded session.
1512
+ first_session, _ = await self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False)
1513
+
1514
+ first_session_date = first_session[0]["created_at"] if first_session else None # type: ignore[index]
1515
+
1516
+ # 3. No metrics records and no sessions records. Return None.
1517
+ if first_session_date is None:
1518
+ return None
1519
+
1520
+ return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date()
1521
+
1522
+ async def calculate_metrics(self) -> Optional[list[dict]]:
1523
+ """Calculate metrics for all dates without complete metrics.
1524
+
1525
+ Returns:
1526
+ Optional[list[dict]]: The calculated metrics.
1527
+
1528
+ Raises:
1529
+ Exception: If an error occurs during metrics calculation.
1530
+ """
1531
+ try:
1532
+ table = await self._get_table(table_type="metrics")
1533
+
1534
+ starting_date = await self._get_metrics_calculation_starting_date(table)
1535
+
1536
+ if starting_date is None:
1537
+ log_info("No session data found. Won't calculate metrics.")
1538
+ return None
1539
+
1540
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
1541
+ if not dates_to_process:
1542
+ log_info("Metrics already calculated for all relevant dates.")
1543
+ return None
1544
+
1545
+ start_timestamp = int(
1546
+ datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp()
1547
+ )
1548
+ end_timestamp = int(
1549
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time())
1550
+ .replace(tzinfo=timezone.utc)
1551
+ .timestamp()
1552
+ )
1553
+
1554
+ sessions = await self._get_all_sessions_for_metrics_calculation(
1555
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
1556
+ )
1557
+
1558
+ all_sessions_data = fetch_all_sessions_data(
1559
+ sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp
1560
+ )
1561
+ if not all_sessions_data:
1562
+ log_info("No new session data found. Won't calculate metrics.")
1563
+ return None
1564
+
1565
+ results = []
1566
+ metrics_records = []
1567
+
1568
+ for date_to_process in dates_to_process:
1569
+ date_key = date_to_process.isoformat()
1570
+ sessions_for_date = all_sessions_data.get(date_key, {})
1571
+
1572
+ # Skip dates with no sessions
1573
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
1574
+ continue
1575
+
1576
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
1577
+
1578
+ metrics_records.append(metrics_record)
1579
+
1580
+ if metrics_records:
1581
+ async with self.async_session_factory() as sess, sess.begin():
1582
+ results = await abulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records)
1583
+
1584
+ log_debug("Updated metrics calculations")
1585
+
1586
+ return results
1587
+
1588
+ except Exception as e:
1589
+ log_error(f"Exception refreshing metrics: {e}")
1590
+ return None
1591
+
1592
+ async def get_metrics(
1593
+ self, starting_date: Optional[date] = None, ending_date: Optional[date] = None
1594
+ ) -> Tuple[List[dict], Optional[int]]:
1595
+ """Get all metrics matching the given date range.
1596
+
1597
+ Args:
1598
+ starting_date (Optional[date]): The starting date to filter metrics by.
1599
+ ending_date (Optional[date]): The ending date to filter metrics by.
1600
+
1601
+ Returns:
1602
+ Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update.
1603
+
1604
+ Raises:
1605
+ Exception: If an error occurs during retrieval.
1606
+ """
1607
+ try:
1608
+ table = await self._get_table(table_type="metrics")
1609
+
1610
+ async with self.async_session_factory() as sess, sess.begin():
1611
+ stmt = select(table)
1612
+ if starting_date:
1613
+ stmt = stmt.where(table.c.date >= starting_date)
1614
+ if ending_date:
1615
+ stmt = stmt.where(table.c.date <= ending_date)
1616
+ result = await sess.execute(stmt)
1617
+ records = result.fetchall()
1618
+ if not records:
1619
+ return [], None
1620
+
1621
+ # Get the latest updated_at
1622
+ latest_stmt = select(func.max(table.c.updated_at))
1623
+ latest_result = await sess.execute(latest_stmt)
1624
+ latest_updated_at = latest_result.scalar()
1625
+
1626
+ return [dict(row._mapping) for row in records], latest_updated_at
1627
+
1628
+ except Exception as e:
1629
+ log_warning(f"Exception getting metrics: {e}")
1630
+ return [], None
1631
+
1632
+ # -- Knowledge methods --
1633
+ async def delete_knowledge_content(self, id: str):
1634
+ """Delete a knowledge row from the database.
1635
+
1636
+ Args:
1637
+ id (str): The ID of the knowledge row to delete.
1638
+ """
1639
+ table = await self._get_table(table_type="knowledge")
1640
+
1641
+ try:
1642
+ async with self.async_session_factory() as sess, sess.begin():
1643
+ stmt = table.delete().where(table.c.id == id)
1644
+ await sess.execute(stmt)
1645
+
1646
+ except Exception as e:
1647
+ log_error(f"Exception deleting knowledge content: {e}")
1648
+
1649
+ async def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1650
+ """Get a knowledge row from the database.
1651
+
1652
+ Args:
1653
+ id (str): The ID of the knowledge row to get.
1654
+
1655
+ Returns:
1656
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1657
+ """
1658
+ table = await self._get_table(table_type="knowledge")
1659
+
1660
+ try:
1661
+ async with self.async_session_factory() as sess, sess.begin():
1662
+ stmt = select(table).where(table.c.id == id)
1663
+ result = await sess.execute(stmt)
1664
+ row = result.fetchone()
1665
+ if row is None:
1666
+ return None
1667
+
1668
+ return KnowledgeRow.model_validate(row._mapping)
1669
+
1670
+ except Exception as e:
1671
+ log_error(f"Exception getting knowledge content: {e}")
1672
+ return None
1673
+
1674
+ async def get_knowledge_contents(
1675
+ self,
1676
+ limit: Optional[int] = None,
1677
+ page: Optional[int] = None,
1678
+ sort_by: Optional[str] = None,
1679
+ sort_order: Optional[str] = None,
1680
+ ) -> Tuple[List[KnowledgeRow], int]:
1681
+ """Get all knowledge contents from the database.
1682
+
1683
+ Args:
1684
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1685
+ page (Optional[int]): The page number.
1686
+ sort_by (Optional[str]): The column to sort by.
1687
+ sort_order (Optional[str]): The order to sort by.
1688
+
1689
+ Returns:
1690
+ List[KnowledgeRow]: The knowledge contents.
1691
+
1692
+ Raises:
1693
+ Exception: If an error occurs during retrieval.
1694
+ """
1695
+ table = await self._get_table(table_type="knowledge")
1696
+
1697
+ try:
1698
+ async with self.async_session_factory() as sess, sess.begin():
1699
+ stmt = select(table)
1700
+
1701
+ # Apply sorting
1702
+ if sort_by is not None:
1703
+ stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1))
1704
+
1705
+ # Get total count before applying limit and pagination
1706
+ count_stmt = select(func.count()).select_from(stmt.alias())
1707
+ total_count = await sess.scalar(count_stmt) or 0
1708
+
1709
+ # Apply pagination after count
1710
+ if limit is not None:
1711
+ stmt = stmt.limit(limit)
1712
+ if page is not None:
1713
+ stmt = stmt.offset((page - 1) * limit)
1714
+
1715
+ result = await sess.execute(stmt)
1716
+ records = result.fetchall()
1717
+ return [KnowledgeRow.model_validate(record._mapping) for record in records], total_count
1718
+
1719
+ except Exception as e:
1720
+ log_error(f"Exception getting knowledge contents: {e}")
1721
+ return [], 0
1722
+
1723
+ async def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1724
+ """Upsert knowledge content in the database.
1725
+
1726
+ Args:
1727
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1728
+
1729
+ Returns:
1730
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1731
+ """
1732
+ try:
1733
+ table = await self._get_table(table_type="knowledge", create_table_if_not_found=True)
1734
+ async with self.async_session_factory() as sess, sess.begin():
1735
+ # Get the actual table columns to avoid "unconsumed column names" error
1736
+ table_columns = set(table.columns.keys())
1737
+
1738
+ # Only include fields that exist in the table and are not None
1739
+ insert_data = {}
1740
+ update_fields = {}
1741
+
1742
+ # Map of KnowledgeRow fields to table columns
1743
+ field_mapping = {
1744
+ "id": "id",
1745
+ "name": "name",
1746
+ "description": "description",
1747
+ "metadata": "metadata",
1748
+ "type": "type",
1749
+ "size": "size",
1750
+ "linked_to": "linked_to",
1751
+ "access_count": "access_count",
1752
+ "status": "status",
1753
+ "status_message": "status_message",
1754
+ "created_at": "created_at",
1755
+ "updated_at": "updated_at",
1756
+ "external_id": "external_id",
1757
+ }
1758
+
1759
+ # Build insert and update data only for fields that exist in the table
1760
+ for model_field, table_column in field_mapping.items():
1761
+ if table_column in table_columns:
1762
+ value = getattr(knowledge_row, model_field, None)
1763
+ if value is not None:
1764
+ insert_data[table_column] = value
1765
+ # Don't include ID in update_fields since it's the primary key
1766
+ if table_column != "id":
1767
+ update_fields[table_column] = value
1768
+
1769
+ # Ensure id is always included for the insert
1770
+ if "id" in table_columns and knowledge_row.id:
1771
+ insert_data["id"] = knowledge_row.id
1772
+
1773
+ # Handle case where update_fields is empty (all fields are None or don't exist in table)
1774
+ if not update_fields:
1775
+ # If we have insert_data, just do an insert without conflict resolution
1776
+ if insert_data:
1777
+ stmt = postgresql.insert(table).values(insert_data)
1778
+ await sess.execute(stmt)
1779
+ else:
1780
+ # If we have no data at all, this is an error
1781
+ log_error("No valid fields found for knowledge row upsert")
1782
+ return None
1783
+ else:
1784
+ # Normal upsert with conflict resolution
1785
+ stmt = (
1786
+ postgresql.insert(table)
1787
+ .values(insert_data)
1788
+ .on_conflict_do_update(index_elements=["id"], set_=update_fields)
1789
+ )
1790
+ await sess.execute(stmt)
1791
+
1792
+ log_debug(f"Upserted knowledge row with id '{knowledge_row.id}'")
1793
+
1794
+ return knowledge_row
1795
+
1796
+ except Exception as e:
1797
+ log_error(f"Error upserting knowledge row: {e}")
1798
+ return None
1799
+
1800
+ # -- Eval methods --
1801
+ async def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1802
+ """Create an EvalRunRecord in the database.
1803
+
1804
+ Args:
1805
+ eval_run (EvalRunRecord): The eval run to create.
1806
+
1807
+ Returns:
1808
+ Optional[EvalRunRecord]: The created eval run, or None if the operation fails.
1809
+
1810
+ Raises:
1811
+ Exception: If an error occurs during creation.
1812
+ """
1813
+ try:
1814
+ table = await self._get_table(table_type="evals")
1815
+
1816
+ async with self.async_session_factory() as sess, sess.begin():
1817
+ current_time = int(time.time())
1818
+ stmt = postgresql.insert(table).values(
1819
+ {"created_at": current_time, "updated_at": current_time, **eval_run.model_dump()}
1820
+ )
1821
+ await sess.execute(stmt)
1822
+
1823
+ log_debug(f"Created eval run with id '{eval_run.run_id}'")
1824
+
1825
+ return eval_run
1826
+
1827
+ except Exception as e:
1828
+ log_error(f"Error creating eval run: {e}")
1829
+ return None
1830
+
1831
+ async def delete_eval_run(self, eval_run_id: str) -> None:
1832
+ """Delete an eval run from the database.
1833
+
1834
+ Args:
1835
+ eval_run_id (str): The ID of the eval run to delete.
1836
+ """
1837
+ try:
1838
+ table = await self._get_table(table_type="evals")
1839
+
1840
+ async with self.async_session_factory() as sess, sess.begin():
1841
+ stmt = table.delete().where(table.c.run_id == eval_run_id)
1842
+ result = await sess.execute(stmt)
1843
+
1844
+ if result.rowcount == 0: # type: ignore
1845
+ log_warning(f"No eval run found with ID: {eval_run_id}")
1846
+ else:
1847
+ log_debug(f"Deleted eval run with ID: {eval_run_id}")
1848
+
1849
+ except Exception as e:
1850
+ log_error(f"Error deleting eval run {eval_run_id}: {e}")
1851
+
1852
+ async def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1853
+ """Delete multiple eval runs from the database.
1854
+
1855
+ Args:
1856
+ eval_run_ids (List[str]): List of eval run IDs to delete.
1857
+ """
1858
+ try:
1859
+ table = await self._get_table(table_type="evals")
1860
+
1861
+ async with self.async_session_factory() as sess, sess.begin():
1862
+ stmt = table.delete().where(table.c.run_id.in_(eval_run_ids))
1863
+ result = await sess.execute(stmt)
1864
+
1865
+ if result.rowcount == 0: # type: ignore
1866
+ log_warning(f"No eval runs found with IDs: {eval_run_ids}")
1867
+ else:
1868
+ log_debug(f"Deleted {result.rowcount} eval runs") # type: ignore
1869
+
1870
+ except Exception as e:
1871
+ log_error(f"Error deleting eval runs {eval_run_ids}: {e}")
1872
+
1873
+ async def get_eval_run(
1874
+ self, eval_run_id: str, deserialize: Optional[bool] = True
1875
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1876
+ """Get an eval run from the database.
1877
+
1878
+ Args:
1879
+ eval_run_id (str): The ID of the eval run to get.
1880
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1881
+
1882
+ Returns:
1883
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1884
+ - When deserialize=True: EvalRunRecord object
1885
+ - When deserialize=False: EvalRun dictionary
1886
+
1887
+ Raises:
1888
+ Exception: If an error occurs during retrieval.
1889
+ """
1890
+ try:
1891
+ table = await self._get_table(table_type="evals")
1892
+
1893
+ async with self.async_session_factory() as sess, sess.begin():
1894
+ stmt = select(table).where(table.c.run_id == eval_run_id)
1895
+ result = await sess.execute(stmt)
1896
+ row = result.fetchone()
1897
+ if row is None:
1898
+ return None
1899
+
1900
+ eval_run_raw = dict(row._mapping)
1901
+ if not deserialize:
1902
+ return eval_run_raw
1903
+
1904
+ return EvalRunRecord.model_validate(eval_run_raw)
1905
+
1906
+ except Exception as e:
1907
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
1908
+ return None
1909
+
1910
+ async def get_eval_runs(
1911
+ self,
1912
+ limit: Optional[int] = None,
1913
+ page: Optional[int] = None,
1914
+ sort_by: Optional[str] = None,
1915
+ sort_order: Optional[str] = None,
1916
+ agent_id: Optional[str] = None,
1917
+ team_id: Optional[str] = None,
1918
+ workflow_id: Optional[str] = None,
1919
+ model_id: Optional[str] = None,
1920
+ filter_type: Optional[EvalFilterType] = None,
1921
+ eval_type: Optional[List[EvalType]] = None,
1922
+ deserialize: Optional[bool] = True,
1923
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1924
+ """Get all eval runs from the database.
1925
+
1926
+ Args:
1927
+ limit (Optional[int]): The maximum number of eval runs to return.
1928
+ page (Optional[int]): The page number.
1929
+ sort_by (Optional[str]): The column to sort by.
1930
+ sort_order (Optional[str]): The order to sort by.
1931
+ agent_id (Optional[str]): The ID of the agent to filter by.
1932
+ team_id (Optional[str]): The ID of the team to filter by.
1933
+ workflow_id (Optional[str]): The ID of the workflow to filter by.
1934
+ model_id (Optional[str]): The ID of the model to filter by.
1935
+ eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by.
1936
+ filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow).
1937
+ deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True.
1938
+
1939
+ Returns:
1940
+ Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1941
+ - When deserialize=True: List of EvalRunRecord objects
1942
+ - When deserialize=False: List of dictionaries
1943
+
1944
+ Raises:
1945
+ Exception: If an error occurs during retrieval.
1946
+ """
1947
+ try:
1948
+ table = await self._get_table(table_type="evals")
1949
+
1950
+ async with self.async_session_factory() as sess, sess.begin():
1951
+ stmt = select(table)
1952
+
1953
+ # Filtering
1954
+ if agent_id is not None:
1955
+ stmt = stmt.where(table.c.agent_id == agent_id)
1956
+ if team_id is not None:
1957
+ stmt = stmt.where(table.c.team_id == team_id)
1958
+ if workflow_id is not None:
1959
+ stmt = stmt.where(table.c.workflow_id == workflow_id)
1960
+ if model_id is not None:
1961
+ stmt = stmt.where(table.c.model_id == model_id)
1962
+ if eval_type is not None and len(eval_type) > 0:
1963
+ stmt = stmt.where(table.c.eval_type.in_(eval_type))
1964
+ if filter_type is not None:
1965
+ if filter_type == EvalFilterType.AGENT:
1966
+ stmt = stmt.where(table.c.agent_id.is_not(None))
1967
+ elif filter_type == EvalFilterType.TEAM:
1968
+ stmt = stmt.where(table.c.team_id.is_not(None))
1969
+ elif filter_type == EvalFilterType.WORKFLOW:
1970
+ stmt = stmt.where(table.c.workflow_id.is_not(None))
1971
+
1972
+ # Get total count after applying filtering
1973
+ count_stmt = select(func.count()).select_from(stmt.alias())
1974
+ total_count = await sess.scalar(count_stmt) or 0
1975
+
1976
+ # Sorting
1977
+ if sort_by is None:
1978
+ stmt = stmt.order_by(table.c.created_at.desc())
1979
+ else:
1980
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1981
+
1982
+ # Paginating
1983
+ if limit is not None:
1984
+ stmt = stmt.limit(limit)
1985
+ if page is not None:
1986
+ stmt = stmt.offset((page - 1) * limit)
1987
+
1988
+ result = await sess.execute(stmt)
1989
+ records = result.fetchall()
1990
+ if not records:
1991
+ return [] if deserialize else ([], 0)
1992
+
1993
+ eval_runs_raw = [dict(row._mapping) for row in records]
1994
+ if not deserialize:
1995
+ return eval_runs_raw, total_count
1996
+
1997
+ return [EvalRunRecord.model_validate(row) for row in eval_runs_raw]
1998
+
1999
+ except Exception as e:
2000
+ log_error(f"Exception getting eval runs: {e}")
2001
+ return [] if deserialize else ([], 0)
2002
+
2003
+ async def rename_eval_run(
2004
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
2005
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
2006
+ """Upsert the name of an eval run in the database, returning raw dictionary.
2007
+
2008
+ Args:
2009
+ eval_run_id (str): The ID of the eval run to update.
2010
+ name (str): The new name of the eval run.
2011
+
2012
+ Returns:
2013
+ Optional[Dict[str, Any]]: The updated eval run, or None if the operation fails.
2014
+
2015
+ Raises:
2016
+ Exception: If an error occurs during update.
2017
+ """
2018
+ try:
2019
+ table = await self._get_table(table_type="evals")
2020
+ async with self.async_session_factory() as sess, sess.begin():
2021
+ stmt = (
2022
+ table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time()))
2023
+ )
2024
+ await sess.execute(stmt)
2025
+
2026
+ eval_run_raw = await self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize)
2027
+ if not eval_run_raw or not deserialize:
2028
+ return eval_run_raw
2029
+
2030
+ return EvalRunRecord.model_validate(eval_run_raw)
2031
+
2032
+ except Exception as e:
2033
+ log_error(f"Error upserting eval run name {eval_run_id}: {e}")
2034
+ return None
2035
+
2036
+ # -- Migrations --
2037
+
2038
+ async def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str):
2039
+ """Migrate all content in the given table to the right v2 table"""
2040
+
2041
+ from agno.db.migrations.v1_to_v2 import (
2042
+ get_all_table_content,
2043
+ parse_agent_sessions,
2044
+ parse_memories,
2045
+ parse_team_sessions,
2046
+ parse_workflow_sessions,
2047
+ )
2048
+
2049
+ # Get all content from the old table
2050
+ old_content: list[dict[str, Any]] = get_all_table_content(
2051
+ db=self,
2052
+ db_schema=v1_db_schema,
2053
+ table_name=v1_table_name,
2054
+ )
2055
+ if not old_content:
2056
+ log_info(f"No content to migrate from table {v1_table_name}")
2057
+ return
2058
+
2059
+ # Parse the content into the new format
2060
+ memories: List[UserMemory] = []
2061
+ sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = []
2062
+ if v1_table_type == "agent_sessions":
2063
+ sessions = parse_agent_sessions(old_content)
2064
+ elif v1_table_type == "team_sessions":
2065
+ sessions = parse_team_sessions(old_content)
2066
+ elif v1_table_type == "workflow_sessions":
2067
+ sessions = parse_workflow_sessions(old_content)
2068
+ elif v1_table_type == "memories":
2069
+ memories = parse_memories(old_content)
2070
+ else:
2071
+ raise ValueError(f"Invalid table type: {v1_table_type}")
2072
+
2073
+ # Insert the new content into the new table
2074
+ if v1_table_type == "agent_sessions":
2075
+ for session in sessions:
2076
+ await self.upsert_session(session)
2077
+ log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table}")
2078
+
2079
+ elif v1_table_type == "team_sessions":
2080
+ for session in sessions:
2081
+ await self.upsert_session(session)
2082
+ log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table}")
2083
+
2084
+ elif v1_table_type == "workflow_sessions":
2085
+ for session in sessions:
2086
+ await self.upsert_session(session)
2087
+ log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table}")
2088
+
2089
+ elif v1_table_type == "memories":
2090
+ for memory in memories:
2091
+ await self.upsert_user_memory(memory)
2092
+ log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}")
2093
+
2094
+ # --- Traces ---
2095
+ def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None):
2096
+ """Build base query for traces with aggregated span counts.
2097
+
2098
+ Args:
2099
+ table: The traces table.
2100
+ spans_table: The spans table (optional).
2101
+
2102
+ Returns:
2103
+ SQLAlchemy select statement with total_spans and error_count calculated dynamically.
2104
+ """
2105
+ from sqlalchemy import case, literal
2106
+
2107
+ if spans_table is not None:
2108
+ # JOIN with spans table to calculate total_spans and error_count
2109
+ return (
2110
+ select(
2111
+ table,
2112
+ func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"),
2113
+ func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label(
2114
+ "error_count"
2115
+ ),
2116
+ )
2117
+ .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id))
2118
+ .group_by(table.c.trace_id)
2119
+ )
2120
+ else:
2121
+ # Fallback if spans table doesn't exist
2122
+ return select(table, literal(0).label("total_spans"), literal(0).label("error_count"))
2123
+
2124
+ def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col):
2125
+ """Build a SQL CASE expression that returns the component level for a trace.
2126
+
2127
+ Component levels (higher = more important):
2128
+ - 3: Workflow root (.run or .arun with workflow_id)
2129
+ - 2: Team root (.run or .arun with team_id)
2130
+ - 1: Agent root (.run or .arun with agent_id)
2131
+ - 0: Child span (not a root)
2132
+
2133
+ Args:
2134
+ workflow_id_col: SQL column/expression for workflow_id
2135
+ team_id_col: SQL column/expression for team_id
2136
+ agent_id_col: SQL column/expression for agent_id
2137
+ name_col: SQL column/expression for name
2138
+
2139
+ Returns:
2140
+ SQLAlchemy CASE expression returning the component level as an integer.
2141
+ """
2142
+ is_root_name = or_(name_col.contains(".run"), name_col.contains(".arun"))
2143
+
2144
+ return case(
2145
+ # Workflow root (level 3)
2146
+ (and_(workflow_id_col.isnot(None), is_root_name), 3),
2147
+ # Team root (level 2)
2148
+ (and_(team_id_col.isnot(None), is_root_name), 2),
2149
+ # Agent root (level 1)
2150
+ (and_(agent_id_col.isnot(None), is_root_name), 1),
2151
+ # Child span or unknown (level 0)
2152
+ else_=0,
2153
+ )
2154
+
2155
+ async def upsert_trace(self, trace: "Trace") -> None:
2156
+ """Create or update a single trace record in the database.
2157
+
2158
+ Uses INSERT ... ON CONFLICT DO UPDATE (upsert) to handle concurrent inserts
2159
+ atomically and avoid race conditions.
2160
+
2161
+ Args:
2162
+ trace: The Trace object to store (one per trace_id).
2163
+ """
2164
+ try:
2165
+ table = await self._get_table(table_type="traces", create_table_if_not_found=True)
2166
+
2167
+ trace_dict = trace.to_dict()
2168
+ trace_dict.pop("total_spans", None)
2169
+ trace_dict.pop("error_count", None)
2170
+
2171
+ async with self.async_session_factory() as sess, sess.begin():
2172
+ # Use upsert to handle concurrent inserts atomically
2173
+ # On conflict, update fields while preserving existing non-null context values
2174
+ # and keeping the earliest start_time
2175
+ insert_stmt = postgresql.insert(table).values(trace_dict)
2176
+
2177
+ # Build component level expressions for comparing trace priority
2178
+ new_level = self._get_trace_component_level_expr(
2179
+ insert_stmt.excluded.workflow_id,
2180
+ insert_stmt.excluded.team_id,
2181
+ insert_stmt.excluded.agent_id,
2182
+ insert_stmt.excluded.name,
2183
+ )
2184
+ existing_level = self._get_trace_component_level_expr(
2185
+ table.c.workflow_id,
2186
+ table.c.team_id,
2187
+ table.c.agent_id,
2188
+ table.c.name,
2189
+ )
2190
+
2191
+ # Build the ON CONFLICT DO UPDATE clause
2192
+ # Use LEAST for start_time, GREATEST for end_time to capture full trace duration
2193
+ # Use COALESCE to preserve existing non-null context values
2194
+ upsert_stmt = insert_stmt.on_conflict_do_update(
2195
+ index_elements=["trace_id"],
2196
+ set_={
2197
+ "end_time": func.greatest(table.c.end_time, insert_stmt.excluded.end_time),
2198
+ "start_time": func.least(table.c.start_time, insert_stmt.excluded.start_time),
2199
+ "duration_ms": func.extract(
2200
+ "epoch",
2201
+ func.cast(
2202
+ func.greatest(table.c.end_time, insert_stmt.excluded.end_time),
2203
+ TIMESTAMP(timezone=True),
2204
+ )
2205
+ - func.cast(
2206
+ func.least(table.c.start_time, insert_stmt.excluded.start_time),
2207
+ TIMESTAMP(timezone=True),
2208
+ ),
2209
+ )
2210
+ * 1000,
2211
+ "status": insert_stmt.excluded.status,
2212
+ # Update name only if new trace is from a higher-level component
2213
+ # Priority: workflow (3) > team (2) > agent (1) > child spans (0)
2214
+ "name": case(
2215
+ (new_level > existing_level, insert_stmt.excluded.name),
2216
+ else_=table.c.name,
2217
+ ),
2218
+ # Preserve existing non-null context values using COALESCE
2219
+ "run_id": func.coalesce(insert_stmt.excluded.run_id, table.c.run_id),
2220
+ "session_id": func.coalesce(insert_stmt.excluded.session_id, table.c.session_id),
2221
+ "user_id": func.coalesce(insert_stmt.excluded.user_id, table.c.user_id),
2222
+ "agent_id": func.coalesce(insert_stmt.excluded.agent_id, table.c.agent_id),
2223
+ "team_id": func.coalesce(insert_stmt.excluded.team_id, table.c.team_id),
2224
+ "workflow_id": func.coalesce(insert_stmt.excluded.workflow_id, table.c.workflow_id),
2225
+ },
2226
+ )
2227
+ await sess.execute(upsert_stmt)
2228
+
2229
+ except Exception as e:
2230
+ log_error(f"Error creating trace: {e}")
2231
+ # Don't raise - tracing should not break the main application flow
2232
+
2233
+ async def get_trace(
2234
+ self,
2235
+ trace_id: Optional[str] = None,
2236
+ run_id: Optional[str] = None,
2237
+ ):
2238
+ """Get a single trace by trace_id or other filters.
2239
+
2240
+ Args:
2241
+ trace_id: The unique trace identifier.
2242
+ run_id: Filter by run ID (returns first match).
2243
+
2244
+ Returns:
2245
+ Optional[Trace]: The trace if found, None otherwise.
2246
+
2247
+ Note:
2248
+ If multiple filters are provided, trace_id takes precedence.
2249
+ For other filters, the most recent trace is returned.
2250
+ """
2251
+ try:
2252
+ from agno.tracing.schemas import Trace
2253
+
2254
+ table = await self._get_table(table_type="traces")
2255
+
2256
+ # Get spans table for JOIN
2257
+ spans_table = await self._get_table(table_type="spans")
2258
+
2259
+ async with self.async_session_factory() as sess:
2260
+ # Build query with aggregated span counts
2261
+ stmt = self._get_traces_base_query(table, spans_table)
2262
+
2263
+ if trace_id:
2264
+ stmt = stmt.where(table.c.trace_id == trace_id)
2265
+ elif run_id:
2266
+ stmt = stmt.where(table.c.run_id == run_id)
2267
+ else:
2268
+ log_debug("get_trace called without any filter parameters")
2269
+ return None
2270
+
2271
+ # Order by most recent and get first result
2272
+ stmt = stmt.order_by(table.c.start_time.desc()).limit(1)
2273
+ result = await sess.execute(stmt)
2274
+ row = result.fetchone()
2275
+
2276
+ if row:
2277
+ return Trace.from_dict(dict(row._mapping))
2278
+ return None
2279
+
2280
+ except Exception as e:
2281
+ log_error(f"Error getting trace: {e}")
2282
+ return None
2283
+
2284
+ async def get_traces(
2285
+ self,
2286
+ run_id: Optional[str] = None,
2287
+ session_id: Optional[str] = None,
2288
+ user_id: Optional[str] = None,
2289
+ agent_id: Optional[str] = None,
2290
+ team_id: Optional[str] = None,
2291
+ workflow_id: Optional[str] = None,
2292
+ status: Optional[str] = None,
2293
+ start_time: Optional[datetime] = None,
2294
+ end_time: Optional[datetime] = None,
2295
+ limit: Optional[int] = 20,
2296
+ page: Optional[int] = 1,
2297
+ ) -> tuple[List, int]:
2298
+ """Get traces matching the provided filters with pagination.
2299
+
2300
+ Args:
2301
+ run_id: Filter by run ID.
2302
+ session_id: Filter by session ID.
2303
+ user_id: Filter by user ID.
2304
+ agent_id: Filter by agent ID.
2305
+ team_id: Filter by team ID.
2306
+ workflow_id: Filter by workflow ID.
2307
+ status: Filter by status (OK, ERROR, UNSET).
2308
+ start_time: Filter traces starting after this datetime.
2309
+ end_time: Filter traces ending before this datetime.
2310
+ limit: Maximum number of traces to return per page.
2311
+ page: Page number (1-indexed).
2312
+
2313
+ Returns:
2314
+ tuple[List[Trace], int]: Tuple of (list of matching traces, total count).
2315
+ """
2316
+ try:
2317
+ from agno.tracing.schemas import Trace
2318
+
2319
+ table = await self._get_table(table_type="traces")
2320
+
2321
+ # Get spans table for JOIN
2322
+ spans_table = await self._get_table(table_type="spans")
2323
+
2324
+ async with self.async_session_factory() as sess:
2325
+ # Build base query with aggregated span counts
2326
+ base_stmt = self._get_traces_base_query(table, spans_table)
2327
+
2328
+ # Apply filters
2329
+ if run_id:
2330
+ base_stmt = base_stmt.where(table.c.run_id == run_id)
2331
+ if session_id:
2332
+ base_stmt = base_stmt.where(table.c.session_id == session_id)
2333
+ if user_id:
2334
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2335
+ if agent_id:
2336
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2337
+ if team_id:
2338
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2339
+ if workflow_id:
2340
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2341
+ if status:
2342
+ base_stmt = base_stmt.where(table.c.status == status)
2343
+ if start_time:
2344
+ # Convert datetime to ISO string for comparison
2345
+ base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat())
2346
+ if end_time:
2347
+ # Convert datetime to ISO string for comparison
2348
+ base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat())
2349
+
2350
+ # Get total count
2351
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2352
+ total_count = await sess.scalar(count_stmt) or 0
2353
+ log_debug(f"Total matching traces: {total_count}")
2354
+
2355
+ # Apply pagination
2356
+ offset = (page - 1) * limit if page and limit else 0
2357
+ paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset)
2358
+
2359
+ result = await sess.execute(paginated_stmt)
2360
+ results = result.fetchall()
2361
+ log_debug(f"Returning page {page} with {len(results)} traces")
2362
+
2363
+ traces = [Trace.from_dict(dict(row._mapping)) for row in results]
2364
+ return traces, total_count
2365
+
2366
+ except Exception as e:
2367
+ log_error(f"Error getting traces: {e}")
2368
+ return [], 0
2369
+
2370
+ async def get_trace_stats(
2371
+ self,
2372
+ user_id: Optional[str] = None,
2373
+ agent_id: Optional[str] = None,
2374
+ team_id: Optional[str] = None,
2375
+ workflow_id: Optional[str] = None,
2376
+ start_time: Optional[datetime] = None,
2377
+ end_time: Optional[datetime] = None,
2378
+ limit: Optional[int] = 20,
2379
+ page: Optional[int] = 1,
2380
+ ) -> tuple[List[Dict[str, Any]], int]:
2381
+ """Get trace statistics grouped by session.
2382
+
2383
+ Args:
2384
+ user_id: Filter by user ID.
2385
+ agent_id: Filter by agent ID.
2386
+ team_id: Filter by team ID.
2387
+ workflow_id: Filter by workflow ID.
2388
+ start_time: Filter sessions with traces created after this datetime.
2389
+ end_time: Filter sessions with traces created before this datetime.
2390
+ limit: Maximum number of sessions to return per page.
2391
+ page: Page number (1-indexed).
2392
+
2393
+ Returns:
2394
+ tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count).
2395
+ Each dict contains: session_id, user_id, agent_id, team_id, total_traces,
2396
+ workflow_id, first_trace_at, last_trace_at.
2397
+ """
2398
+ try:
2399
+ table = await self._get_table(table_type="traces")
2400
+
2401
+ async with self.async_session_factory() as sess:
2402
+ # Build base query grouped by session_id
2403
+ base_stmt = (
2404
+ select(
2405
+ table.c.session_id,
2406
+ table.c.user_id,
2407
+ table.c.agent_id,
2408
+ table.c.team_id,
2409
+ table.c.workflow_id,
2410
+ func.count(table.c.trace_id).label("total_traces"),
2411
+ func.min(table.c.created_at).label("first_trace_at"),
2412
+ func.max(table.c.created_at).label("last_trace_at"),
2413
+ )
2414
+ .where(table.c.session_id.isnot(None)) # Only sessions with session_id
2415
+ .group_by(
2416
+ table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id
2417
+ )
2418
+ )
2419
+
2420
+ # Apply filters
2421
+ if user_id:
2422
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2423
+ if workflow_id:
2424
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2425
+ if team_id:
2426
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2427
+ if agent_id:
2428
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2429
+ if start_time:
2430
+ # Convert datetime to ISO string for comparison
2431
+ base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat())
2432
+ if end_time:
2433
+ # Convert datetime to ISO string for comparison
2434
+ base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat())
2435
+
2436
+ # Get total count of sessions
2437
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2438
+ total_count = await sess.scalar(count_stmt) or 0
2439
+
2440
+ # Apply pagination and ordering
2441
+ offset = (page - 1) * limit if page and limit else 0
2442
+ paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset)
2443
+
2444
+ result = await sess.execute(paginated_stmt)
2445
+ results = result.fetchall()
2446
+
2447
+ # Convert to list of dicts with datetime objects
2448
+ stats_list = []
2449
+ for row in results:
2450
+ # Convert ISO strings to datetime objects
2451
+ first_trace_at_str = row.first_trace_at
2452
+ last_trace_at_str = row.last_trace_at
2453
+
2454
+ # Parse ISO format strings to datetime objects
2455
+ first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00"))
2456
+ last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00"))
2457
+
2458
+ stats_list.append(
2459
+ {
2460
+ "session_id": row.session_id,
2461
+ "user_id": row.user_id,
2462
+ "agent_id": row.agent_id,
2463
+ "team_id": row.team_id,
2464
+ "workflow_id": row.workflow_id,
2465
+ "total_traces": row.total_traces,
2466
+ "first_trace_at": first_trace_at,
2467
+ "last_trace_at": last_trace_at,
2468
+ }
2469
+ )
2470
+
2471
+ return stats_list, total_count
2472
+
2473
+ except Exception as e:
2474
+ log_error(f"Error getting trace stats: {e}")
2475
+ return [], 0
2476
+
2477
+ # --- Spans ---
2478
+ async def create_span(self, span: "Span") -> None:
2479
+ """Create a single span in the database.
2480
+
2481
+ Args:
2482
+ span: The Span object to store.
2483
+ """
2484
+ try:
2485
+ table = await self._get_table(table_type="spans", create_table_if_not_found=True)
2486
+
2487
+ async with self.async_session_factory() as sess, sess.begin():
2488
+ stmt = postgresql.insert(table).values(span.to_dict())
2489
+ await sess.execute(stmt)
2490
+
2491
+ except Exception as e:
2492
+ log_error(f"Error creating span: {e}")
2493
+
2494
+ async def create_spans(self, spans: List) -> None:
2495
+ """Create multiple spans in the database as a batch.
2496
+
2497
+ Args:
2498
+ spans: List of Span objects to store.
2499
+ """
2500
+ if not spans:
2501
+ return
2502
+
2503
+ try:
2504
+ table = await self._get_table(table_type="spans", create_table_if_not_found=True)
2505
+
2506
+ async with self.async_session_factory() as sess, sess.begin():
2507
+ for span in spans:
2508
+ stmt = postgresql.insert(table).values(span.to_dict())
2509
+ await sess.execute(stmt)
2510
+
2511
+ except Exception as e:
2512
+ log_error(f"Error creating spans batch: {e}")
2513
+
2514
+ async def get_span(self, span_id: str):
2515
+ """Get a single span by its span_id.
2516
+
2517
+ Args:
2518
+ span_id: The unique span identifier.
2519
+
2520
+ Returns:
2521
+ Optional[Span]: The span if found, None otherwise.
2522
+ """
2523
+ try:
2524
+ from agno.tracing.schemas import Span
2525
+
2526
+ table = await self._get_table(table_type="spans")
2527
+
2528
+ async with self.async_session_factory() as sess:
2529
+ stmt = select(table).where(table.c.span_id == span_id)
2530
+ result = await sess.execute(stmt)
2531
+ row = result.fetchone()
2532
+ if row:
2533
+ return Span.from_dict(dict(row._mapping))
2534
+ return None
2535
+
2536
+ except Exception as e:
2537
+ log_error(f"Error getting span: {e}")
2538
+ return None
2539
+
2540
+ async def get_spans(
2541
+ self,
2542
+ trace_id: Optional[str] = None,
2543
+ parent_span_id: Optional[str] = None,
2544
+ limit: Optional[int] = 1000,
2545
+ ) -> List:
2546
+ """Get spans matching the provided filters.
2547
+
2548
+ Args:
2549
+ trace_id: Filter by trace ID.
2550
+ parent_span_id: Filter by parent span ID.
2551
+ limit: Maximum number of spans to return.
2552
+
2553
+ Returns:
2554
+ List[Span]: List of matching spans.
2555
+ """
2556
+ try:
2557
+ from agno.tracing.schemas import Span
2558
+
2559
+ table = await self._get_table(table_type="spans")
2560
+
2561
+ async with self.async_session_factory() as sess:
2562
+ stmt = select(table)
2563
+
2564
+ # Apply filters
2565
+ if trace_id:
2566
+ stmt = stmt.where(table.c.trace_id == trace_id)
2567
+ if parent_span_id:
2568
+ stmt = stmt.where(table.c.parent_span_id == parent_span_id)
2569
+
2570
+ if limit:
2571
+ stmt = stmt.limit(limit)
2572
+
2573
+ result = await sess.execute(stmt)
2574
+ results = result.fetchall()
2575
+ return [Span.from_dict(dict(row._mapping)) for row in results]
2576
+
2577
+ except Exception as e:
2578
+ log_error(f"Error getting spans: {e}")
2579
+ return []