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