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
agno/db/mysql/mysql.py ADDED
@@ -0,0 +1,2923 @@
1
+ import time
2
+ from datetime import date, datetime, timedelta, timezone
3
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
4
+ from uuid import uuid4
5
+
6
+ if TYPE_CHECKING:
7
+ from agno.tracing.schemas import Span, Trace
8
+
9
+ from agno.db.base import BaseDb, SessionType
10
+ from agno.db.migrations.manager import MigrationManager
11
+ from agno.db.mysql.schemas import get_table_schema_definition
12
+ from agno.db.mysql.utils import (
13
+ apply_sorting,
14
+ bulk_upsert_metrics,
15
+ calculate_date_metrics,
16
+ create_schema,
17
+ deserialize_cultural_knowledge_from_db,
18
+ fetch_all_sessions_data,
19
+ get_dates_to_calculate_metrics_for,
20
+ is_table_available,
21
+ is_valid_table,
22
+ serialize_cultural_knowledge_for_db,
23
+ )
24
+ from agno.db.schemas.culture import CulturalKnowledge
25
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
26
+ from agno.db.schemas.knowledge import KnowledgeRow
27
+ from agno.db.schemas.memory import UserMemory
28
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
29
+ from agno.utils.log import log_debug, log_error, log_info, log_warning
30
+ from agno.utils.string import generate_id
31
+
32
+ try:
33
+ from sqlalchemy import TEXT, ForeignKey, Index, UniqueConstraint, and_, cast, func, update
34
+ from sqlalchemy.dialects import mysql
35
+ from sqlalchemy.engine import Engine, create_engine
36
+ from sqlalchemy.orm import scoped_session, sessionmaker
37
+ from sqlalchemy.schema import Column, MetaData, Table
38
+ from sqlalchemy.sql.expression import select, text
39
+ except ImportError:
40
+ raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`")
41
+
42
+
43
+ class MySQLDb(BaseDb):
44
+ def __init__(
45
+ self,
46
+ id: Optional[str] = None,
47
+ db_engine: Optional[Engine] = None,
48
+ db_schema: Optional[str] = None,
49
+ db_url: Optional[str] = None,
50
+ session_table: Optional[str] = None,
51
+ culture_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
+ traces_table: Optional[str] = None,
57
+ spans_table: Optional[str] = None,
58
+ versions_table: Optional[str] = None,
59
+ create_schema: bool = True,
60
+ ):
61
+ """
62
+ Interface for interacting with a MySQL database.
63
+
64
+ The following order is used to determine the database connection:
65
+ 1. Use the db_engine if provided
66
+ 2. Use the db_url
67
+ 3. Raise an error if neither is provided
68
+
69
+ Args:
70
+ id (Optional[str]): ID of the database.
71
+ db_url (Optional[str]): The database URL to connect to.
72
+ db_engine (Optional[Engine]): The SQLAlchemy database engine to use.
73
+ db_schema (Optional[str]): The database schema to use.
74
+ session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions.
75
+ culture_table (Optional[str]): Name of the table to store cultural knowledge.
76
+ memory_table (Optional[str]): Name of the table to store memories.
77
+ metrics_table (Optional[str]): Name of the table to store metrics.
78
+ eval_table (Optional[str]): Name of the table to store evaluation runs data.
79
+ knowledge_table (Optional[str]): Name of the table to store knowledge content.
80
+ traces_table (Optional[str]): Name of the table to store run traces.
81
+ spans_table (Optional[str]): Name of the table to store span events.
82
+ versions_table (Optional[str]): Name of the table to store schema versions.
83
+ create_schema (bool): Whether to automatically create the database schema if it doesn't exist.
84
+ Set to False if schema is managed externally (e.g., via migrations). Defaults to True.
85
+
86
+ Raises:
87
+ ValueError: If neither db_url nor db_engine is provided.
88
+ ValueError: If none of the tables are provided.
89
+ """
90
+ if id is None:
91
+ base_seed = db_url or str(db_engine.url) # type: ignore
92
+ schema_suffix = db_schema if db_schema is not None else "ai"
93
+ seed = f"{base_seed}#{schema_suffix}"
94
+ id = generate_id(seed)
95
+
96
+ super().__init__(
97
+ id=id,
98
+ session_table=session_table,
99
+ culture_table=culture_table,
100
+ memory_table=memory_table,
101
+ metrics_table=metrics_table,
102
+ eval_table=eval_table,
103
+ knowledge_table=knowledge_table,
104
+ traces_table=traces_table,
105
+ spans_table=spans_table,
106
+ versions_table=versions_table,
107
+ )
108
+
109
+ _engine: Optional[Engine] = db_engine
110
+ if _engine is None and db_url is not None:
111
+ _engine = create_engine(db_url)
112
+ if _engine is None:
113
+ raise ValueError("One of db_url or db_engine must be provided")
114
+
115
+ self.db_url: Optional[str] = db_url
116
+ self.db_engine: Engine = _engine
117
+ self.db_schema: str = db_schema if db_schema is not None else "ai"
118
+ self.metadata: MetaData = MetaData(schema=self.db_schema)
119
+ self.create_schema: bool = create_schema
120
+
121
+ # Initialize database session
122
+ self.Session: scoped_session = scoped_session(sessionmaker(bind=self.db_engine))
123
+
124
+ # -- DB methods --
125
+ def table_exists(self, table_name: str) -> bool:
126
+ """Check if a table with the given name exists in the MySQL database.
127
+
128
+ Args:
129
+ table_name: Name of the table to check
130
+
131
+ Returns:
132
+ bool: True if the table exists in the database, False otherwise
133
+ """
134
+ with self.Session() as sess:
135
+ return is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema)
136
+
137
+ def _create_table(self, table_name: str, table_type: str) -> Table:
138
+ """
139
+ Create a table with the appropriate schema based on the table type.
140
+
141
+ Args:
142
+ table_name (str): Name of the table to create
143
+ table_type (str): Type of table (used to get schema definition)
144
+
145
+ Returns:
146
+ Table: SQLAlchemy Table object
147
+ """
148
+ try:
149
+ table_schema = get_table_schema_definition(table_type).copy()
150
+
151
+ columns: List[Column] = []
152
+ indexes: List[str] = []
153
+ unique_constraints: List[str] = []
154
+ schema_unique_constraints = table_schema.pop("_unique_constraints", [])
155
+
156
+ # Get the columns, indexes, and unique constraints from the table schema
157
+ for col_name, col_config in table_schema.items():
158
+ column_args = [col_name, col_config["type"]()]
159
+ column_kwargs = {}
160
+ if col_config.get("primary_key", False):
161
+ column_kwargs["primary_key"] = True
162
+ if "nullable" in col_config:
163
+ column_kwargs["nullable"] = col_config["nullable"]
164
+ if col_config.get("index", False):
165
+ indexes.append(col_name)
166
+ if col_config.get("unique", False):
167
+ column_kwargs["unique"] = True
168
+ unique_constraints.append(col_name)
169
+
170
+ # Handle foreign key constraint
171
+ if "foreign_key" in col_config:
172
+ fk_ref = col_config["foreign_key"]
173
+ # For spans table, dynamically replace the traces table reference
174
+ # with the actual trace table name configured for this db instance
175
+ if table_type == "spans" and "trace_id" in fk_ref:
176
+ fk_ref = f"{self.db_schema}.{self.trace_table_name}.trace_id"
177
+ column_args.append(ForeignKey(fk_ref))
178
+
179
+ columns.append(Column(*column_args, **column_kwargs)) # type: ignore
180
+
181
+ # Create the table object
182
+ table = Table(table_name, self.metadata, *columns, schema=self.db_schema)
183
+
184
+ # Add multi-column unique constraints with table-specific names
185
+ for constraint in schema_unique_constraints:
186
+ constraint_name = f"{table_name}_{constraint['name']}"
187
+ constraint_columns = constraint["columns"]
188
+ table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name))
189
+
190
+ # Add indexes to the table definition
191
+ for idx_col in indexes:
192
+ idx_name = f"idx_{table_name}_{idx_col}"
193
+ table.append_constraint(Index(idx_name, idx_col))
194
+
195
+ if self.create_schema:
196
+ with self.Session() as sess, sess.begin():
197
+ create_schema(session=sess, db_schema=self.db_schema)
198
+
199
+ # Create table
200
+ table_created = False
201
+ if not self.table_exists(table_name):
202
+ table.create(self.db_engine, checkfirst=True)
203
+ log_debug(f"Successfully created table '{table_name}'")
204
+ table_created = True
205
+ else:
206
+ log_debug(f"Table {self.db_schema}.{table_name} already exists, skipping creation")
207
+
208
+ # Create indexes
209
+ for idx in table.indexes:
210
+ try:
211
+ # Check if index already exists
212
+ with self.Session() as sess:
213
+ exists_query = text(
214
+ "SELECT 1 FROM information_schema.statistics WHERE table_schema = :schema "
215
+ "AND table_name = :table_name AND index_name = :index_name"
216
+ )
217
+ exists = (
218
+ sess.execute(
219
+ exists_query,
220
+ {"schema": self.db_schema, "table_name": table_name, "index_name": idx.name},
221
+ ).scalar()
222
+ is not None
223
+ )
224
+ if exists:
225
+ log_debug(
226
+ f"Index {idx.name} already exists in {self.db_schema}.{table_name}, skipping creation"
227
+ )
228
+ continue
229
+
230
+ idx.create(self.db_engine)
231
+
232
+ log_debug(f"Created index: {idx.name} for table {self.db_schema}.{table_name}")
233
+ except Exception as e:
234
+ log_error(f"Error creating index {idx.name}: {e}")
235
+
236
+ # Store the schema version for the created table
237
+ if table_name != self.versions_table_name and table_created:
238
+ latest_schema_version = MigrationManager(self).latest_schema_version
239
+ self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public)
240
+ log_info(
241
+ f"Successfully stored version {latest_schema_version.public} in database for table {table_name}"
242
+ )
243
+
244
+ return table
245
+
246
+ except Exception as e:
247
+ log_error(f"Could not create table {self.db_schema}.{table_name}: {e}")
248
+ raise
249
+
250
+ def _create_all_tables(self):
251
+ """Create all tables for the database."""
252
+ tables_to_create = [
253
+ (self.session_table_name, "sessions"),
254
+ (self.memory_table_name, "memories"),
255
+ (self.metrics_table_name, "metrics"),
256
+ (self.eval_table_name, "evals"),
257
+ (self.knowledge_table_name, "knowledge"),
258
+ (self.culture_table_name, "culture"),
259
+ (self.trace_table_name, "traces"),
260
+ (self.span_table_name, "spans"),
261
+ (self.versions_table_name, "versions"),
262
+ ]
263
+
264
+ for table_name, table_type in tables_to_create:
265
+ self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True)
266
+
267
+ def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Optional[Table]:
268
+ if table_type == "sessions":
269
+ self.session_table = self._get_or_create_table(
270
+ table_name=self.session_table_name,
271
+ table_type="sessions",
272
+ create_table_if_not_found=create_table_if_not_found,
273
+ )
274
+ return self.session_table
275
+
276
+ if table_type == "memories":
277
+ self.memory_table = self._get_or_create_table(
278
+ table_name=self.memory_table_name,
279
+ table_type="memories",
280
+ create_table_if_not_found=create_table_if_not_found,
281
+ )
282
+ return self.memory_table
283
+
284
+ if table_type == "metrics":
285
+ self.metrics_table = self._get_or_create_table(
286
+ table_name=self.metrics_table_name,
287
+ table_type="metrics",
288
+ create_table_if_not_found=create_table_if_not_found,
289
+ )
290
+ return self.metrics_table
291
+
292
+ if table_type == "evals":
293
+ self.eval_table = self._get_or_create_table(
294
+ table_name=self.eval_table_name,
295
+ table_type="evals",
296
+ create_table_if_not_found=create_table_if_not_found,
297
+ )
298
+ return self.eval_table
299
+
300
+ if table_type == "knowledge":
301
+ self.knowledge_table = self._get_or_create_table(
302
+ table_name=self.knowledge_table_name,
303
+ table_type="knowledge",
304
+ create_table_if_not_found=create_table_if_not_found,
305
+ )
306
+ return self.knowledge_table
307
+
308
+ if table_type == "culture":
309
+ self.culture_table = self._get_or_create_table(
310
+ table_name=self.culture_table_name,
311
+ table_type="culture",
312
+ create_table_if_not_found=create_table_if_not_found,
313
+ )
314
+ return self.culture_table
315
+
316
+ if table_type == "versions":
317
+ self.versions_table = 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
+ self.traces_table = self._get_or_create_table(
326
+ table_name=self.trace_table_name,
327
+ table_type="traces",
328
+ create_table_if_not_found=create_table_if_not_found,
329
+ )
330
+ return self.traces_table
331
+
332
+ if table_type == "spans":
333
+ # Ensure traces table exists first (spans has FK to traces)
334
+ if create_table_if_not_found:
335
+ self._get_table(table_type="traces", create_table_if_not_found=True)
336
+
337
+ self.spans_table = 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
+ def _get_or_create_table(
347
+ self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False
348
+ ) -> Optional[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
+ with self.Session() as sess, sess.begin():
361
+ table_is_available = is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema)
362
+
363
+ if not table_is_available:
364
+ if not create_table_if_not_found:
365
+ return None
366
+
367
+ created_table = self._create_table(table_name=table_name, table_type=table_type)
368
+
369
+ return created_table
370
+
371
+ if not is_valid_table(
372
+ db_engine=self.db_engine,
373
+ table_name=table_name,
374
+ table_type=table_type,
375
+ db_schema=self.db_schema,
376
+ ):
377
+ raise ValueError(f"Table {self.db_schema}.{table_name} has an invalid schema")
378
+
379
+ try:
380
+ table = Table(table_name, self.metadata, schema=self.db_schema, autoload_with=self.db_engine)
381
+ return table
382
+
383
+ except Exception as e:
384
+ log_error(f"Error loading existing table {self.db_schema}.{table_name}: {e}")
385
+ raise
386
+
387
+ def get_latest_schema_version(self, table_name: str) -> str:
388
+ """Get the latest version of the database schema."""
389
+ table = self._get_table(table_type="versions", create_table_if_not_found=True)
390
+ with self.Session() as sess:
391
+ # Latest version for the given table
392
+ stmt = select(table).where(table.c.table_name == table_name).order_by(table.c.version.desc()).limit(1) # type: ignore
393
+ result = sess.execute(stmt).fetchone()
394
+ if result is None:
395
+ return "2.0.0"
396
+ version_dict = dict(result._mapping)
397
+ return version_dict.get("version") or "2.0.0"
398
+
399
+ def upsert_schema_version(self, table_name: str, version: str) -> None:
400
+ """Upsert the schema version into the database."""
401
+ table = self._get_table(table_type="versions", create_table_if_not_found=True)
402
+ if table is None:
403
+ return
404
+ current_datetime = datetime.now().isoformat()
405
+ with self.Session() as sess, sess.begin():
406
+ stmt = mysql.insert(table).values( # type: ignore
407
+ table_name=table_name,
408
+ version=version,
409
+ created_at=current_datetime, # Store as ISO format string
410
+ updated_at=current_datetime,
411
+ )
412
+ # Update version if table_name already exists
413
+ stmt = stmt.on_duplicate_key_update(
414
+ version=version,
415
+ created_at=current_datetime,
416
+ updated_at=current_datetime,
417
+ )
418
+ sess.execute(stmt)
419
+
420
+ # -- Session methods --
421
+ def delete_session(self, session_id: str) -> bool:
422
+ """
423
+ Delete a session from the database.
424
+
425
+ Args:
426
+ session_id (str): ID of the session to delete
427
+
428
+ Returns:
429
+ bool: True if the session was deleted, False otherwise.
430
+
431
+ Raises:
432
+ Exception: If an error occurs during deletion.
433
+ """
434
+ try:
435
+ table = self._get_table(table_type="sessions")
436
+ if table is None:
437
+ return False
438
+
439
+ with self.Session() as sess, sess.begin():
440
+ delete_stmt = table.delete().where(table.c.session_id == session_id)
441
+ result = sess.execute(delete_stmt)
442
+ if result.rowcount == 0:
443
+ log_debug(f"No session found to delete with session_id: {session_id} in table {table.name}")
444
+ return False
445
+ else:
446
+ log_debug(f"Successfully deleted session with session_id: {session_id} in table {table.name}")
447
+ return True
448
+
449
+ except Exception as e:
450
+ log_error(f"Error deleting session: {e}")
451
+ return False
452
+
453
+ def delete_sessions(self, session_ids: List[str]) -> None:
454
+ """Delete all given sessions from the database.
455
+ Can handle multiple session types in the same run.
456
+
457
+ Args:
458
+ session_ids (List[str]): The IDs of the sessions to delete.
459
+
460
+ Raises:
461
+ Exception: If an error occurs during deletion.
462
+ """
463
+ try:
464
+ table = self._get_table(table_type="sessions")
465
+ if table is None:
466
+ return
467
+
468
+ with self.Session() as sess, sess.begin():
469
+ delete_stmt = table.delete().where(table.c.session_id.in_(session_ids))
470
+ result = sess.execute(delete_stmt)
471
+
472
+ log_debug(f"Successfully deleted {result.rowcount} sessions")
473
+
474
+ except Exception as e:
475
+ log_error(f"Error deleting sessions: {e}")
476
+
477
+ def get_session(
478
+ self,
479
+ session_id: str,
480
+ session_type: SessionType,
481
+ user_id: Optional[str] = None,
482
+ deserialize: Optional[bool] = True,
483
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
484
+ """
485
+ Read a session from the database.
486
+
487
+ Args:
488
+ session_id (str): ID of the session to read.
489
+ session_type (SessionType): Type of session to get.
490
+ user_id (Optional[str]): User ID to filter by. Defaults to None.
491
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
492
+
493
+ Returns:
494
+ Union[Session, Dict[str, Any], None]:
495
+ - When deserialize=True: Session object
496
+ - When deserialize=False: Session dictionary
497
+
498
+ Raises:
499
+ Exception: If an error occurs during retrieval.
500
+ """
501
+ try:
502
+ table = self._get_table(table_type="sessions")
503
+ if table is None:
504
+ return None
505
+
506
+ with self.Session() as sess:
507
+ stmt = select(table).where(table.c.session_id == session_id)
508
+
509
+ if user_id is not None:
510
+ stmt = stmt.where(table.c.user_id == user_id)
511
+ result = sess.execute(stmt).fetchone()
512
+ if result is None:
513
+ return None
514
+
515
+ session = dict(result._mapping)
516
+
517
+ if not deserialize:
518
+ return session
519
+
520
+ if session_type == SessionType.AGENT:
521
+ return AgentSession.from_dict(session)
522
+ elif session_type == SessionType.TEAM:
523
+ return TeamSession.from_dict(session)
524
+ elif session_type == SessionType.WORKFLOW:
525
+ return WorkflowSession.from_dict(session)
526
+ else:
527
+ raise ValueError(f"Invalid session type: {session_type}")
528
+
529
+ except Exception as e:
530
+ log_error(f"Exception reading from session table: {e}")
531
+ return None
532
+
533
+ def get_sessions(
534
+ self,
535
+ session_type: Optional[SessionType] = None,
536
+ user_id: Optional[str] = None,
537
+ component_id: Optional[str] = None,
538
+ session_name: Optional[str] = None,
539
+ start_timestamp: Optional[int] = None,
540
+ end_timestamp: Optional[int] = None,
541
+ limit: Optional[int] = None,
542
+ page: Optional[int] = None,
543
+ sort_by: Optional[str] = None,
544
+ sort_order: Optional[str] = None,
545
+ deserialize: Optional[bool] = True,
546
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
547
+ """
548
+ Get all sessions in the given table. Can filter by user_id and entity_id.
549
+
550
+ Args:
551
+ session_type (Optional[SessionType]): The type of sessions to get.
552
+ user_id (Optional[str]): The ID of the user to filter by.
553
+ component_id (Optional[str]): The ID of the agent / workflow to filter by.
554
+ start_timestamp (Optional[int]): The start timestamp to filter by.
555
+ end_timestamp (Optional[int]): The end timestamp to filter by.
556
+ session_name (Optional[str]): The name of the session to filter by.
557
+ limit (Optional[int]): The maximum number of sessions to return. Defaults to None.
558
+ page (Optional[int]): The page number to return. Defaults to None.
559
+ sort_by (Optional[str]): The field to sort by. Defaults to None.
560
+ sort_order (Optional[str]): The sort order. Defaults to None.
561
+ deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True.
562
+
563
+ Returns:
564
+ Union[List[Session], Tuple[List[Dict], int]]:
565
+ - When deserialize=True: List of Session objects
566
+ - When deserialize=False: Tuple of (session dictionaries, total count)
567
+
568
+ Raises:
569
+ Exception: If an error occurs during retrieval.
570
+ """
571
+ try:
572
+ table = self._get_table(table_type="sessions")
573
+ if table is None:
574
+ return [] if deserialize else ([], 0)
575
+
576
+ with self.Session() as sess, sess.begin():
577
+ stmt = select(table)
578
+
579
+ # Filtering
580
+ if user_id is not None:
581
+ stmt = stmt.where(table.c.user_id == user_id)
582
+ if component_id is not None:
583
+ if session_type == SessionType.AGENT:
584
+ stmt = stmt.where(table.c.agent_id == component_id)
585
+ elif session_type == SessionType.TEAM:
586
+ stmt = stmt.where(table.c.team_id == component_id)
587
+ elif session_type == SessionType.WORKFLOW:
588
+ stmt = stmt.where(table.c.workflow_id == component_id)
589
+ if start_timestamp is not None:
590
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
591
+ if end_timestamp is not None:
592
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
593
+ if session_name is not None:
594
+ # MySQL JSON extraction syntax
595
+ stmt = stmt.where(
596
+ func.coalesce(
597
+ func.json_unquote(func.json_extract(table.c.session_data, "$.session_name")), ""
598
+ ).ilike(f"%{session_name}%")
599
+ )
600
+ if session_type is not None:
601
+ session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type
602
+ stmt = stmt.where(table.c.session_type == session_type_value)
603
+
604
+ count_stmt = select(func.count()).select_from(stmt.alias())
605
+ total_count = sess.execute(count_stmt).scalar()
606
+
607
+ # Sorting
608
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
609
+
610
+ # Paginating
611
+ if limit is not None:
612
+ stmt = stmt.limit(limit)
613
+ if page is not None:
614
+ stmt = stmt.offset((page - 1) * limit)
615
+
616
+ result = sess.execute(stmt).fetchall()
617
+ if not result:
618
+ return [] if deserialize else ([], 0)
619
+
620
+ session_dicts = [dict(row._mapping) for row in result]
621
+ if not deserialize:
622
+ return session_dicts, total_count
623
+
624
+ if session_type == SessionType.AGENT:
625
+ return [AgentSession.from_dict(record) for record in session_dicts] # type: ignore
626
+ elif session_type == SessionType.TEAM:
627
+ return [TeamSession.from_dict(record) for record in session_dicts] # type: ignore
628
+ elif session_type == SessionType.WORKFLOW:
629
+ return [WorkflowSession.from_dict(record) for record in session_dicts] # type: ignore
630
+ else:
631
+ raise ValueError(f"Invalid session type: {session_type}")
632
+
633
+ except Exception as e:
634
+ log_error(f"Exception getting sessions: {e}")
635
+ raise e
636
+
637
+ def rename_session(
638
+ self, session_id: str, session_type: SessionType, session_name: str, deserialize: Optional[bool] = True
639
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
640
+ """
641
+ Rename a session in the database.
642
+
643
+ Args:
644
+ session_id (str): The ID of the session to rename.
645
+ session_type (SessionType): The type of session to rename.
646
+ session_name (str): The new name for the session.
647
+ deserialize (Optional[bool]): Whether to serialize the session. Defaults to True.
648
+
649
+ Returns:
650
+ Optional[Union[Session, Dict[str, Any]]]:
651
+ - When deserialize=True: Session object
652
+ - When deserialize=False: Session dictionary
653
+
654
+ Raises:
655
+ Exception: If an error occurs during renaming.
656
+ """
657
+ try:
658
+ table = self._get_table(table_type="sessions")
659
+ if table is None:
660
+ return None
661
+
662
+ with self.Session() as sess, sess.begin():
663
+ # MySQL JSON_SET syntax
664
+ stmt = (
665
+ update(table)
666
+ .where(table.c.session_id == session_id)
667
+ .where(table.c.session_type == session_type.value)
668
+ .values(session_data=func.json_set(table.c.session_data, "$.session_name", session_name))
669
+ )
670
+ sess.execute(stmt)
671
+
672
+ # Fetch the updated row
673
+ select_stmt = select(table).where(table.c.session_id == session_id)
674
+ result = sess.execute(select_stmt)
675
+ row = result.fetchone()
676
+ if not row:
677
+ return None
678
+
679
+ session = dict(row._mapping)
680
+ if not deserialize:
681
+ return session
682
+
683
+ # Return the appropriate session type
684
+ if session_type == SessionType.AGENT:
685
+ return AgentSession.from_dict(session)
686
+ elif session_type == SessionType.TEAM:
687
+ return TeamSession.from_dict(session)
688
+ elif session_type == SessionType.WORKFLOW:
689
+ return WorkflowSession.from_dict(session)
690
+ else:
691
+ raise ValueError(f"Invalid session type: {session_type}")
692
+
693
+ except Exception as e:
694
+ log_error(f"Exception renaming session: {e}")
695
+ return None
696
+
697
+ def upsert_session(
698
+ self, session: Session, deserialize: Optional[bool] = True
699
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
700
+ """
701
+ Insert or update a session in the database.
702
+
703
+ Args:
704
+ session (Session): The session data to upsert.
705
+ deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True.
706
+
707
+ Returns:
708
+ Optional[Union[Session, Dict[str, Any]]]:
709
+ - When deserialize=True: Session object
710
+ - When deserialize=False: Session dictionary
711
+
712
+ Raises:
713
+ Exception: If an error occurs during upsert.
714
+ """
715
+ try:
716
+ table = self._get_table(table_type="sessions", create_table_if_not_found=True)
717
+ if table is None:
718
+ return None
719
+
720
+ session_dict = session.to_dict()
721
+
722
+ if isinstance(session, AgentSession):
723
+ with self.Session() as sess, sess.begin():
724
+ stmt = mysql.insert(table).values(
725
+ session_id=session_dict.get("session_id"),
726
+ session_type=SessionType.AGENT.value,
727
+ agent_id=session_dict.get("agent_id"),
728
+ user_id=session_dict.get("user_id"),
729
+ runs=session_dict.get("runs"),
730
+ agent_data=session_dict.get("agent_data"),
731
+ session_data=session_dict.get("session_data"),
732
+ summary=session_dict.get("summary"),
733
+ metadata=session_dict.get("metadata"),
734
+ created_at=session_dict.get("created_at"),
735
+ updated_at=session_dict.get("created_at"),
736
+ )
737
+ stmt = stmt.on_duplicate_key_update(
738
+ agent_id=session_dict.get("agent_id"),
739
+ user_id=session_dict.get("user_id"),
740
+ agent_data=session_dict.get("agent_data"),
741
+ session_data=session_dict.get("session_data"),
742
+ summary=session_dict.get("summary"),
743
+ metadata=session_dict.get("metadata"),
744
+ runs=session_dict.get("runs"),
745
+ updated_at=int(time.time()),
746
+ )
747
+ sess.execute(stmt)
748
+
749
+ # Fetch the row
750
+ select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id"))
751
+ result = sess.execute(select_stmt)
752
+ row = result.fetchone()
753
+ if not row:
754
+ return None
755
+ session_dict = dict(row._mapping)
756
+ if session_dict is None or not deserialize:
757
+ return session_dict
758
+ return AgentSession.from_dict(session_dict)
759
+
760
+ elif isinstance(session, TeamSession):
761
+ with self.Session() as sess, sess.begin():
762
+ stmt = mysql.insert(table).values(
763
+ session_id=session_dict.get("session_id"),
764
+ session_type=SessionType.TEAM.value,
765
+ team_id=session_dict.get("team_id"),
766
+ user_id=session_dict.get("user_id"),
767
+ runs=session_dict.get("runs"),
768
+ team_data=session_dict.get("team_data"),
769
+ session_data=session_dict.get("session_data"),
770
+ summary=session_dict.get("summary"),
771
+ metadata=session_dict.get("metadata"),
772
+ created_at=session_dict.get("created_at"),
773
+ updated_at=session_dict.get("created_at"),
774
+ )
775
+ stmt = stmt.on_duplicate_key_update(
776
+ team_id=session_dict.get("team_id"),
777
+ user_id=session_dict.get("user_id"),
778
+ team_data=session_dict.get("team_data"),
779
+ session_data=session_dict.get("session_data"),
780
+ summary=session_dict.get("summary"),
781
+ metadata=session_dict.get("metadata"),
782
+ runs=session_dict.get("runs"),
783
+ updated_at=int(time.time()),
784
+ )
785
+ sess.execute(stmt)
786
+
787
+ # Fetch the row
788
+ select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id"))
789
+ result = sess.execute(select_stmt)
790
+ row = result.fetchone()
791
+ if not row:
792
+ return None
793
+ session_dict = dict(row._mapping)
794
+ if session_dict is None or not deserialize:
795
+ return session_dict
796
+ return TeamSession.from_dict(session_dict)
797
+
798
+ else:
799
+ with self.Session() as sess, sess.begin():
800
+ stmt = mysql.insert(table).values(
801
+ session_id=session_dict.get("session_id"),
802
+ session_type=SessionType.WORKFLOW.value,
803
+ workflow_id=session_dict.get("workflow_id"),
804
+ user_id=session_dict.get("user_id"),
805
+ runs=session_dict.get("runs"),
806
+ workflow_data=session_dict.get("workflow_data"),
807
+ session_data=session_dict.get("session_data"),
808
+ summary=session_dict.get("summary"),
809
+ metadata=session_dict.get("metadata"),
810
+ created_at=session_dict.get("created_at"),
811
+ updated_at=session_dict.get("created_at"),
812
+ )
813
+ stmt = stmt.on_duplicate_key_update(
814
+ workflow_id=session_dict.get("workflow_id"),
815
+ user_id=session_dict.get("user_id"),
816
+ workflow_data=session_dict.get("workflow_data"),
817
+ session_data=session_dict.get("session_data"),
818
+ summary=session_dict.get("summary"),
819
+ metadata=session_dict.get("metadata"),
820
+ runs=session_dict.get("runs"),
821
+ updated_at=int(time.time()),
822
+ )
823
+ sess.execute(stmt)
824
+
825
+ # Fetch the row
826
+ select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id"))
827
+ result = sess.execute(select_stmt)
828
+ row = result.fetchone()
829
+ if not row:
830
+ return None
831
+ session_dict = dict(row._mapping)
832
+ if session_dict is None or not deserialize:
833
+ return session_dict
834
+ return WorkflowSession.from_dict(session_dict)
835
+
836
+ except Exception as e:
837
+ log_error(f"Exception upserting into sessions table: {e}")
838
+ return None
839
+
840
+ def upsert_sessions(
841
+ self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False
842
+ ) -> List[Union[Session, Dict[str, Any]]]:
843
+ """
844
+ Bulk upsert multiple sessions for improved performance on large datasets.
845
+
846
+ Args:
847
+ sessions (List[Session]): List of sessions to upsert.
848
+ deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True.
849
+ preserve_updated_at (bool): If True, preserve the updated_at from the session object.
850
+
851
+ Returns:
852
+ List[Union[Session, Dict[str, Any]]]: List of upserted sessions.
853
+
854
+ Raises:
855
+ Exception: If an error occurs during bulk upsert.
856
+ """
857
+ if not sessions:
858
+ return []
859
+
860
+ try:
861
+ table = self._get_table(table_type="sessions", create_table_if_not_found=True)
862
+ if table is None:
863
+ log_info("Sessions table not available, falling back to individual upserts")
864
+ return [
865
+ result
866
+ for session in sessions
867
+ if session is not None
868
+ for result in [self.upsert_session(session, deserialize=deserialize)]
869
+ if result is not None
870
+ ]
871
+
872
+ # Group sessions by type for batch processing
873
+ agent_sessions = []
874
+ team_sessions = []
875
+ workflow_sessions = []
876
+
877
+ for session in sessions:
878
+ if isinstance(session, AgentSession):
879
+ agent_sessions.append(session)
880
+ elif isinstance(session, TeamSession):
881
+ team_sessions.append(session)
882
+ elif isinstance(session, WorkflowSession):
883
+ workflow_sessions.append(session)
884
+
885
+ results: List[Union[Session, Dict[str, Any]]] = []
886
+
887
+ # Process each session type in bulk
888
+ with self.Session() as sess, sess.begin():
889
+ # Bulk upsert agent sessions
890
+ if agent_sessions:
891
+ agent_data = []
892
+ for session in agent_sessions:
893
+ session_dict = session.to_dict()
894
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
895
+ updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time())
896
+ agent_data.append(
897
+ {
898
+ "session_id": session_dict.get("session_id"),
899
+ "session_type": SessionType.AGENT.value,
900
+ "agent_id": session_dict.get("agent_id"),
901
+ "user_id": session_dict.get("user_id"),
902
+ "runs": session_dict.get("runs"),
903
+ "agent_data": session_dict.get("agent_data"),
904
+ "session_data": session_dict.get("session_data"),
905
+ "summary": session_dict.get("summary"),
906
+ "metadata": session_dict.get("metadata"),
907
+ "created_at": session_dict.get("created_at"),
908
+ "updated_at": updated_at,
909
+ }
910
+ )
911
+
912
+ if agent_data:
913
+ stmt = mysql.insert(table)
914
+ stmt = stmt.on_duplicate_key_update(
915
+ agent_id=stmt.inserted.agent_id,
916
+ user_id=stmt.inserted.user_id,
917
+ agent_data=stmt.inserted.agent_data,
918
+ session_data=stmt.inserted.session_data,
919
+ summary=stmt.inserted.summary,
920
+ metadata=stmt.inserted.metadata,
921
+ runs=stmt.inserted.runs,
922
+ updated_at=stmt.inserted.updated_at,
923
+ )
924
+ sess.execute(stmt, agent_data)
925
+
926
+ # Fetch the results for agent sessions
927
+ agent_ids = [session.session_id for session in agent_sessions]
928
+ select_stmt = select(table).where(table.c.session_id.in_(agent_ids))
929
+ result = sess.execute(select_stmt).fetchall()
930
+
931
+ for row in result:
932
+ session_dict = dict(row._mapping)
933
+ if deserialize:
934
+ deserialized_agent_session = AgentSession.from_dict(session_dict)
935
+ if deserialized_agent_session is None:
936
+ continue
937
+ results.append(deserialized_agent_session)
938
+ else:
939
+ results.append(session_dict)
940
+
941
+ # Bulk upsert team sessions
942
+ if team_sessions:
943
+ team_data = []
944
+ for session in team_sessions:
945
+ session_dict = session.to_dict()
946
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
947
+ updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time())
948
+ team_data.append(
949
+ {
950
+ "session_id": session_dict.get("session_id"),
951
+ "session_type": SessionType.TEAM.value,
952
+ "team_id": session_dict.get("team_id"),
953
+ "user_id": session_dict.get("user_id"),
954
+ "runs": session_dict.get("runs"),
955
+ "team_data": session_dict.get("team_data"),
956
+ "session_data": session_dict.get("session_data"),
957
+ "summary": session_dict.get("summary"),
958
+ "metadata": session_dict.get("metadata"),
959
+ "created_at": session_dict.get("created_at"),
960
+ "updated_at": updated_at,
961
+ }
962
+ )
963
+
964
+ if team_data:
965
+ stmt = mysql.insert(table)
966
+ stmt = stmt.on_duplicate_key_update(
967
+ team_id=stmt.inserted.team_id,
968
+ user_id=stmt.inserted.user_id,
969
+ team_data=stmt.inserted.team_data,
970
+ session_data=stmt.inserted.session_data,
971
+ summary=stmt.inserted.summary,
972
+ metadata=stmt.inserted.metadata,
973
+ runs=stmt.inserted.runs,
974
+ updated_at=stmt.inserted.updated_at,
975
+ )
976
+ sess.execute(stmt, team_data)
977
+
978
+ # Fetch the results for team sessions
979
+ team_ids = [session.session_id for session in team_sessions]
980
+ select_stmt = select(table).where(table.c.session_id.in_(team_ids))
981
+ result = sess.execute(select_stmt).fetchall()
982
+
983
+ for row in result:
984
+ session_dict = dict(row._mapping)
985
+ if deserialize:
986
+ deserialized_team_session = TeamSession.from_dict(session_dict)
987
+ if deserialized_team_session is None:
988
+ continue
989
+ results.append(deserialized_team_session)
990
+ else:
991
+ results.append(session_dict)
992
+
993
+ # Bulk upsert workflow sessions
994
+ if workflow_sessions:
995
+ workflow_data = []
996
+ for session in workflow_sessions:
997
+ session_dict = session.to_dict()
998
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
999
+ updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time())
1000
+ workflow_data.append(
1001
+ {
1002
+ "session_id": session_dict.get("session_id"),
1003
+ "session_type": SessionType.WORKFLOW.value,
1004
+ "workflow_id": session_dict.get("workflow_id"),
1005
+ "user_id": session_dict.get("user_id"),
1006
+ "runs": session_dict.get("runs"),
1007
+ "workflow_data": session_dict.get("workflow_data"),
1008
+ "session_data": session_dict.get("session_data"),
1009
+ "summary": session_dict.get("summary"),
1010
+ "metadata": session_dict.get("metadata"),
1011
+ "created_at": session_dict.get("created_at"),
1012
+ "updated_at": updated_at,
1013
+ }
1014
+ )
1015
+
1016
+ if workflow_data:
1017
+ stmt = mysql.insert(table)
1018
+ stmt = stmt.on_duplicate_key_update(
1019
+ workflow_id=stmt.inserted.workflow_id,
1020
+ user_id=stmt.inserted.user_id,
1021
+ workflow_data=stmt.inserted.workflow_data,
1022
+ session_data=stmt.inserted.session_data,
1023
+ summary=stmt.inserted.summary,
1024
+ metadata=stmt.inserted.metadata,
1025
+ runs=stmt.inserted.runs,
1026
+ updated_at=stmt.inserted.updated_at,
1027
+ )
1028
+ sess.execute(stmt, workflow_data)
1029
+
1030
+ # Fetch the results for workflow sessions
1031
+ workflow_ids = [session.session_id for session in workflow_sessions]
1032
+ select_stmt = select(table).where(table.c.session_id.in_(workflow_ids))
1033
+ result = sess.execute(select_stmt).fetchall()
1034
+
1035
+ for row in result:
1036
+ session_dict = dict(row._mapping)
1037
+ if deserialize:
1038
+ deserialized_workflow_session = WorkflowSession.from_dict(session_dict)
1039
+ if deserialized_workflow_session is None:
1040
+ continue
1041
+ results.append(deserialized_workflow_session)
1042
+ else:
1043
+ results.append(session_dict)
1044
+
1045
+ return results
1046
+
1047
+ except Exception as e:
1048
+ log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}")
1049
+ # Fallback to individual upserts
1050
+ return [
1051
+ result
1052
+ for session in sessions
1053
+ if session is not None
1054
+ for result in [self.upsert_session(session, deserialize=deserialize)]
1055
+ if result is not None
1056
+ ]
1057
+
1058
+ # -- Memory methods --
1059
+ def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None):
1060
+ """Delete a user memory from the database.
1061
+
1062
+ Args:
1063
+ memory_id (str): The ID of the memory to delete.
1064
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
1065
+
1066
+ Returns:
1067
+ bool: True if deletion was successful, False otherwise.
1068
+
1069
+ Raises:
1070
+ Exception: If an error occurs during deletion.
1071
+ """
1072
+ try:
1073
+ table = self._get_table(table_type="memories")
1074
+ if table is None:
1075
+ return
1076
+
1077
+ with self.Session() as sess, sess.begin():
1078
+ delete_stmt = table.delete().where(table.c.memory_id == memory_id)
1079
+ if user_id is not None:
1080
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
1081
+ result = sess.execute(delete_stmt)
1082
+
1083
+ success = result.rowcount > 0
1084
+ if success:
1085
+ log_debug(f"Successfully deleted user memory id: {memory_id}")
1086
+ else:
1087
+ log_debug(f"No user memory found with id: {memory_id}")
1088
+
1089
+ except Exception as e:
1090
+ log_error(f"Error deleting user memory: {e}")
1091
+
1092
+ def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None:
1093
+ """Delete user memories from the database.
1094
+
1095
+ Args:
1096
+ memory_ids (List[str]): The IDs of the memories to delete.
1097
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
1098
+
1099
+ Raises:
1100
+ Exception: If an error occurs during deletion.
1101
+ """
1102
+ try:
1103
+ table = self._get_table(table_type="memories")
1104
+ if table is None:
1105
+ return
1106
+
1107
+ with self.Session() as sess, sess.begin():
1108
+ delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids))
1109
+ if user_id is not None:
1110
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
1111
+ result = sess.execute(delete_stmt)
1112
+ if result.rowcount == 0:
1113
+ log_debug(f"No user memories found with ids: {memory_ids}")
1114
+
1115
+ except Exception as e:
1116
+ log_error(f"Error deleting user memories: {e}")
1117
+
1118
+ def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]:
1119
+ """Get all memory topics from the database.
1120
+
1121
+ Args:
1122
+ user_id (Optional[str]): Optional user ID to filter topics.
1123
+
1124
+ Returns:
1125
+ List[str]: List of memory topics.
1126
+ """
1127
+ try:
1128
+ table = self._get_table(table_type="memories")
1129
+ if table is None:
1130
+ return []
1131
+
1132
+ with self.Session() as sess, sess.begin():
1133
+ # MySQL approach: extract JSON array elements differently
1134
+ stmt = select(table.c.topics)
1135
+ result = sess.execute(stmt).fetchall()
1136
+
1137
+ topics_set = set()
1138
+ for row in result:
1139
+ if row[0]:
1140
+ # Parse JSON array and add topics to set
1141
+ import json
1142
+
1143
+ try:
1144
+ topics = json.loads(row[0]) if isinstance(row[0], str) else row[0]
1145
+ if isinstance(topics, list):
1146
+ topics_set.update(topics)
1147
+ except Exception:
1148
+ pass
1149
+
1150
+ return list(topics_set)
1151
+
1152
+ except Exception as e:
1153
+ log_error(f"Exception reading from memory table: {e}")
1154
+ raise e
1155
+
1156
+ def get_user_memory(
1157
+ self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None
1158
+ ) -> Optional[UserMemory]:
1159
+ """Get a memory from the database.
1160
+
1161
+ Args:
1162
+ memory_id (str): The ID of the memory to get.
1163
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1164
+ user_id (Optional[str]): The user ID to filter by. Defaults to None.
1165
+
1166
+ Returns:
1167
+ Union[UserMemory, Dict[str, Any], None]:
1168
+ - When deserialize=True: UserMemory object
1169
+ - When deserialize=False: UserMemory dictionary
1170
+
1171
+ Raises:
1172
+ Exception: If an error occurs during retrieval.
1173
+ """
1174
+ try:
1175
+ table = self._get_table(table_type="memories")
1176
+ if table is None:
1177
+ return None
1178
+
1179
+ with self.Session() as sess, sess.begin():
1180
+ stmt = select(table).where(table.c.memory_id == memory_id)
1181
+ if user_id is not None:
1182
+ stmt = stmt.where(table.c.user_id == user_id)
1183
+
1184
+ result = sess.execute(stmt).fetchone()
1185
+ if not result:
1186
+ return None
1187
+
1188
+ memory_raw = result._mapping
1189
+ if not deserialize:
1190
+ return memory_raw
1191
+ return UserMemory.from_dict(memory_raw)
1192
+
1193
+ except Exception as e:
1194
+ log_error(f"Exception reading from memory table: {e}")
1195
+ return None
1196
+
1197
+ def get_user_memories(
1198
+ self,
1199
+ user_id: Optional[str] = None,
1200
+ agent_id: Optional[str] = None,
1201
+ team_id: Optional[str] = None,
1202
+ topics: Optional[List[str]] = None,
1203
+ search_content: Optional[str] = None,
1204
+ limit: Optional[int] = None,
1205
+ page: Optional[int] = None,
1206
+ sort_by: Optional[str] = None,
1207
+ sort_order: Optional[str] = None,
1208
+ deserialize: Optional[bool] = True,
1209
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1210
+ """Get all memories from the database as MemoryRow objects.
1211
+
1212
+ Args:
1213
+ user_id (Optional[str]): The ID of the user to filter by.
1214
+ agent_id (Optional[str]): The ID of the agent to filter by.
1215
+ team_id (Optional[str]): The ID of the team to filter by.
1216
+ topics (Optional[List[str]]): The topics to filter by.
1217
+ search_content (Optional[str]): The content to search for.
1218
+ limit (Optional[int]): The maximum number of memories to return.
1219
+ page (Optional[int]): The page number.
1220
+ sort_by (Optional[str]): The column to sort by.
1221
+ sort_order (Optional[str]): The order to sort by.
1222
+ deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True.
1223
+
1224
+
1225
+ Returns:
1226
+ Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
1227
+ - When deserialize=True: List of UserMemory objects
1228
+ - When deserialize=False: Tuple of (memory dictionaries, total count)
1229
+
1230
+ Raises:
1231
+ Exception: If an error occurs during retrieval.
1232
+ """
1233
+ try:
1234
+ table = self._get_table(table_type="memories")
1235
+ if table is None:
1236
+ return [] if deserialize else ([], 0)
1237
+
1238
+ with self.Session() as sess, sess.begin():
1239
+ stmt = select(table)
1240
+ # Filtering
1241
+ if user_id is not None:
1242
+ stmt = stmt.where(table.c.user_id == user_id)
1243
+ if agent_id is not None:
1244
+ stmt = stmt.where(table.c.agent_id == agent_id)
1245
+ if team_id is not None:
1246
+ stmt = stmt.where(table.c.team_id == team_id)
1247
+ if topics is not None:
1248
+ # MySQL JSON contains syntax
1249
+ topic_conditions = []
1250
+ for topic in topics:
1251
+ topic_conditions.append(func.json_contains(table.c.topics, f'"{topic}"'))
1252
+ stmt = stmt.where(and_(*topic_conditions))
1253
+ if search_content is not None:
1254
+ stmt = stmt.where(cast(table.c.memory, TEXT).ilike(f"%{search_content}%"))
1255
+
1256
+ # Get total count after applying filtering
1257
+ count_stmt = select(func.count()).select_from(stmt.alias())
1258
+ total_count = sess.execute(count_stmt).scalar()
1259
+
1260
+ # Sorting
1261
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
1262
+
1263
+ # Paginating
1264
+ if limit is not None:
1265
+ stmt = stmt.limit(limit)
1266
+ if page is not None:
1267
+ stmt = stmt.offset((page - 1) * limit)
1268
+
1269
+ result = sess.execute(stmt).fetchall()
1270
+ if not result:
1271
+ return [] if deserialize else ([], 0)
1272
+
1273
+ memories_raw = [record._mapping for record in result]
1274
+ if not deserialize:
1275
+ return memories_raw, total_count
1276
+
1277
+ return [UserMemory.from_dict(record) for record in memories_raw]
1278
+
1279
+ except Exception as e:
1280
+ log_error(f"Exception reading from memory table: {e}")
1281
+ raise e
1282
+
1283
+ def clear_memories(self) -> None:
1284
+ """Clear all user memories from the database."""
1285
+ try:
1286
+ table = self._get_table(table_type="memories")
1287
+ if table is None:
1288
+ return
1289
+
1290
+ with self.Session() as sess, sess.begin():
1291
+ sess.execute(table.delete())
1292
+ except Exception as e:
1293
+ log_error(f"Exception clearing user memories: {e}")
1294
+
1295
+ def get_user_memory_stats(
1296
+ self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None
1297
+ ) -> Tuple[List[Dict[str, Any]], int]:
1298
+ """Get user memories stats.
1299
+
1300
+ Args:
1301
+ limit (Optional[int]): The maximum number of user stats to return.
1302
+ page (Optional[int]): The page number.
1303
+
1304
+ Returns:
1305
+ Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count.
1306
+
1307
+ Example:
1308
+ (
1309
+ [
1310
+ {
1311
+ "user_id": "123",
1312
+ "total_memories": 10,
1313
+ "last_memory_updated_at": 1714560000,
1314
+ },
1315
+ ],
1316
+ total_count: 1,
1317
+ )
1318
+ """
1319
+ try:
1320
+ table = self._get_table(table_type="memories")
1321
+ if table is None:
1322
+ return [], 0
1323
+
1324
+ with self.Session() as sess, sess.begin():
1325
+ stmt = select(
1326
+ table.c.user_id,
1327
+ func.count(table.c.memory_id).label("total_memories"),
1328
+ func.max(table.c.updated_at).label("last_memory_updated_at"),
1329
+ )
1330
+
1331
+ if user_id is not None:
1332
+ stmt = stmt.where(table.c.user_id == user_id)
1333
+ else:
1334
+ stmt = stmt.where(table.c.user_id.is_not(None))
1335
+
1336
+ stmt = stmt.group_by(table.c.user_id)
1337
+ stmt = stmt.order_by(func.max(table.c.updated_at).desc())
1338
+
1339
+ count_stmt = select(func.count()).select_from(stmt.alias())
1340
+ total_count = sess.execute(count_stmt).scalar()
1341
+
1342
+ # Pagination
1343
+ if limit is not None:
1344
+ stmt = stmt.limit(limit)
1345
+ if page is not None:
1346
+ stmt = stmt.offset((page - 1) * limit)
1347
+
1348
+ result = sess.execute(stmt).fetchall()
1349
+ if not result:
1350
+ return [], 0
1351
+
1352
+ return [
1353
+ {
1354
+ "user_id": record.user_id, # type: ignore
1355
+ "total_memories": record.total_memories,
1356
+ "last_memory_updated_at": record.last_memory_updated_at,
1357
+ }
1358
+ for record in result
1359
+ ], total_count
1360
+
1361
+ except Exception as e:
1362
+ log_error(f"Exception getting user memory stats: {e}")
1363
+ return [], 0
1364
+
1365
+ def upsert_user_memory(
1366
+ self, memory: UserMemory, deserialize: Optional[bool] = True
1367
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
1368
+ """Upsert a user memory in the database.
1369
+
1370
+ Args:
1371
+ memory (UserMemory): The user memory to upsert.
1372
+ deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
1373
+
1374
+ Returns:
1375
+ Optional[Union[UserMemory, Dict[str, Any]]]:
1376
+ - When deserialize=True: UserMemory object
1377
+ - When deserialize=False: UserMemory dictionary
1378
+
1379
+ Raises:
1380
+ Exception: If an error occurs during upsert.
1381
+ """
1382
+ try:
1383
+ table = self._get_table(table_type="memories", create_table_if_not_found=True)
1384
+ if table is None:
1385
+ return None
1386
+
1387
+ with self.Session() as sess, sess.begin():
1388
+ if memory.memory_id is None:
1389
+ memory.memory_id = str(uuid4())
1390
+
1391
+ current_time = int(time.time())
1392
+
1393
+ stmt = mysql.insert(table).values(
1394
+ memory_id=memory.memory_id,
1395
+ memory=memory.memory,
1396
+ input=memory.input,
1397
+ user_id=memory.user_id,
1398
+ agent_id=memory.agent_id,
1399
+ team_id=memory.team_id,
1400
+ topics=memory.topics,
1401
+ feedback=memory.feedback,
1402
+ created_at=memory.created_at,
1403
+ updated_at=memory.created_at,
1404
+ )
1405
+ stmt = stmt.on_duplicate_key_update(
1406
+ memory=memory.memory,
1407
+ topics=memory.topics,
1408
+ input=memory.input,
1409
+ agent_id=memory.agent_id,
1410
+ team_id=memory.team_id,
1411
+ feedback=memory.feedback,
1412
+ updated_at=current_time,
1413
+ # Preserve created_at on update - don't overwrite existing value
1414
+ created_at=table.c.created_at,
1415
+ )
1416
+ sess.execute(stmt)
1417
+
1418
+ # Fetch the row
1419
+ select_stmt = select(table).where(table.c.memory_id == memory.memory_id)
1420
+ result = sess.execute(select_stmt)
1421
+ row = result.fetchone()
1422
+ if not row:
1423
+ return None
1424
+
1425
+ memory_raw = row._mapping
1426
+ if not memory_raw or not deserialize:
1427
+ return memory_raw
1428
+
1429
+ return UserMemory.from_dict(memory_raw)
1430
+
1431
+ except Exception as e:
1432
+ log_error(f"Exception upserting user memory: {e}")
1433
+ return None
1434
+
1435
+ def upsert_memories(
1436
+ self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False
1437
+ ) -> List[Union[UserMemory, Dict[str, Any]]]:
1438
+ """
1439
+ Bulk upsert multiple user memories for improved performance on large datasets.
1440
+
1441
+ Args:
1442
+ memories (List[UserMemory]): List of memories to upsert.
1443
+ deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True.
1444
+
1445
+ Returns:
1446
+ List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories.
1447
+
1448
+ Raises:
1449
+ Exception: If an error occurs during bulk upsert.
1450
+ """
1451
+ if not memories:
1452
+ return []
1453
+
1454
+ try:
1455
+ table = self._get_table(table_type="memories", create_table_if_not_found=True)
1456
+ if table is None:
1457
+ log_info("Memories table not available, falling back to individual upserts")
1458
+ return [
1459
+ result
1460
+ for memory in memories
1461
+ if memory is not None
1462
+ for result in [self.upsert_user_memory(memory, deserialize=deserialize)]
1463
+ if result is not None
1464
+ ]
1465
+
1466
+ # Prepare bulk data
1467
+ bulk_data = []
1468
+ current_time = int(time.time())
1469
+
1470
+ for memory in memories:
1471
+ if memory.memory_id is None:
1472
+ memory.memory_id = str(uuid4())
1473
+
1474
+ # Use preserved updated_at if flag is set and value exists, otherwise use current time
1475
+ updated_at = memory.updated_at if preserve_updated_at else current_time
1476
+
1477
+ bulk_data.append(
1478
+ {
1479
+ "memory_id": memory.memory_id,
1480
+ "memory": memory.memory,
1481
+ "input": memory.input,
1482
+ "user_id": memory.user_id,
1483
+ "agent_id": memory.agent_id,
1484
+ "team_id": memory.team_id,
1485
+ "topics": memory.topics,
1486
+ "feedback": memory.feedback,
1487
+ "created_at": memory.created_at,
1488
+ "updated_at": updated_at,
1489
+ }
1490
+ )
1491
+
1492
+ results: List[Union[UserMemory, Dict[str, Any]]] = []
1493
+
1494
+ with self.Session() as sess, sess.begin():
1495
+ # Bulk upsert memories using MySQL ON DUPLICATE KEY UPDATE
1496
+ stmt = mysql.insert(table)
1497
+ stmt = stmt.on_duplicate_key_update(
1498
+ memory=stmt.inserted.memory,
1499
+ topics=stmt.inserted.topics,
1500
+ input=stmt.inserted.input,
1501
+ agent_id=stmt.inserted.agent_id,
1502
+ team_id=stmt.inserted.team_id,
1503
+ feedback=stmt.inserted.feedback,
1504
+ updated_at=stmt.inserted.updated_at,
1505
+ # Preserve created_at on update
1506
+ created_at=table.c.created_at,
1507
+ )
1508
+ sess.execute(stmt, bulk_data)
1509
+
1510
+ # Fetch results
1511
+ memory_ids = [memory.memory_id for memory in memories if memory.memory_id]
1512
+ select_stmt = select(table).where(table.c.memory_id.in_(memory_ids))
1513
+ result = sess.execute(select_stmt).fetchall()
1514
+
1515
+ for row in result:
1516
+ memory_dict = dict(row._mapping)
1517
+ if deserialize:
1518
+ results.append(UserMemory.from_dict(memory_dict))
1519
+ else:
1520
+ results.append(memory_dict)
1521
+
1522
+ return results
1523
+
1524
+ except Exception as e:
1525
+ log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}")
1526
+ # Fallback to individual upserts
1527
+ return [
1528
+ result
1529
+ for memory in memories
1530
+ if memory is not None
1531
+ for result in [self.upsert_user_memory(memory, deserialize=deserialize)]
1532
+ if result is not None
1533
+ ]
1534
+
1535
+ # -- Metrics methods --
1536
+ def _get_all_sessions_for_metrics_calculation(
1537
+ self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
1538
+ ) -> List[Dict[str, Any]]:
1539
+ """
1540
+ Get all sessions of all types (agent, team, workflow) as raw dictionaries.
1541
+
1542
+ Args:
1543
+ start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None.
1544
+ end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None.
1545
+
1546
+ Returns:
1547
+ List[Dict[str, Any]]: List of session dictionaries with session_type field.
1548
+
1549
+ Raises:
1550
+ Exception: If an error occurs during retrieval.
1551
+ """
1552
+ try:
1553
+ table = self._get_table(table_type="sessions")
1554
+ if table is None:
1555
+ return []
1556
+
1557
+ stmt = select(
1558
+ table.c.user_id,
1559
+ table.c.session_data,
1560
+ table.c.runs,
1561
+ table.c.created_at,
1562
+ table.c.session_type,
1563
+ )
1564
+
1565
+ if start_timestamp is not None:
1566
+ stmt = stmt.where(table.c.created_at >= start_timestamp)
1567
+ if end_timestamp is not None:
1568
+ stmt = stmt.where(table.c.created_at <= end_timestamp)
1569
+
1570
+ with self.Session() as sess:
1571
+ result = sess.execute(stmt).fetchall()
1572
+ return [record._mapping for record in result]
1573
+
1574
+ except Exception as e:
1575
+ log_error(f"Exception reading from sessions table: {e}")
1576
+ raise e
1577
+
1578
+ def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]:
1579
+ """Get the first date for which metrics calculation is needed:
1580
+
1581
+ 1. If there are metrics records, return the date of the first day without a complete metrics record.
1582
+ 2. If there are no metrics records, return the date of the first recorded session.
1583
+ 3. If there are no metrics records and no sessions records, return None.
1584
+
1585
+ Args:
1586
+ table (Table): The table to get the starting date for.
1587
+
1588
+ Returns:
1589
+ Optional[date]: The starting date for which metrics calculation is needed.
1590
+ """
1591
+ with self.Session() as sess:
1592
+ stmt = select(table).order_by(table.c.date.desc()).limit(1)
1593
+ result = sess.execute(stmt).fetchone()
1594
+
1595
+ # 1. Return the date of the first day without a complete metrics record.
1596
+ if result is not None:
1597
+ if result.completed:
1598
+ return result._mapping["date"] + timedelta(days=1)
1599
+ else:
1600
+ return result._mapping["date"]
1601
+
1602
+ # 2. No metrics records. Return the date of the first recorded session.
1603
+ first_session, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False)
1604
+ if not isinstance(first_session, list):
1605
+ raise ValueError("Error obtaining session list to calculate metrics")
1606
+
1607
+ first_session_date = first_session[0]["created_at"] if first_session else None
1608
+
1609
+ # 3. No metrics records and no sessions records. Return None.
1610
+ if first_session_date is None:
1611
+ return None
1612
+
1613
+ return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date()
1614
+
1615
+ def calculate_metrics(self) -> Optional[list[dict]]:
1616
+ """Calculate metrics for all dates without complete metrics.
1617
+
1618
+ Returns:
1619
+ Optional[list[dict]]: The calculated metrics.
1620
+
1621
+ Raises:
1622
+ Exception: If an error occurs during metrics calculation.
1623
+ """
1624
+ try:
1625
+ table = self._get_table(table_type="metrics", create_table_if_not_found=True)
1626
+ if table is None:
1627
+ return None
1628
+
1629
+ starting_date = self._get_metrics_calculation_starting_date(table)
1630
+ if starting_date is None:
1631
+ log_info("No session data found. Won't calculate metrics.")
1632
+ return None
1633
+
1634
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
1635
+ if not dates_to_process:
1636
+ log_info("Metrics already calculated for all relevant dates.")
1637
+ return None
1638
+
1639
+ start_timestamp = int(
1640
+ datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp()
1641
+ )
1642
+ end_timestamp = int(
1643
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time())
1644
+ .replace(tzinfo=timezone.utc)
1645
+ .timestamp()
1646
+ )
1647
+
1648
+ sessions = self._get_all_sessions_for_metrics_calculation(
1649
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
1650
+ )
1651
+ all_sessions_data = fetch_all_sessions_data(
1652
+ sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp
1653
+ )
1654
+ if not all_sessions_data:
1655
+ log_info("No new session data found. Won't calculate metrics.")
1656
+ return None
1657
+
1658
+ results = []
1659
+ metrics_records = []
1660
+
1661
+ for date_to_process in dates_to_process:
1662
+ date_key = date_to_process.isoformat()
1663
+ sessions_for_date = all_sessions_data.get(date_key, {})
1664
+
1665
+ # Skip dates with no sessions
1666
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
1667
+ continue
1668
+
1669
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
1670
+ metrics_records.append(metrics_record)
1671
+
1672
+ if metrics_records:
1673
+ with self.Session() as sess, sess.begin():
1674
+ results = bulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records)
1675
+
1676
+ return results
1677
+
1678
+ except Exception as e:
1679
+ log_error(f"Exception refreshing metrics: {e}")
1680
+ return None
1681
+
1682
+ def get_metrics(
1683
+ self,
1684
+ starting_date: Optional[date] = None,
1685
+ ending_date: Optional[date] = None,
1686
+ ) -> Tuple[List[dict], Optional[int]]:
1687
+ """Get all metrics matching the given date range.
1688
+
1689
+ Args:
1690
+ starting_date (Optional[date]): The starting date to filter metrics by.
1691
+ ending_date (Optional[date]): The ending date to filter metrics by.
1692
+
1693
+ Returns:
1694
+ Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update.
1695
+
1696
+ Raises:
1697
+ Exception: If an error occurs during retrieval.
1698
+ """
1699
+ try:
1700
+ table = self._get_table(table_type="metrics", create_table_if_not_found=True)
1701
+ if table is None:
1702
+ return [], 0
1703
+
1704
+ with self.Session() as sess, sess.begin():
1705
+ stmt = select(table)
1706
+ if starting_date:
1707
+ stmt = stmt.where(table.c.date >= starting_date)
1708
+ if ending_date:
1709
+ stmt = stmt.where(table.c.date <= ending_date)
1710
+ result = sess.execute(stmt).fetchall()
1711
+ if not result:
1712
+ return [], None
1713
+
1714
+ # Get the latest updated_at
1715
+ latest_stmt = select(func.max(table.c.updated_at))
1716
+ latest_updated_at = sess.execute(latest_stmt).scalar()
1717
+
1718
+ return [row._mapping for row in result], latest_updated_at
1719
+
1720
+ except Exception as e:
1721
+ log_error(f"Exception getting metrics: {e}")
1722
+ return [], None
1723
+
1724
+ # -- Knowledge methods --
1725
+
1726
+ def delete_knowledge_content(self, id: str):
1727
+ """Delete a knowledge row from the database.
1728
+
1729
+ Args:
1730
+ id (str): The ID of the knowledge row to delete.
1731
+
1732
+ Raises:
1733
+ Exception: If an error occurs during deletion.
1734
+ """
1735
+ table = self._get_table(table_type="knowledge")
1736
+ if table is None:
1737
+ return None
1738
+
1739
+ try:
1740
+ with self.Session() as sess, sess.begin():
1741
+ stmt = table.delete().where(table.c.id == id)
1742
+ sess.execute(stmt)
1743
+
1744
+ except Exception as e:
1745
+ log_error(f"Exception deleting knowledge content: {e}")
1746
+
1747
+ def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1748
+ """Get a knowledge row from the database.
1749
+
1750
+ Args:
1751
+ id (str): The ID of the knowledge row to get.
1752
+
1753
+ Returns:
1754
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1755
+
1756
+ Raises:
1757
+ Exception: If an error occurs during retrieval.
1758
+ """
1759
+ table = self._get_table(table_type="knowledge")
1760
+ if table is None:
1761
+ return None
1762
+
1763
+ try:
1764
+ with self.Session() as sess, sess.begin():
1765
+ stmt = select(table).where(table.c.id == id)
1766
+ result = sess.execute(stmt).fetchone()
1767
+ if result is None:
1768
+ return None
1769
+ return KnowledgeRow.model_validate(result._mapping)
1770
+
1771
+ except Exception as e:
1772
+ log_error(f"Exception getting knowledge content: {e}")
1773
+ return None
1774
+
1775
+ def get_knowledge_contents(
1776
+ self,
1777
+ limit: Optional[int] = None,
1778
+ page: Optional[int] = None,
1779
+ sort_by: Optional[str] = None,
1780
+ sort_order: Optional[str] = None,
1781
+ ) -> Tuple[List[KnowledgeRow], int]:
1782
+ """Get all knowledge contents from the database.
1783
+
1784
+ Args:
1785
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1786
+ page (Optional[int]): The page number.
1787
+ sort_by (Optional[str]): The column to sort by.
1788
+ sort_order (Optional[str]): The order to sort by.
1789
+ create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist.
1790
+
1791
+ Returns:
1792
+ Tuple[List[KnowledgeRow], int]: The knowledge contents and total count.
1793
+
1794
+ Raises:
1795
+ Exception: If an error occurs during retrieval.
1796
+ """
1797
+ table = self._get_table(table_type="knowledge")
1798
+ if table is None:
1799
+ return [], 0
1800
+
1801
+ try:
1802
+ with self.Session() as sess, sess.begin():
1803
+ stmt = select(table)
1804
+
1805
+ # Apply sorting
1806
+ if sort_by is not None:
1807
+ stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1))
1808
+
1809
+ # Get total count before applying limit and pagination
1810
+ count_stmt = select(func.count()).select_from(stmt.alias())
1811
+ total_count = sess.execute(count_stmt).scalar()
1812
+
1813
+ # Apply pagination after count
1814
+ if limit is not None:
1815
+ stmt = stmt.limit(limit)
1816
+ if page is not None:
1817
+ stmt = stmt.offset((page - 1) * limit)
1818
+
1819
+ result = sess.execute(stmt).fetchall()
1820
+ if not result:
1821
+ return [], 0
1822
+
1823
+ return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count
1824
+
1825
+ except Exception as e:
1826
+ log_error(f"Exception getting knowledge contents: {e}")
1827
+ return [], 0
1828
+
1829
+ def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1830
+ """Upsert knowledge content in the database.
1831
+
1832
+ Args:
1833
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1834
+
1835
+ Returns:
1836
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1837
+
1838
+ Raises:
1839
+ Exception: If an error occurs during upsert.
1840
+ """
1841
+ try:
1842
+ table = self._get_table(table_type="knowledge", create_table_if_not_found=True)
1843
+ if table is None:
1844
+ return None
1845
+
1846
+ with self.Session() as sess, sess.begin():
1847
+ # Get the actual table columns to avoid "unconsumed column names" error
1848
+ table_columns = set(table.columns.keys())
1849
+
1850
+ # Only include fields that exist in the table and are not None
1851
+ insert_data = {}
1852
+ update_fields = {}
1853
+
1854
+ # Map of KnowledgeRow fields to table columns
1855
+ field_mapping = {
1856
+ "id": "id",
1857
+ "name": "name",
1858
+ "description": "description",
1859
+ "metadata": "metadata",
1860
+ "type": "type",
1861
+ "size": "size",
1862
+ "linked_to": "linked_to",
1863
+ "access_count": "access_count",
1864
+ "status": "status",
1865
+ "status_message": "status_message",
1866
+ "created_at": "created_at",
1867
+ "updated_at": "updated_at",
1868
+ "external_id": "external_id",
1869
+ }
1870
+
1871
+ # Build insert and update data only for fields that exist in the table
1872
+ for model_field, table_column in field_mapping.items():
1873
+ if table_column in table_columns:
1874
+ value = getattr(knowledge_row, model_field, None)
1875
+ if value is not None:
1876
+ insert_data[table_column] = value
1877
+ # Don't include ID in update_fields since it's the primary key
1878
+ if table_column != "id":
1879
+ update_fields[table_column] = value
1880
+
1881
+ # Ensure id is always included for the insert
1882
+ if "id" in table_columns and knowledge_row.id:
1883
+ insert_data["id"] = knowledge_row.id
1884
+
1885
+ # Handle case where update_fields is empty (all fields are None or don't exist in table)
1886
+ if not update_fields:
1887
+ # If we have insert_data, just do an insert without conflict resolution
1888
+ if insert_data:
1889
+ stmt = mysql.insert(table).values(insert_data)
1890
+ sess.execute(stmt)
1891
+ else:
1892
+ # If we have no data at all, this is an error
1893
+ log_error("No valid fields found for knowledge row upsert")
1894
+ return None
1895
+ else:
1896
+ # Normal upsert with conflict resolution
1897
+ stmt = mysql.insert(table).values(insert_data).on_duplicate_key_update(**update_fields)
1898
+ sess.execute(stmt)
1899
+
1900
+ return knowledge_row
1901
+
1902
+ except Exception as e:
1903
+ log_error(f"Error upserting knowledge row: {e}")
1904
+ return None
1905
+
1906
+ # -- Eval methods --
1907
+
1908
+ def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1909
+ """Create an EvalRunRecord in the database.
1910
+
1911
+ Args:
1912
+ eval_run (EvalRunRecord): The eval run to create.
1913
+
1914
+ Returns:
1915
+ Optional[EvalRunRecord]: The created eval run, or None if the operation fails.
1916
+
1917
+ Raises:
1918
+ Exception: If an error occurs during creation.
1919
+ """
1920
+ try:
1921
+ table = self._get_table(table_type="evals", create_table_if_not_found=True)
1922
+ if table is None:
1923
+ return None
1924
+
1925
+ with self.Session() as sess, sess.begin():
1926
+ current_time = int(time.time())
1927
+ stmt = mysql.insert(table).values(
1928
+ {"created_at": current_time, "updated_at": current_time, **eval_run.model_dump()}
1929
+ )
1930
+ sess.execute(stmt)
1931
+
1932
+ return eval_run
1933
+
1934
+ except Exception as e:
1935
+ log_error(f"Error creating eval run: {e}")
1936
+ return None
1937
+
1938
+ def delete_eval_run(self, eval_run_id: str) -> None:
1939
+ """Delete an eval run from the database.
1940
+
1941
+ Args:
1942
+ eval_run_id (str): The ID of the eval run to delete.
1943
+ """
1944
+ try:
1945
+ table = self._get_table(table_type="evals")
1946
+ if table is None:
1947
+ return
1948
+
1949
+ with self.Session() as sess, sess.begin():
1950
+ stmt = table.delete().where(table.c.run_id == eval_run_id)
1951
+ result = sess.execute(stmt)
1952
+ if result.rowcount == 0:
1953
+ log_error(f"No eval run found with ID: {eval_run_id}")
1954
+ else:
1955
+ log_debug(f"Deleted eval run with ID: {eval_run_id}")
1956
+
1957
+ except Exception as e:
1958
+ log_error(f"Error deleting eval run {eval_run_id}: {e}")
1959
+
1960
+ def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1961
+ """Delete multiple eval runs from the database.
1962
+
1963
+ Args:
1964
+ eval_run_ids (List[str]): List of eval run IDs to delete.
1965
+ """
1966
+ try:
1967
+ table = self._get_table(table_type="evals")
1968
+ if table is None:
1969
+ return
1970
+
1971
+ with self.Session() as sess, sess.begin():
1972
+ stmt = table.delete().where(table.c.run_id.in_(eval_run_ids))
1973
+ result = sess.execute(stmt)
1974
+ if result.rowcount == 0:
1975
+ log_error(f"No eval runs found with IDs: {eval_run_ids}")
1976
+ else:
1977
+ log_debug(f"Deleted {result.rowcount} eval runs")
1978
+
1979
+ except Exception as e:
1980
+ log_error(f"Error deleting eval runs {eval_run_ids}: {e}")
1981
+
1982
+ def get_eval_run(
1983
+ self, eval_run_id: str, deserialize: Optional[bool] = True
1984
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1985
+ """Get an eval run from the database.
1986
+
1987
+ Args:
1988
+ eval_run_id (str): The ID of the eval run to get.
1989
+ deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True.
1990
+
1991
+ Returns:
1992
+ Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1993
+ - When deserialize=True: EvalRunRecord object
1994
+ - When deserialize=False: EvalRun dictionary
1995
+
1996
+ Raises:
1997
+ Exception: If an error occurs during retrieval.
1998
+ """
1999
+ try:
2000
+ table = self._get_table(table_type="evals")
2001
+ if table is None:
2002
+ return None
2003
+
2004
+ with self.Session() as sess, sess.begin():
2005
+ stmt = select(table).where(table.c.run_id == eval_run_id)
2006
+ result = sess.execute(stmt).fetchone()
2007
+ if result is None:
2008
+ return None
2009
+
2010
+ eval_run_raw = result._mapping
2011
+ if not deserialize:
2012
+ return eval_run_raw
2013
+
2014
+ return EvalRunRecord.model_validate(eval_run_raw)
2015
+
2016
+ except Exception as e:
2017
+ log_error(f"Exception getting eval run {eval_run_id}: {e}")
2018
+ return None
2019
+
2020
+ def get_eval_runs(
2021
+ self,
2022
+ limit: Optional[int] = None,
2023
+ page: Optional[int] = None,
2024
+ sort_by: Optional[str] = None,
2025
+ sort_order: Optional[str] = None,
2026
+ agent_id: Optional[str] = None,
2027
+ team_id: Optional[str] = None,
2028
+ workflow_id: Optional[str] = None,
2029
+ model_id: Optional[str] = None,
2030
+ filter_type: Optional[EvalFilterType] = None,
2031
+ eval_type: Optional[List[EvalType]] = None,
2032
+ deserialize: Optional[bool] = True,
2033
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
2034
+ """Get all eval runs from the database.
2035
+
2036
+ Args:
2037
+ limit (Optional[int]): The maximum number of eval runs to return.
2038
+ page (Optional[int]): The page number.
2039
+ sort_by (Optional[str]): The column to sort by.
2040
+ sort_order (Optional[str]): The order to sort by.
2041
+ agent_id (Optional[str]): The ID of the agent to filter by.
2042
+ team_id (Optional[str]): The ID of the team to filter by.
2043
+ workflow_id (Optional[str]): The ID of the workflow to filter by.
2044
+ model_id (Optional[str]): The ID of the model to filter by.
2045
+ eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by.
2046
+ filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow).
2047
+ deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True.
2048
+ create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist.
2049
+
2050
+ Returns:
2051
+ Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
2052
+ - When deserialize=True: List of EvalRunRecord objects
2053
+ - When deserialize=False: List of dictionaries
2054
+
2055
+ Raises:
2056
+ Exception: If an error occurs during retrieval.
2057
+ """
2058
+ try:
2059
+ table = self._get_table(table_type="evals")
2060
+ if table is None:
2061
+ return [] if deserialize else ([], 0)
2062
+
2063
+ with self.Session() as sess, sess.begin():
2064
+ stmt = select(table)
2065
+
2066
+ # Filtering
2067
+ if agent_id is not None:
2068
+ stmt = stmt.where(table.c.agent_id == agent_id)
2069
+ if team_id is not None:
2070
+ stmt = stmt.where(table.c.team_id == team_id)
2071
+ if workflow_id is not None:
2072
+ stmt = stmt.where(table.c.workflow_id == workflow_id)
2073
+ if model_id is not None:
2074
+ stmt = stmt.where(table.c.model_id == model_id)
2075
+ if eval_type is not None and len(eval_type) > 0:
2076
+ stmt = stmt.where(table.c.eval_type.in_(eval_type))
2077
+ if filter_type is not None:
2078
+ if filter_type == EvalFilterType.AGENT:
2079
+ stmt = stmt.where(table.c.agent_id.is_not(None))
2080
+ elif filter_type == EvalFilterType.TEAM:
2081
+ stmt = stmt.where(table.c.team_id.is_not(None))
2082
+ elif filter_type == EvalFilterType.WORKFLOW:
2083
+ stmt = stmt.where(table.c.workflow_id.is_not(None))
2084
+
2085
+ # Get total count after applying filtering
2086
+ count_stmt = select(func.count()).select_from(stmt.alias())
2087
+ total_count = sess.execute(count_stmt).scalar()
2088
+
2089
+ # Sorting
2090
+ if sort_by is None:
2091
+ stmt = stmt.order_by(table.c.created_at.desc())
2092
+ else:
2093
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
2094
+
2095
+ # Paginating
2096
+ if limit is not None:
2097
+ stmt = stmt.limit(limit)
2098
+ if page is not None:
2099
+ stmt = stmt.offset((page - 1) * limit)
2100
+
2101
+ result = sess.execute(stmt).fetchall()
2102
+ if not result:
2103
+ return [] if deserialize else ([], 0)
2104
+
2105
+ eval_runs_raw = [row._mapping for row in result]
2106
+ if not deserialize:
2107
+ return eval_runs_raw, total_count
2108
+
2109
+ return [EvalRunRecord.model_validate(row) for row in eval_runs_raw]
2110
+
2111
+ except Exception as e:
2112
+ log_error(f"Exception getting eval runs: {e}")
2113
+ raise e
2114
+
2115
+ def rename_eval_run(
2116
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
2117
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
2118
+ """Upsert the name of an eval run in the database, returning raw dictionary.
2119
+
2120
+ Args:
2121
+ eval_run_id (str): The ID of the eval run to update.
2122
+ name (str): The new name of the eval run.
2123
+
2124
+ Returns:
2125
+ Optional[Dict[str, Any]]: The updated eval run, or None if the operation fails.
2126
+
2127
+ Raises:
2128
+ Exception: If an error occurs during update.
2129
+ """
2130
+ try:
2131
+ table = self._get_table(table_type="evals")
2132
+ if table is None:
2133
+ return None
2134
+
2135
+ with self.Session() as sess, sess.begin():
2136
+ stmt = (
2137
+ table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time()))
2138
+ )
2139
+ sess.execute(stmt)
2140
+
2141
+ eval_run_raw = self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize)
2142
+ if not eval_run_raw or not deserialize:
2143
+ return eval_run_raw
2144
+
2145
+ return EvalRunRecord.model_validate(eval_run_raw)
2146
+
2147
+ except Exception as e:
2148
+ log_error(f"Error upserting eval run name {eval_run_id}: {e}")
2149
+ return None
2150
+
2151
+ # -- Culture methods --
2152
+
2153
+ def clear_cultural_knowledge(self) -> None:
2154
+ """Delete all cultural knowledge from the database.
2155
+
2156
+ Raises:
2157
+ Exception: If an error occurs during deletion.
2158
+ """
2159
+ try:
2160
+ table = self._get_table(table_type="culture")
2161
+ if table is None:
2162
+ return
2163
+
2164
+ with self.Session() as sess, sess.begin():
2165
+ sess.execute(table.delete())
2166
+
2167
+ except Exception as e:
2168
+ log_warning(f"Exception deleting all cultural knowledge: {e}")
2169
+ raise e
2170
+
2171
+ def delete_cultural_knowledge(self, id: str) -> None:
2172
+ """Delete a cultural knowledge entry from the database.
2173
+
2174
+ Args:
2175
+ id (str): The ID of the cultural knowledge to delete.
2176
+
2177
+ Raises:
2178
+ Exception: If an error occurs during deletion.
2179
+ """
2180
+ try:
2181
+ table = self._get_table(table_type="culture")
2182
+ if table is None:
2183
+ return
2184
+
2185
+ with self.Session() as sess, sess.begin():
2186
+ delete_stmt = table.delete().where(table.c.id == id)
2187
+ result = sess.execute(delete_stmt)
2188
+
2189
+ success = result.rowcount > 0
2190
+ if success:
2191
+ log_debug(f"Successfully deleted cultural knowledge id: {id}")
2192
+ else:
2193
+ log_debug(f"No cultural knowledge found with id: {id}")
2194
+
2195
+ except Exception as e:
2196
+ log_error(f"Error deleting cultural knowledge: {e}")
2197
+ raise e
2198
+
2199
+ def get_cultural_knowledge(
2200
+ self, id: str, deserialize: Optional[bool] = True
2201
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
2202
+ """Get a cultural knowledge entry from the database.
2203
+
2204
+ Args:
2205
+ id (str): The ID of the cultural knowledge to get.
2206
+ deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True.
2207
+
2208
+ Returns:
2209
+ Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge entry, or None if it doesn't exist.
2210
+
2211
+ Raises:
2212
+ Exception: If an error occurs during retrieval.
2213
+ """
2214
+ try:
2215
+ table = self._get_table(table_type="culture")
2216
+ if table is None:
2217
+ return None
2218
+
2219
+ with self.Session() as sess, sess.begin():
2220
+ stmt = select(table).where(table.c.id == id)
2221
+ result = sess.execute(stmt).fetchone()
2222
+ if result is None:
2223
+ return None
2224
+
2225
+ db_row = dict(result._mapping)
2226
+ if not db_row or not deserialize:
2227
+ return db_row
2228
+
2229
+ return deserialize_cultural_knowledge_from_db(db_row)
2230
+
2231
+ except Exception as e:
2232
+ log_error(f"Exception reading from cultural knowledge table: {e}")
2233
+ raise e
2234
+
2235
+ def get_all_cultural_knowledge(
2236
+ self,
2237
+ name: Optional[str] = None,
2238
+ agent_id: Optional[str] = None,
2239
+ team_id: Optional[str] = None,
2240
+ limit: Optional[int] = None,
2241
+ page: Optional[int] = None,
2242
+ sort_by: Optional[str] = None,
2243
+ sort_order: Optional[str] = None,
2244
+ deserialize: Optional[bool] = True,
2245
+ ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
2246
+ """Get all cultural knowledge from the database as CulturalKnowledge objects.
2247
+
2248
+ Args:
2249
+ name (Optional[str]): The name of the cultural knowledge to filter by.
2250
+ agent_id (Optional[str]): The ID of the agent to filter by.
2251
+ team_id (Optional[str]): The ID of the team to filter by.
2252
+ limit (Optional[int]): The maximum number of cultural knowledge entries to return.
2253
+ page (Optional[int]): The page number.
2254
+ sort_by (Optional[str]): The column to sort by.
2255
+ sort_order (Optional[str]): The order to sort by.
2256
+ deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True.
2257
+
2258
+ Returns:
2259
+ Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]:
2260
+ - When deserialize=True: List of CulturalKnowledge objects
2261
+ - When deserialize=False: List of CulturalKnowledge dictionaries and total count
2262
+
2263
+ Raises:
2264
+ Exception: If an error occurs during retrieval.
2265
+ """
2266
+ try:
2267
+ table = self._get_table(table_type="culture")
2268
+ if table is None:
2269
+ return [] if deserialize else ([], 0)
2270
+
2271
+ with self.Session() as sess, sess.begin():
2272
+ stmt = select(table)
2273
+
2274
+ # Filtering
2275
+ if name is not None:
2276
+ stmt = stmt.where(table.c.name == name)
2277
+ if agent_id is not None:
2278
+ stmt = stmt.where(table.c.agent_id == agent_id)
2279
+ if team_id is not None:
2280
+ stmt = stmt.where(table.c.team_id == team_id)
2281
+
2282
+ # Get total count after applying filtering
2283
+ count_stmt = select(func.count()).select_from(stmt.alias())
2284
+ total_count = sess.execute(count_stmt).scalar()
2285
+
2286
+ # Sorting
2287
+ stmt = apply_sorting(stmt, table, sort_by, sort_order)
2288
+ # Paginating
2289
+ if limit is not None:
2290
+ stmt = stmt.limit(limit)
2291
+ if page is not None:
2292
+ stmt = stmt.offset((page - 1) * limit)
2293
+
2294
+ result = sess.execute(stmt).fetchall()
2295
+ if not result:
2296
+ return [] if deserialize else ([], 0)
2297
+
2298
+ db_rows = [dict(record._mapping) for record in result]
2299
+
2300
+ if not deserialize:
2301
+ return db_rows, total_count
2302
+
2303
+ return [deserialize_cultural_knowledge_from_db(row) for row in db_rows]
2304
+
2305
+ except Exception as e:
2306
+ log_error(f"Error reading from cultural knowledge table: {e}")
2307
+ raise e
2308
+
2309
+ def upsert_cultural_knowledge(
2310
+ self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True
2311
+ ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]:
2312
+ """Upsert a cultural knowledge entry into the database.
2313
+
2314
+ Args:
2315
+ cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert.
2316
+ deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True.
2317
+
2318
+ Returns:
2319
+ Optional[CulturalKnowledge]: The upserted cultural knowledge entry.
2320
+
2321
+ Raises:
2322
+ Exception: If an error occurs during upsert.
2323
+ """
2324
+ try:
2325
+ table = self._get_table(table_type="culture", create_table_if_not_found=True)
2326
+ if table is None:
2327
+ return None
2328
+
2329
+ if cultural_knowledge.id is None:
2330
+ cultural_knowledge.id = str(uuid4())
2331
+
2332
+ # Serialize content, categories, and notes into a JSON dict for DB storage
2333
+ content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge)
2334
+
2335
+ with self.Session() as sess, sess.begin():
2336
+ stmt = mysql.insert(table).values(
2337
+ id=cultural_knowledge.id,
2338
+ name=cultural_knowledge.name,
2339
+ summary=cultural_knowledge.summary,
2340
+ content=content_dict if content_dict else None,
2341
+ metadata=cultural_knowledge.metadata,
2342
+ input=cultural_knowledge.input,
2343
+ created_at=cultural_knowledge.created_at,
2344
+ updated_at=int(time.time()),
2345
+ agent_id=cultural_knowledge.agent_id,
2346
+ team_id=cultural_knowledge.team_id,
2347
+ )
2348
+ stmt = stmt.on_duplicate_key_update(
2349
+ name=cultural_knowledge.name,
2350
+ summary=cultural_knowledge.summary,
2351
+ content=content_dict if content_dict else None,
2352
+ metadata=cultural_knowledge.metadata,
2353
+ input=cultural_knowledge.input,
2354
+ updated_at=int(time.time()),
2355
+ agent_id=cultural_knowledge.agent_id,
2356
+ team_id=cultural_knowledge.team_id,
2357
+ )
2358
+ sess.execute(stmt)
2359
+
2360
+ # Fetch the inserted/updated row
2361
+ return self.get_cultural_knowledge(id=cultural_knowledge.id, deserialize=deserialize)
2362
+
2363
+ except Exception as e:
2364
+ log_error(f"Error upserting cultural knowledge: {e}")
2365
+ raise e
2366
+
2367
+ # -- Migrations --
2368
+
2369
+ def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str):
2370
+ """Migrate all content in the given table to the right v2 table"""
2371
+
2372
+ from agno.db.migrations.v1_to_v2 import (
2373
+ get_all_table_content,
2374
+ parse_agent_sessions,
2375
+ parse_memories,
2376
+ parse_team_sessions,
2377
+ parse_workflow_sessions,
2378
+ )
2379
+
2380
+ # Get all content from the old table
2381
+ old_content: list[dict[str, Any]] = get_all_table_content(
2382
+ db=self,
2383
+ db_schema=v1_db_schema,
2384
+ table_name=v1_table_name,
2385
+ )
2386
+ if not old_content:
2387
+ log_info(f"No content to migrate from table {v1_table_name}")
2388
+ return
2389
+
2390
+ # Parse the content into the new format
2391
+ memories: List[UserMemory] = []
2392
+ sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = []
2393
+ if v1_table_type == "agent_sessions":
2394
+ sessions = parse_agent_sessions(old_content)
2395
+ elif v1_table_type == "team_sessions":
2396
+ sessions = parse_team_sessions(old_content)
2397
+ elif v1_table_type == "workflow_sessions":
2398
+ sessions = parse_workflow_sessions(old_content)
2399
+ elif v1_table_type == "memories":
2400
+ memories = parse_memories(old_content)
2401
+ else:
2402
+ raise ValueError(f"Invalid table type: {v1_table_type}")
2403
+
2404
+ # Insert the new content into the new table
2405
+ if v1_table_type == "agent_sessions":
2406
+ for session in sessions:
2407
+ self.upsert_session(session)
2408
+ log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table_name}")
2409
+
2410
+ elif v1_table_type == "team_sessions":
2411
+ for session in sessions:
2412
+ self.upsert_session(session)
2413
+ log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table_name}")
2414
+
2415
+ elif v1_table_type == "workflow_sessions":
2416
+ for session in sessions:
2417
+ self.upsert_session(session)
2418
+ log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table_name}")
2419
+
2420
+ elif v1_table_type == "memories":
2421
+ for memory in memories:
2422
+ self.upsert_user_memory(memory)
2423
+ log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}")
2424
+
2425
+ # --- Traces ---
2426
+ def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None):
2427
+ """Build base query for traces with aggregated span counts.
2428
+
2429
+ Args:
2430
+ table: The traces table.
2431
+ spans_table: The spans table (optional).
2432
+
2433
+ Returns:
2434
+ SQLAlchemy select statement with total_spans and error_count calculated dynamically.
2435
+ """
2436
+ from sqlalchemy import case, literal
2437
+
2438
+ if spans_table is not None:
2439
+ # JOIN with spans table to calculate total_spans and error_count
2440
+ return (
2441
+ select(
2442
+ table,
2443
+ func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"),
2444
+ func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label(
2445
+ "error_count"
2446
+ ),
2447
+ )
2448
+ .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id))
2449
+ .group_by(table.c.trace_id)
2450
+ )
2451
+ else:
2452
+ # Fallback if spans table doesn't exist
2453
+ return select(table, literal(0).label("total_spans"), literal(0).label("error_count"))
2454
+
2455
+ def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col):
2456
+ """Build a SQL CASE expression that returns the component level for a trace.
2457
+
2458
+ Component levels (higher = more important):
2459
+ - 3: Workflow root (.run or .arun with workflow_id)
2460
+ - 2: Team root (.run or .arun with team_id)
2461
+ - 1: Agent root (.run or .arun with agent_id)
2462
+ - 0: Child span (not a root)
2463
+
2464
+ Args:
2465
+ workflow_id_col: SQL column/expression for workflow_id
2466
+ team_id_col: SQL column/expression for team_id
2467
+ agent_id_col: SQL column/expression for agent_id
2468
+ name_col: SQL column/expression for name
2469
+
2470
+ Returns:
2471
+ SQLAlchemy CASE expression returning the component level as an integer.
2472
+ """
2473
+ from sqlalchemy import and_, case, or_
2474
+
2475
+ is_root_name = or_(name_col.like("%.run%"), name_col.like("%.arun%"))
2476
+
2477
+ return case(
2478
+ # Workflow root (level 3)
2479
+ (and_(workflow_id_col.isnot(None), is_root_name), 3),
2480
+ # Team root (level 2)
2481
+ (and_(team_id_col.isnot(None), is_root_name), 2),
2482
+ # Agent root (level 1)
2483
+ (and_(agent_id_col.isnot(None), is_root_name), 1),
2484
+ # Child span or unknown (level 0)
2485
+ else_=0,
2486
+ )
2487
+
2488
+ def upsert_trace(self, trace: "Trace") -> None:
2489
+ """Create or update a single trace record in the database.
2490
+
2491
+ Uses INSERT ... ON DUPLICATE KEY UPDATE (upsert) to handle concurrent inserts
2492
+ atomically and avoid race conditions.
2493
+
2494
+ Args:
2495
+ trace: The Trace object to store (one per trace_id).
2496
+ """
2497
+ from sqlalchemy import case
2498
+
2499
+ try:
2500
+ table = self._get_table(table_type="traces", create_table_if_not_found=True)
2501
+ if table is None:
2502
+ return
2503
+
2504
+ trace_dict = trace.to_dict()
2505
+ trace_dict.pop("total_spans", None)
2506
+ trace_dict.pop("error_count", None)
2507
+
2508
+ with self.Session() as sess, sess.begin():
2509
+ # Use upsert to handle concurrent inserts atomically
2510
+ # On conflict, update fields while preserving existing non-null context values
2511
+ # and keeping the earliest start_time
2512
+ insert_stmt = mysql.insert(table).values(trace_dict)
2513
+
2514
+ # Build component level expressions for comparing trace priority
2515
+ new_level = self._get_trace_component_level_expr(
2516
+ insert_stmt.inserted.workflow_id,
2517
+ insert_stmt.inserted.team_id,
2518
+ insert_stmt.inserted.agent_id,
2519
+ insert_stmt.inserted.name,
2520
+ )
2521
+ existing_level = self._get_trace_component_level_expr(
2522
+ table.c.workflow_id,
2523
+ table.c.team_id,
2524
+ table.c.agent_id,
2525
+ table.c.name,
2526
+ )
2527
+
2528
+ # Build the ON DUPLICATE KEY UPDATE clause
2529
+ # Use LEAST for start_time, GREATEST for end_time to capture full trace duration
2530
+ # MySQL stores timestamps as ISO strings, so string comparison works for ISO format
2531
+ # Duration is calculated using TIMESTAMPDIFF in microseconds then converted to ms
2532
+ upsert_stmt = insert_stmt.on_duplicate_key_update(
2533
+ end_time=func.greatest(table.c.end_time, insert_stmt.inserted.end_time),
2534
+ start_time=func.least(table.c.start_time, insert_stmt.inserted.start_time),
2535
+ # Calculate duration in milliseconds using TIMESTAMPDIFF
2536
+ # TIMESTAMPDIFF(MICROSECOND, start, end) / 1000 gives milliseconds
2537
+ duration_ms=func.timestampdiff(
2538
+ text("MICROSECOND"),
2539
+ func.least(table.c.start_time, insert_stmt.inserted.start_time),
2540
+ func.greatest(table.c.end_time, insert_stmt.inserted.end_time),
2541
+ )
2542
+ / 1000,
2543
+ status=insert_stmt.inserted.status,
2544
+ # Update name only if new trace is from a higher-level component
2545
+ # Priority: workflow (3) > team (2) > agent (1) > child spans (0)
2546
+ name=case(
2547
+ (new_level > existing_level, insert_stmt.inserted.name),
2548
+ else_=table.c.name,
2549
+ ),
2550
+ # Preserve existing non-null context values using COALESCE
2551
+ run_id=func.coalesce(insert_stmt.inserted.run_id, table.c.run_id),
2552
+ session_id=func.coalesce(insert_stmt.inserted.session_id, table.c.session_id),
2553
+ user_id=func.coalesce(insert_stmt.inserted.user_id, table.c.user_id),
2554
+ agent_id=func.coalesce(insert_stmt.inserted.agent_id, table.c.agent_id),
2555
+ team_id=func.coalesce(insert_stmt.inserted.team_id, table.c.team_id),
2556
+ workflow_id=func.coalesce(insert_stmt.inserted.workflow_id, table.c.workflow_id),
2557
+ )
2558
+ sess.execute(upsert_stmt)
2559
+
2560
+ except Exception as e:
2561
+ log_error(f"Error creating trace: {e}")
2562
+ # Don't raise - tracing should not break the main application flow
2563
+
2564
+ def get_trace(
2565
+ self,
2566
+ trace_id: Optional[str] = None,
2567
+ run_id: Optional[str] = None,
2568
+ ):
2569
+ """Get a single trace by trace_id or other filters.
2570
+
2571
+ Args:
2572
+ trace_id: The unique trace identifier.
2573
+ run_id: Filter by run ID (returns first match).
2574
+
2575
+ Returns:
2576
+ Optional[Trace]: The trace if found, None otherwise.
2577
+
2578
+ Note:
2579
+ If multiple filters are provided, trace_id takes precedence.
2580
+ For other filters, the most recent trace is returned.
2581
+ """
2582
+ try:
2583
+ from agno.tracing.schemas import Trace
2584
+
2585
+ table = self._get_table(table_type="traces")
2586
+ if table is None:
2587
+ return None
2588
+
2589
+ # Get spans table for JOIN
2590
+ spans_table = self._get_table(table_type="spans")
2591
+
2592
+ with self.Session() as sess:
2593
+ # Build query with aggregated span counts
2594
+ stmt = self._get_traces_base_query(table, spans_table)
2595
+
2596
+ if trace_id:
2597
+ stmt = stmt.where(table.c.trace_id == trace_id)
2598
+ elif run_id:
2599
+ stmt = stmt.where(table.c.run_id == run_id)
2600
+ else:
2601
+ log_debug("get_trace called without any filter parameters")
2602
+ return None
2603
+
2604
+ # Order by most recent and get first result
2605
+ stmt = stmt.order_by(table.c.start_time.desc()).limit(1)
2606
+ result = sess.execute(stmt).fetchone()
2607
+
2608
+ if result:
2609
+ return Trace.from_dict(dict(result._mapping))
2610
+ return None
2611
+
2612
+ except Exception as e:
2613
+ log_error(f"Error getting trace: {e}")
2614
+ return None
2615
+
2616
+ def get_traces(
2617
+ self,
2618
+ run_id: Optional[str] = None,
2619
+ session_id: Optional[str] = None,
2620
+ user_id: Optional[str] = None,
2621
+ agent_id: Optional[str] = None,
2622
+ team_id: Optional[str] = None,
2623
+ workflow_id: Optional[str] = None,
2624
+ status: Optional[str] = None,
2625
+ start_time: Optional[datetime] = None,
2626
+ end_time: Optional[datetime] = None,
2627
+ limit: Optional[int] = 20,
2628
+ page: Optional[int] = 1,
2629
+ ) -> tuple[List, int]:
2630
+ """Get traces matching the provided filters with pagination.
2631
+
2632
+ Args:
2633
+ run_id: Filter by run ID.
2634
+ session_id: Filter by session ID.
2635
+ user_id: Filter by user ID.
2636
+ agent_id: Filter by agent ID.
2637
+ team_id: Filter by team ID.
2638
+ workflow_id: Filter by workflow ID.
2639
+ status: Filter by status (OK, ERROR, UNSET).
2640
+ start_time: Filter traces starting after this datetime.
2641
+ end_time: Filter traces ending before this datetime.
2642
+ limit: Maximum number of traces to return per page.
2643
+ page: Page number (1-indexed).
2644
+
2645
+ Returns:
2646
+ tuple[List[Trace], int]: Tuple of (list of matching traces, total count).
2647
+ """
2648
+ try:
2649
+ from agno.tracing.schemas import Trace
2650
+
2651
+ log_debug(
2652
+ f"get_traces called with filters: run_id={run_id}, session_id={session_id}, user_id={user_id}, agent_id={agent_id}, page={page}, limit={limit}"
2653
+ )
2654
+
2655
+ table = self._get_table(table_type="traces")
2656
+ if table is None:
2657
+ log_debug("Traces table not found")
2658
+ return [], 0
2659
+
2660
+ # Get spans table for JOIN
2661
+ spans_table = self._get_table(table_type="spans")
2662
+
2663
+ with self.Session() as sess:
2664
+ # Build base query with aggregated span counts
2665
+ base_stmt = self._get_traces_base_query(table, spans_table)
2666
+
2667
+ # Apply filters
2668
+ if run_id:
2669
+ base_stmt = base_stmt.where(table.c.run_id == run_id)
2670
+ if session_id:
2671
+ base_stmt = base_stmt.where(table.c.session_id == session_id)
2672
+ if user_id:
2673
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2674
+ if agent_id:
2675
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2676
+ if team_id:
2677
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2678
+ if workflow_id:
2679
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2680
+ if status:
2681
+ base_stmt = base_stmt.where(table.c.status == status)
2682
+ if start_time:
2683
+ # Convert datetime to ISO string for comparison
2684
+ base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat())
2685
+ if end_time:
2686
+ # Convert datetime to ISO string for comparison
2687
+ base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat())
2688
+
2689
+ # Get total count
2690
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2691
+ total_count = sess.execute(count_stmt).scalar() or 0
2692
+
2693
+ # Apply pagination
2694
+ offset = (page - 1) * limit if page and limit else 0
2695
+ paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset)
2696
+
2697
+ results = sess.execute(paginated_stmt).fetchall()
2698
+
2699
+ traces = [Trace.from_dict(dict(row._mapping)) for row in results]
2700
+ return traces, total_count
2701
+
2702
+ except Exception as e:
2703
+ log_error(f"Error getting traces: {e}")
2704
+ return [], 0
2705
+
2706
+ def get_trace_stats(
2707
+ self,
2708
+ user_id: Optional[str] = None,
2709
+ agent_id: Optional[str] = None,
2710
+ team_id: Optional[str] = None,
2711
+ workflow_id: Optional[str] = None,
2712
+ start_time: Optional[datetime] = None,
2713
+ end_time: Optional[datetime] = None,
2714
+ limit: Optional[int] = 20,
2715
+ page: Optional[int] = 1,
2716
+ ) -> tuple[List[Dict[str, Any]], int]:
2717
+ """Get trace statistics grouped by session.
2718
+
2719
+ Args:
2720
+ user_id: Filter by user ID.
2721
+ agent_id: Filter by agent ID.
2722
+ team_id: Filter by team ID.
2723
+ workflow_id: Filter by workflow ID.
2724
+ start_time: Filter sessions with traces created after this datetime.
2725
+ end_time: Filter sessions with traces created before this datetime.
2726
+ limit: Maximum number of sessions to return per page.
2727
+ page: Page number (1-indexed).
2728
+
2729
+ Returns:
2730
+ tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count).
2731
+ Each dict contains: session_id, user_id, agent_id, team_id, total_traces,
2732
+ workflow_id, first_trace_at, last_trace_at.
2733
+ """
2734
+ try:
2735
+ table = self._get_table(table_type="traces")
2736
+ if table is None:
2737
+ log_debug("Traces table not found")
2738
+ return [], 0
2739
+
2740
+ with self.Session() as sess:
2741
+ # Build base query grouped by session_id
2742
+ base_stmt = (
2743
+ select(
2744
+ table.c.session_id,
2745
+ table.c.user_id,
2746
+ table.c.agent_id,
2747
+ table.c.team_id,
2748
+ table.c.workflow_id,
2749
+ func.count(table.c.trace_id).label("total_traces"),
2750
+ func.min(table.c.created_at).label("first_trace_at"),
2751
+ func.max(table.c.created_at).label("last_trace_at"),
2752
+ )
2753
+ .where(table.c.session_id.isnot(None)) # Only sessions with session_id
2754
+ .group_by(
2755
+ table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id
2756
+ )
2757
+ )
2758
+
2759
+ # Apply filters
2760
+ if user_id:
2761
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2762
+ if workflow_id:
2763
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2764
+ if team_id:
2765
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2766
+ if agent_id:
2767
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2768
+ if start_time:
2769
+ # Convert datetime to ISO string for comparison
2770
+ base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat())
2771
+ if end_time:
2772
+ # Convert datetime to ISO string for comparison
2773
+ base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat())
2774
+
2775
+ # Get total count of sessions
2776
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2777
+ total_count = sess.execute(count_stmt).scalar() or 0
2778
+
2779
+ # Apply pagination and ordering
2780
+ offset = (page - 1) * limit if page and limit else 0
2781
+ paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset)
2782
+
2783
+ results = sess.execute(paginated_stmt).fetchall()
2784
+
2785
+ # Convert to list of dicts with datetime objects
2786
+ stats_list = []
2787
+ for row in results:
2788
+ # Convert ISO strings to datetime objects
2789
+ first_trace_at_str = row.first_trace_at
2790
+ last_trace_at_str = row.last_trace_at
2791
+
2792
+ # Parse ISO format strings to datetime objects
2793
+ first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00"))
2794
+ last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00"))
2795
+
2796
+ stats_list.append(
2797
+ {
2798
+ "session_id": row.session_id,
2799
+ "user_id": row.user_id,
2800
+ "agent_id": row.agent_id,
2801
+ "team_id": row.team_id,
2802
+ "workflow_id": row.workflow_id,
2803
+ "total_traces": row.total_traces,
2804
+ "first_trace_at": first_trace_at,
2805
+ "last_trace_at": last_trace_at,
2806
+ }
2807
+ )
2808
+
2809
+ return stats_list, total_count
2810
+
2811
+ except Exception as e:
2812
+ log_error(f"Error getting trace stats: {e}")
2813
+ return [], 0
2814
+
2815
+ # --- Spans ---
2816
+ def create_span(self, span: "Span") -> None:
2817
+ """Create a single span in the database.
2818
+
2819
+ Args:
2820
+ span: The Span object to store.
2821
+ """
2822
+ try:
2823
+ table = self._get_table(table_type="spans", create_table_if_not_found=True)
2824
+ if table is None:
2825
+ return
2826
+
2827
+ with self.Session() as sess, sess.begin():
2828
+ stmt = mysql.insert(table).values(span.to_dict())
2829
+ sess.execute(stmt)
2830
+
2831
+ except Exception as e:
2832
+ log_error(f"Error creating span: {e}")
2833
+
2834
+ def create_spans(self, spans: List) -> None:
2835
+ """Create multiple spans in the database as a batch.
2836
+
2837
+ Args:
2838
+ spans: List of Span objects to store.
2839
+ """
2840
+ if not spans:
2841
+ return
2842
+
2843
+ try:
2844
+ table = self._get_table(table_type="spans", create_table_if_not_found=True)
2845
+ if table is None:
2846
+ return
2847
+
2848
+ with self.Session() as sess, sess.begin():
2849
+ for span in spans:
2850
+ stmt = mysql.insert(table).values(span.to_dict())
2851
+ sess.execute(stmt)
2852
+
2853
+ except Exception as e:
2854
+ log_error(f"Error creating spans batch: {e}")
2855
+
2856
+ def get_span(self, span_id: str):
2857
+ """Get a single span by its span_id.
2858
+
2859
+ Args:
2860
+ span_id: The unique span identifier.
2861
+
2862
+ Returns:
2863
+ Optional[Span]: The span if found, None otherwise.
2864
+ """
2865
+ try:
2866
+ from agno.tracing.schemas import Span
2867
+
2868
+ table = self._get_table(table_type="spans")
2869
+ if table is None:
2870
+ return None
2871
+
2872
+ with self.Session() as sess:
2873
+ stmt = select(table).where(table.c.span_id == span_id)
2874
+ result = sess.execute(stmt).fetchone()
2875
+ if result:
2876
+ return Span.from_dict(dict(result._mapping))
2877
+ return None
2878
+
2879
+ except Exception as e:
2880
+ log_error(f"Error getting span: {e}")
2881
+ return None
2882
+
2883
+ def get_spans(
2884
+ self,
2885
+ trace_id: Optional[str] = None,
2886
+ parent_span_id: Optional[str] = None,
2887
+ limit: Optional[int] = 1000,
2888
+ ) -> List:
2889
+ """Get spans matching the provided filters.
2890
+
2891
+ Args:
2892
+ trace_id: Filter by trace ID.
2893
+ parent_span_id: Filter by parent span ID.
2894
+ limit: Maximum number of spans to return.
2895
+
2896
+ Returns:
2897
+ List[Span]: List of matching spans.
2898
+ """
2899
+ try:
2900
+ from agno.tracing.schemas import Span
2901
+
2902
+ table = self._get_table(table_type="spans")
2903
+ if table is None:
2904
+ return []
2905
+
2906
+ with self.Session() as sess:
2907
+ stmt = select(table)
2908
+
2909
+ # Apply filters
2910
+ if trace_id:
2911
+ stmt = stmt.where(table.c.trace_id == trace_id)
2912
+ if parent_span_id:
2913
+ stmt = stmt.where(table.c.parent_span_id == parent_span_id)
2914
+
2915
+ if limit:
2916
+ stmt = stmt.limit(limit)
2917
+
2918
+ results = sess.execute(stmt).fetchall()
2919
+ return [Span.from_dict(dict(row._mapping)) for row in results]
2920
+
2921
+ except Exception as e:
2922
+ log_error(f"Error getting spans: {e}")
2923
+ return []