agno 1.8.1__py3-none-any.whl → 2.0.0rc1__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 (583) hide show
  1. agno/__init__.py +8 -0
  2. agno/agent/__init__.py +19 -27
  3. agno/agent/agent.py +3181 -4169
  4. agno/api/agent.py +11 -67
  5. agno/api/api.py +5 -46
  6. agno/api/evals.py +8 -19
  7. agno/api/os.py +17 -0
  8. agno/api/routes.py +6 -41
  9. agno/api/schemas/__init__.py +9 -0
  10. agno/api/schemas/agent.py +5 -21
  11. agno/api/schemas/evals.py +7 -16
  12. agno/api/schemas/os.py +14 -0
  13. agno/api/schemas/team.py +5 -21
  14. agno/api/schemas/utils.py +21 -0
  15. agno/api/schemas/workflows.py +11 -7
  16. agno/api/settings.py +53 -0
  17. agno/api/team.py +11 -66
  18. agno/api/workflow.py +28 -0
  19. agno/cloud/aws/base.py +214 -0
  20. agno/cloud/aws/s3/__init__.py +2 -0
  21. agno/cloud/aws/s3/api_client.py +43 -0
  22. agno/cloud/aws/s3/bucket.py +195 -0
  23. agno/cloud/aws/s3/object.py +57 -0
  24. agno/db/__init__.py +24 -0
  25. agno/db/base.py +245 -0
  26. agno/db/dynamo/__init__.py +3 -0
  27. agno/db/dynamo/dynamo.py +1743 -0
  28. agno/db/dynamo/schemas.py +278 -0
  29. agno/db/dynamo/utils.py +684 -0
  30. agno/db/firestore/__init__.py +3 -0
  31. agno/db/firestore/firestore.py +1432 -0
  32. agno/db/firestore/schemas.py +130 -0
  33. agno/db/firestore/utils.py +278 -0
  34. agno/db/gcs_json/__init__.py +3 -0
  35. agno/db/gcs_json/gcs_json_db.py +1001 -0
  36. agno/db/gcs_json/utils.py +194 -0
  37. agno/db/in_memory/__init__.py +3 -0
  38. agno/db/in_memory/in_memory_db.py +882 -0
  39. agno/db/in_memory/utils.py +172 -0
  40. agno/db/json/__init__.py +3 -0
  41. agno/db/json/json_db.py +1045 -0
  42. agno/db/json/utils.py +196 -0
  43. agno/db/migrations/v1_to_v2.py +162 -0
  44. agno/db/mongo/__init__.py +3 -0
  45. agno/db/mongo/mongo.py +1411 -0
  46. agno/db/mongo/schemas.py +77 -0
  47. agno/db/mongo/utils.py +204 -0
  48. agno/db/mysql/__init__.py +3 -0
  49. agno/db/mysql/mysql.py +1719 -0
  50. agno/db/mysql/schemas.py +124 -0
  51. agno/db/mysql/utils.py +297 -0
  52. agno/db/postgres/__init__.py +3 -0
  53. agno/db/postgres/postgres.py +1710 -0
  54. agno/db/postgres/schemas.py +124 -0
  55. agno/db/postgres/utils.py +280 -0
  56. agno/db/redis/__init__.py +3 -0
  57. agno/db/redis/redis.py +1367 -0
  58. agno/db/redis/schemas.py +109 -0
  59. agno/db/redis/utils.py +288 -0
  60. agno/db/schemas/__init__.py +3 -0
  61. agno/db/schemas/evals.py +33 -0
  62. agno/db/schemas/knowledge.py +40 -0
  63. agno/db/schemas/memory.py +46 -0
  64. agno/db/singlestore/__init__.py +3 -0
  65. agno/db/singlestore/schemas.py +116 -0
  66. agno/db/singlestore/singlestore.py +1712 -0
  67. agno/db/singlestore/utils.py +326 -0
  68. agno/db/sqlite/__init__.py +3 -0
  69. agno/db/sqlite/schemas.py +119 -0
  70. agno/db/sqlite/sqlite.py +1676 -0
  71. agno/db/sqlite/utils.py +268 -0
  72. agno/db/utils.py +88 -0
  73. agno/eval/__init__.py +14 -0
  74. agno/eval/accuracy.py +142 -43
  75. agno/eval/performance.py +88 -23
  76. agno/eval/reliability.py +73 -20
  77. agno/eval/utils.py +23 -13
  78. agno/integrations/discord/__init__.py +3 -0
  79. agno/{app → integrations}/discord/client.py +15 -11
  80. agno/knowledge/__init__.py +2 -2
  81. agno/{document → knowledge}/chunking/agentic.py +2 -2
  82. agno/{document → knowledge}/chunking/document.py +2 -2
  83. agno/{document → knowledge}/chunking/fixed.py +3 -3
  84. agno/{document → knowledge}/chunking/markdown.py +2 -2
  85. agno/{document → knowledge}/chunking/recursive.py +2 -2
  86. agno/{document → knowledge}/chunking/row.py +2 -2
  87. agno/knowledge/chunking/semantic.py +59 -0
  88. agno/knowledge/chunking/strategy.py +121 -0
  89. agno/knowledge/content.py +74 -0
  90. agno/knowledge/document/__init__.py +5 -0
  91. agno/{document → knowledge/document}/base.py +12 -2
  92. agno/knowledge/embedder/__init__.py +5 -0
  93. agno/{embedder → knowledge/embedder}/aws_bedrock.py +127 -1
  94. agno/{embedder → knowledge/embedder}/azure_openai.py +65 -1
  95. agno/{embedder → knowledge/embedder}/base.py +6 -0
  96. agno/{embedder → knowledge/embedder}/cohere.py +72 -1
  97. agno/{embedder → knowledge/embedder}/fastembed.py +17 -1
  98. agno/{embedder → knowledge/embedder}/fireworks.py +1 -1
  99. agno/{embedder → knowledge/embedder}/google.py +74 -1
  100. agno/{embedder → knowledge/embedder}/huggingface.py +36 -2
  101. agno/{embedder → knowledge/embedder}/jina.py +48 -2
  102. agno/knowledge/embedder/langdb.py +22 -0
  103. agno/knowledge/embedder/mistral.py +139 -0
  104. agno/{embedder → knowledge/embedder}/nebius.py +1 -1
  105. agno/{embedder → knowledge/embedder}/ollama.py +54 -3
  106. agno/knowledge/embedder/openai.py +223 -0
  107. agno/{embedder → knowledge/embedder}/sentence_transformer.py +16 -1
  108. agno/{embedder → knowledge/embedder}/together.py +1 -1
  109. agno/{embedder → knowledge/embedder}/voyageai.py +49 -1
  110. agno/knowledge/knowledge.py +1515 -0
  111. agno/knowledge/reader/__init__.py +7 -0
  112. agno/{document → knowledge}/reader/arxiv_reader.py +32 -4
  113. agno/knowledge/reader/base.py +88 -0
  114. agno/{document → knowledge}/reader/csv_reader.py +68 -15
  115. agno/knowledge/reader/docx_reader.py +83 -0
  116. agno/{document → knowledge}/reader/firecrawl_reader.py +42 -21
  117. agno/knowledge/reader/gcs_reader.py +67 -0
  118. agno/{document → knowledge}/reader/json_reader.py +30 -9
  119. agno/{document → knowledge}/reader/markdown_reader.py +36 -9
  120. agno/{document → knowledge}/reader/pdf_reader.py +79 -21
  121. agno/knowledge/reader/reader_factory.py +275 -0
  122. agno/knowledge/reader/s3_reader.py +171 -0
  123. agno/{document → knowledge}/reader/text_reader.py +31 -10
  124. agno/knowledge/reader/url_reader.py +84 -0
  125. agno/knowledge/reader/web_search_reader.py +389 -0
  126. agno/{document → knowledge}/reader/website_reader.py +37 -10
  127. agno/knowledge/reader/wikipedia_reader.py +59 -0
  128. agno/knowledge/reader/youtube_reader.py +78 -0
  129. agno/knowledge/remote_content/remote_content.py +88 -0
  130. agno/{reranker → knowledge/reranker}/base.py +1 -1
  131. agno/{reranker → knowledge/reranker}/cohere.py +2 -2
  132. agno/{reranker → knowledge/reranker}/infinity.py +2 -2
  133. agno/{reranker → knowledge/reranker}/sentence_transformer.py +2 -2
  134. agno/knowledge/types.py +30 -0
  135. agno/knowledge/utils.py +169 -0
  136. agno/memory/__init__.py +2 -10
  137. agno/memory/manager.py +1003 -148
  138. agno/models/aimlapi/__init__.py +2 -2
  139. agno/models/aimlapi/aimlapi.py +6 -6
  140. agno/models/anthropic/claude.py +131 -131
  141. agno/models/aws/bedrock.py +107 -175
  142. agno/models/aws/claude.py +64 -18
  143. agno/models/azure/ai_foundry.py +73 -23
  144. agno/models/base.py +347 -287
  145. agno/models/cerebras/cerebras.py +84 -27
  146. agno/models/cohere/chat.py +106 -98
  147. agno/models/google/gemini.py +100 -42
  148. agno/models/groq/groq.py +97 -35
  149. agno/models/huggingface/huggingface.py +92 -27
  150. agno/models/ibm/watsonx.py +72 -13
  151. agno/models/litellm/chat.py +85 -13
  152. agno/models/message.py +45 -150
  153. agno/models/meta/llama.py +85 -49
  154. agno/models/metrics.py +120 -0
  155. agno/models/mistral/mistral.py +90 -21
  156. agno/models/ollama/__init__.py +0 -2
  157. agno/models/ollama/chat.py +84 -46
  158. agno/models/openai/chat.py +121 -23
  159. agno/models/openai/responses.py +178 -105
  160. agno/models/perplexity/perplexity.py +26 -2
  161. agno/models/portkey/portkey.py +0 -7
  162. agno/models/response.py +14 -8
  163. agno/models/utils.py +20 -0
  164. agno/models/vercel/__init__.py +2 -2
  165. agno/models/vercel/v0.py +1 -1
  166. agno/models/vllm/__init__.py +2 -2
  167. agno/models/vllm/vllm.py +3 -3
  168. agno/models/xai/xai.py +10 -10
  169. agno/os/__init__.py +3 -0
  170. agno/os/app.py +489 -0
  171. agno/os/auth.py +47 -0
  172. agno/os/config.py +103 -0
  173. agno/os/interfaces/agui/__init__.py +3 -0
  174. agno/os/interfaces/agui/agui.py +31 -0
  175. agno/{app/agui/async_router.py → os/interfaces/agui/router.py} +16 -16
  176. agno/{app → os/interfaces}/agui/utils.py +77 -33
  177. agno/os/interfaces/base.py +21 -0
  178. agno/os/interfaces/slack/__init__.py +3 -0
  179. agno/{app/slack/async_router.py → os/interfaces/slack/router.py} +3 -5
  180. agno/os/interfaces/slack/slack.py +32 -0
  181. agno/os/interfaces/whatsapp/__init__.py +3 -0
  182. agno/{app/whatsapp/async_router.py → os/interfaces/whatsapp/router.py} +4 -7
  183. agno/os/interfaces/whatsapp/whatsapp.py +29 -0
  184. agno/os/mcp.py +255 -0
  185. agno/os/router.py +869 -0
  186. agno/os/routers/__init__.py +3 -0
  187. agno/os/routers/evals/__init__.py +3 -0
  188. agno/os/routers/evals/evals.py +208 -0
  189. agno/os/routers/evals/schemas.py +142 -0
  190. agno/os/routers/evals/utils.py +161 -0
  191. agno/os/routers/knowledge/__init__.py +3 -0
  192. agno/os/routers/knowledge/knowledge.py +436 -0
  193. agno/os/routers/knowledge/schemas.py +118 -0
  194. agno/os/routers/memory/__init__.py +3 -0
  195. agno/os/routers/memory/memory.py +188 -0
  196. agno/os/routers/memory/schemas.py +58 -0
  197. agno/os/routers/metrics/__init__.py +3 -0
  198. agno/os/routers/metrics/metrics.py +60 -0
  199. agno/os/routers/metrics/schemas.py +47 -0
  200. agno/os/routers/session/__init__.py +3 -0
  201. agno/os/routers/session/session.py +168 -0
  202. agno/os/schema.py +892 -0
  203. agno/{app/playground → os}/settings.py +7 -15
  204. agno/os/utils.py +270 -0
  205. agno/reasoning/azure_ai_foundry.py +4 -4
  206. agno/reasoning/deepseek.py +4 -4
  207. agno/reasoning/default.py +6 -11
  208. agno/reasoning/groq.py +4 -4
  209. agno/reasoning/helpers.py +4 -6
  210. agno/reasoning/ollama.py +4 -4
  211. agno/reasoning/openai.py +4 -4
  212. agno/run/{response.py → agent.py} +231 -74
  213. agno/run/base.py +44 -58
  214. agno/run/cancel.py +81 -0
  215. agno/run/team.py +133 -77
  216. agno/run/workflow.py +537 -12
  217. agno/session/__init__.py +10 -0
  218. agno/session/agent.py +244 -0
  219. agno/session/summary.py +225 -0
  220. agno/session/team.py +262 -0
  221. agno/{storage/session/v2 → session}/workflow.py +47 -24
  222. agno/team/__init__.py +15 -16
  223. agno/team/team.py +2960 -4252
  224. agno/tools/agentql.py +14 -5
  225. agno/tools/airflow.py +9 -4
  226. agno/tools/api.py +7 -3
  227. agno/tools/apify.py +2 -46
  228. agno/tools/arxiv.py +8 -3
  229. agno/tools/aws_lambda.py +7 -5
  230. agno/tools/aws_ses.py +7 -1
  231. agno/tools/baidusearch.py +4 -1
  232. agno/tools/bitbucket.py +4 -4
  233. agno/tools/brandfetch.py +14 -11
  234. agno/tools/bravesearch.py +4 -1
  235. agno/tools/brightdata.py +42 -22
  236. agno/tools/browserbase.py +13 -4
  237. agno/tools/calcom.py +12 -10
  238. agno/tools/calculator.py +10 -27
  239. agno/tools/cartesia.py +18 -13
  240. agno/tools/{clickup_tool.py → clickup.py} +12 -25
  241. agno/tools/confluence.py +8 -8
  242. agno/tools/crawl4ai.py +7 -1
  243. agno/tools/csv_toolkit.py +9 -8
  244. agno/tools/dalle.py +18 -11
  245. agno/tools/daytona.py +13 -16
  246. agno/tools/decorator.py +6 -3
  247. agno/tools/desi_vocal.py +16 -7
  248. agno/tools/discord.py +11 -8
  249. agno/tools/docker.py +30 -42
  250. agno/tools/duckdb.py +34 -53
  251. agno/tools/duckduckgo.py +8 -7
  252. agno/tools/e2b.py +61 -61
  253. agno/tools/eleven_labs.py +35 -28
  254. agno/tools/email.py +4 -1
  255. agno/tools/evm.py +7 -1
  256. agno/tools/exa.py +19 -14
  257. agno/tools/fal.py +29 -29
  258. agno/tools/file.py +9 -8
  259. agno/tools/financial_datasets.py +25 -44
  260. agno/tools/firecrawl.py +22 -22
  261. agno/tools/function.py +127 -18
  262. agno/tools/giphy.py +22 -10
  263. agno/tools/github.py +48 -126
  264. agno/tools/gmail.py +45 -61
  265. agno/tools/google_bigquery.py +7 -6
  266. agno/tools/google_maps.py +11 -26
  267. agno/tools/googlesearch.py +7 -2
  268. agno/tools/googlesheets.py +21 -17
  269. agno/tools/hackernews.py +9 -5
  270. agno/tools/jina.py +5 -4
  271. agno/tools/jira.py +18 -9
  272. agno/tools/knowledge.py +31 -32
  273. agno/tools/linear.py +19 -34
  274. agno/tools/linkup.py +5 -1
  275. agno/tools/local_file_system.py +8 -5
  276. agno/tools/lumalab.py +31 -19
  277. agno/tools/mem0.py +18 -12
  278. agno/tools/memori.py +14 -10
  279. agno/tools/mlx_transcribe.py +3 -2
  280. agno/tools/models/azure_openai.py +32 -14
  281. agno/tools/models/gemini.py +58 -31
  282. agno/tools/models/groq.py +29 -20
  283. agno/tools/models/nebius.py +27 -11
  284. agno/tools/models_labs.py +39 -15
  285. agno/tools/moviepy_video.py +7 -6
  286. agno/tools/neo4j.py +10 -8
  287. agno/tools/newspaper.py +7 -2
  288. agno/tools/newspaper4k.py +8 -3
  289. agno/tools/openai.py +57 -26
  290. agno/tools/openbb.py +12 -11
  291. agno/tools/opencv.py +62 -46
  292. agno/tools/openweather.py +14 -12
  293. agno/tools/pandas.py +11 -3
  294. agno/tools/postgres.py +4 -12
  295. agno/tools/pubmed.py +4 -1
  296. agno/tools/python.py +9 -22
  297. agno/tools/reasoning.py +35 -27
  298. agno/tools/reddit.py +11 -26
  299. agno/tools/replicate.py +54 -41
  300. agno/tools/resend.py +4 -1
  301. agno/tools/scrapegraph.py +15 -14
  302. agno/tools/searxng.py +10 -23
  303. agno/tools/serpapi.py +6 -3
  304. agno/tools/serper.py +13 -4
  305. agno/tools/shell.py +9 -2
  306. agno/tools/slack.py +12 -11
  307. agno/tools/sleep.py +3 -2
  308. agno/tools/spider.py +24 -4
  309. agno/tools/sql.py +7 -6
  310. agno/tools/tavily.py +6 -4
  311. agno/tools/telegram.py +12 -4
  312. agno/tools/todoist.py +11 -31
  313. agno/tools/toolkit.py +1 -1
  314. agno/tools/trafilatura.py +22 -6
  315. agno/tools/trello.py +9 -22
  316. agno/tools/twilio.py +10 -3
  317. agno/tools/user_control_flow.py +6 -1
  318. agno/tools/valyu.py +34 -5
  319. agno/tools/visualization.py +19 -28
  320. agno/tools/webbrowser.py +4 -3
  321. agno/tools/webex.py +11 -7
  322. agno/tools/website.py +15 -46
  323. agno/tools/webtools.py +12 -4
  324. agno/tools/whatsapp.py +5 -9
  325. agno/tools/wikipedia.py +20 -13
  326. agno/tools/x.py +14 -13
  327. agno/tools/yfinance.py +13 -40
  328. agno/tools/youtube.py +26 -20
  329. agno/tools/zendesk.py +7 -2
  330. agno/tools/zep.py +10 -7
  331. agno/tools/zoom.py +10 -9
  332. agno/utils/common.py +1 -19
  333. agno/utils/events.py +95 -118
  334. agno/utils/gemini.py +31 -1
  335. agno/utils/knowledge.py +29 -0
  336. agno/utils/log.py +2 -2
  337. agno/utils/mcp.py +11 -5
  338. agno/utils/media.py +39 -0
  339. agno/utils/message.py +12 -1
  340. agno/utils/models/claude.py +55 -4
  341. agno/utils/models/mistral.py +8 -7
  342. agno/utils/models/schema_utils.py +3 -3
  343. agno/utils/pprint.py +33 -32
  344. agno/utils/print_response/agent.py +779 -0
  345. agno/utils/print_response/team.py +1565 -0
  346. agno/utils/print_response/workflow.py +1451 -0
  347. agno/utils/prompts.py +14 -14
  348. agno/utils/reasoning.py +87 -0
  349. agno/utils/response.py +42 -42
  350. agno/utils/streamlit.py +454 -0
  351. agno/utils/string.py +8 -22
  352. agno/utils/team.py +50 -0
  353. agno/utils/timer.py +2 -2
  354. agno/vectordb/base.py +33 -21
  355. agno/vectordb/cassandra/cassandra.py +287 -23
  356. agno/vectordb/chroma/chromadb.py +482 -59
  357. agno/vectordb/clickhouse/clickhousedb.py +270 -63
  358. agno/vectordb/couchbase/couchbase.py +309 -29
  359. agno/vectordb/lancedb/lance_db.py +360 -21
  360. agno/vectordb/langchaindb/__init__.py +5 -0
  361. agno/vectordb/langchaindb/langchaindb.py +145 -0
  362. agno/vectordb/lightrag/__init__.py +5 -0
  363. agno/vectordb/lightrag/lightrag.py +374 -0
  364. agno/vectordb/llamaindex/llamaindexdb.py +127 -0
  365. agno/vectordb/milvus/milvus.py +242 -32
  366. agno/vectordb/mongodb/mongodb.py +200 -24
  367. agno/vectordb/pgvector/pgvector.py +319 -37
  368. agno/vectordb/pineconedb/pineconedb.py +221 -27
  369. agno/vectordb/qdrant/qdrant.py +334 -14
  370. agno/vectordb/singlestore/singlestore.py +286 -29
  371. agno/vectordb/surrealdb/surrealdb.py +187 -7
  372. agno/vectordb/upstashdb/upstashdb.py +342 -26
  373. agno/vectordb/weaviate/weaviate.py +227 -165
  374. agno/workflow/__init__.py +17 -13
  375. agno/workflow/{v2/condition.py → condition.py} +135 -32
  376. agno/workflow/{v2/loop.py → loop.py} +115 -28
  377. agno/workflow/{v2/parallel.py → parallel.py} +138 -108
  378. agno/workflow/{v2/router.py → router.py} +133 -32
  379. agno/workflow/{v2/step.py → step.py} +200 -42
  380. agno/workflow/{v2/steps.py → steps.py} +147 -66
  381. agno/workflow/types.py +482 -0
  382. agno/workflow/workflow.py +2401 -696
  383. agno-2.0.0rc1.dist-info/METADATA +355 -0
  384. agno-2.0.0rc1.dist-info/RECORD +516 -0
  385. agno/agent/metrics.py +0 -107
  386. agno/api/app.py +0 -35
  387. agno/api/playground.py +0 -92
  388. agno/api/schemas/app.py +0 -12
  389. agno/api/schemas/playground.py +0 -22
  390. agno/api/schemas/user.py +0 -35
  391. agno/api/schemas/workspace.py +0 -46
  392. agno/api/user.py +0 -160
  393. agno/api/workflows.py +0 -33
  394. agno/api/workspace.py +0 -175
  395. agno/app/agui/__init__.py +0 -3
  396. agno/app/agui/app.py +0 -17
  397. agno/app/agui/sync_router.py +0 -120
  398. agno/app/base.py +0 -186
  399. agno/app/discord/__init__.py +0 -3
  400. agno/app/fastapi/__init__.py +0 -3
  401. agno/app/fastapi/app.py +0 -107
  402. agno/app/fastapi/async_router.py +0 -457
  403. agno/app/fastapi/sync_router.py +0 -448
  404. agno/app/playground/app.py +0 -228
  405. agno/app/playground/async_router.py +0 -1050
  406. agno/app/playground/deploy.py +0 -249
  407. agno/app/playground/operator.py +0 -183
  408. agno/app/playground/schemas.py +0 -220
  409. agno/app/playground/serve.py +0 -55
  410. agno/app/playground/sync_router.py +0 -1042
  411. agno/app/playground/utils.py +0 -46
  412. agno/app/settings.py +0 -15
  413. agno/app/slack/__init__.py +0 -3
  414. agno/app/slack/app.py +0 -19
  415. agno/app/slack/sync_router.py +0 -92
  416. agno/app/utils.py +0 -54
  417. agno/app/whatsapp/__init__.py +0 -3
  418. agno/app/whatsapp/app.py +0 -15
  419. agno/app/whatsapp/sync_router.py +0 -197
  420. agno/cli/auth_server.py +0 -249
  421. agno/cli/config.py +0 -274
  422. agno/cli/console.py +0 -88
  423. agno/cli/credentials.py +0 -23
  424. agno/cli/entrypoint.py +0 -571
  425. agno/cli/operator.py +0 -357
  426. agno/cli/settings.py +0 -96
  427. agno/cli/ws/ws_cli.py +0 -817
  428. agno/constants.py +0 -13
  429. agno/document/__init__.py +0 -5
  430. agno/document/chunking/semantic.py +0 -45
  431. agno/document/chunking/strategy.py +0 -31
  432. agno/document/reader/__init__.py +0 -5
  433. agno/document/reader/base.py +0 -47
  434. agno/document/reader/docx_reader.py +0 -60
  435. agno/document/reader/gcs/pdf_reader.py +0 -44
  436. agno/document/reader/s3/pdf_reader.py +0 -59
  437. agno/document/reader/s3/text_reader.py +0 -63
  438. agno/document/reader/url_reader.py +0 -59
  439. agno/document/reader/youtube_reader.py +0 -58
  440. agno/embedder/__init__.py +0 -5
  441. agno/embedder/langdb.py +0 -80
  442. agno/embedder/mistral.py +0 -82
  443. agno/embedder/openai.py +0 -78
  444. agno/file/__init__.py +0 -5
  445. agno/file/file.py +0 -16
  446. agno/file/local/csv.py +0 -32
  447. agno/file/local/txt.py +0 -19
  448. agno/infra/app.py +0 -240
  449. agno/infra/base.py +0 -144
  450. agno/infra/context.py +0 -20
  451. agno/infra/db_app.py +0 -52
  452. agno/infra/resource.py +0 -205
  453. agno/infra/resources.py +0 -55
  454. agno/knowledge/agent.py +0 -702
  455. agno/knowledge/arxiv.py +0 -33
  456. agno/knowledge/combined.py +0 -36
  457. agno/knowledge/csv.py +0 -144
  458. agno/knowledge/csv_url.py +0 -124
  459. agno/knowledge/document.py +0 -223
  460. agno/knowledge/docx.py +0 -137
  461. agno/knowledge/firecrawl.py +0 -34
  462. agno/knowledge/gcs/__init__.py +0 -0
  463. agno/knowledge/gcs/base.py +0 -39
  464. agno/knowledge/gcs/pdf.py +0 -125
  465. agno/knowledge/json.py +0 -137
  466. agno/knowledge/langchain.py +0 -71
  467. agno/knowledge/light_rag.py +0 -273
  468. agno/knowledge/llamaindex.py +0 -66
  469. agno/knowledge/markdown.py +0 -154
  470. agno/knowledge/pdf.py +0 -164
  471. agno/knowledge/pdf_bytes.py +0 -42
  472. agno/knowledge/pdf_url.py +0 -148
  473. agno/knowledge/s3/__init__.py +0 -0
  474. agno/knowledge/s3/base.py +0 -64
  475. agno/knowledge/s3/pdf.py +0 -33
  476. agno/knowledge/s3/text.py +0 -34
  477. agno/knowledge/text.py +0 -141
  478. agno/knowledge/url.py +0 -46
  479. agno/knowledge/website.py +0 -179
  480. agno/knowledge/wikipedia.py +0 -32
  481. agno/knowledge/youtube.py +0 -35
  482. agno/memory/agent.py +0 -423
  483. agno/memory/classifier.py +0 -104
  484. agno/memory/db/__init__.py +0 -5
  485. agno/memory/db/base.py +0 -42
  486. agno/memory/db/mongodb.py +0 -189
  487. agno/memory/db/postgres.py +0 -203
  488. agno/memory/db/sqlite.py +0 -193
  489. agno/memory/memory.py +0 -22
  490. agno/memory/row.py +0 -36
  491. agno/memory/summarizer.py +0 -201
  492. agno/memory/summary.py +0 -19
  493. agno/memory/team.py +0 -415
  494. agno/memory/v2/__init__.py +0 -2
  495. agno/memory/v2/db/__init__.py +0 -1
  496. agno/memory/v2/db/base.py +0 -42
  497. agno/memory/v2/db/firestore.py +0 -339
  498. agno/memory/v2/db/mongodb.py +0 -196
  499. agno/memory/v2/db/postgres.py +0 -214
  500. agno/memory/v2/db/redis.py +0 -187
  501. agno/memory/v2/db/schema.py +0 -54
  502. agno/memory/v2/db/sqlite.py +0 -209
  503. agno/memory/v2/manager.py +0 -437
  504. agno/memory/v2/memory.py +0 -1097
  505. agno/memory/v2/schema.py +0 -55
  506. agno/memory/v2/summarizer.py +0 -215
  507. agno/memory/workflow.py +0 -38
  508. agno/models/ollama/tools.py +0 -430
  509. agno/models/qwen/__init__.py +0 -5
  510. agno/playground/__init__.py +0 -10
  511. agno/playground/deploy.py +0 -3
  512. agno/playground/playground.py +0 -3
  513. agno/playground/serve.py +0 -3
  514. agno/playground/settings.py +0 -3
  515. agno/reranker/__init__.py +0 -0
  516. agno/run/v2/__init__.py +0 -0
  517. agno/run/v2/workflow.py +0 -567
  518. agno/storage/__init__.py +0 -0
  519. agno/storage/agent/__init__.py +0 -0
  520. agno/storage/agent/dynamodb.py +0 -1
  521. agno/storage/agent/json.py +0 -1
  522. agno/storage/agent/mongodb.py +0 -1
  523. agno/storage/agent/postgres.py +0 -1
  524. agno/storage/agent/singlestore.py +0 -1
  525. agno/storage/agent/sqlite.py +0 -1
  526. agno/storage/agent/yaml.py +0 -1
  527. agno/storage/base.py +0 -60
  528. agno/storage/dynamodb.py +0 -673
  529. agno/storage/firestore.py +0 -297
  530. agno/storage/gcs_json.py +0 -261
  531. agno/storage/in_memory.py +0 -234
  532. agno/storage/json.py +0 -237
  533. agno/storage/mongodb.py +0 -328
  534. agno/storage/mysql.py +0 -685
  535. agno/storage/postgres.py +0 -682
  536. agno/storage/redis.py +0 -336
  537. agno/storage/session/__init__.py +0 -16
  538. agno/storage/session/agent.py +0 -64
  539. agno/storage/session/team.py +0 -63
  540. agno/storage/session/v2/__init__.py +0 -5
  541. agno/storage/session/workflow.py +0 -61
  542. agno/storage/singlestore.py +0 -606
  543. agno/storage/sqlite.py +0 -646
  544. agno/storage/workflow/__init__.py +0 -0
  545. agno/storage/workflow/mongodb.py +0 -1
  546. agno/storage/workflow/postgres.py +0 -1
  547. agno/storage/workflow/sqlite.py +0 -1
  548. agno/storage/yaml.py +0 -241
  549. agno/tools/thinking.py +0 -73
  550. agno/utils/defaults.py +0 -57
  551. agno/utils/filesystem.py +0 -39
  552. agno/utils/git.py +0 -52
  553. agno/utils/json_io.py +0 -30
  554. agno/utils/load_env.py +0 -19
  555. agno/utils/py_io.py +0 -19
  556. agno/utils/pyproject.py +0 -18
  557. agno/utils/resource_filter.py +0 -31
  558. agno/workflow/v2/__init__.py +0 -21
  559. agno/workflow/v2/types.py +0 -357
  560. agno/workflow/v2/workflow.py +0 -3312
  561. agno/workspace/__init__.py +0 -0
  562. agno/workspace/config.py +0 -325
  563. agno/workspace/enums.py +0 -6
  564. agno/workspace/helpers.py +0 -52
  565. agno/workspace/operator.py +0 -757
  566. agno/workspace/settings.py +0 -158
  567. agno-1.8.1.dist-info/METADATA +0 -982
  568. agno-1.8.1.dist-info/RECORD +0 -566
  569. agno-1.8.1.dist-info/entry_points.txt +0 -3
  570. /agno/{app → db/migrations}/__init__.py +0 -0
  571. /agno/{app/playground/__init__.py → db/schemas/metrics.py} +0 -0
  572. /agno/{cli → integrations}/__init__.py +0 -0
  573. /agno/{cli/ws → knowledge/chunking}/__init__.py +0 -0
  574. /agno/{document/chunking → knowledge/remote_content}/__init__.py +0 -0
  575. /agno/{document/reader/gcs → knowledge/reranker}/__init__.py +0 -0
  576. /agno/{document/reader/s3 → os/interfaces}/__init__.py +0 -0
  577. /agno/{app → os/interfaces}/slack/security.py +0 -0
  578. /agno/{app → os/interfaces}/whatsapp/security.py +0 -0
  579. /agno/{file/local → utils/print_response}/__init__.py +0 -0
  580. /agno/{infra → vectordb/llamaindex}/__init__.py +0 -0
  581. {agno-1.8.1.dist-info → agno-2.0.0rc1.dist-info}/WHEEL +0 -0
  582. {agno-1.8.1.dist-info → agno-2.0.0rc1.dist-info}/licenses/LICENSE +0 -0
  583. {agno-1.8.1.dist-info → agno-2.0.0rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1743 @@
1
+ import json
2
+ import time
3
+ from datetime import date, datetime, timedelta, timezone
4
+ from os import getenv
5
+ from typing import Any, Dict, List, Optional, Tuple, Union
6
+
7
+ from agno.db.base import BaseDb, SessionType
8
+ from agno.db.dynamo.schemas import get_table_schema_definition
9
+ from agno.db.dynamo.utils import (
10
+ apply_pagination,
11
+ apply_sorting,
12
+ build_query_filter_expression,
13
+ build_topic_filter_expression,
14
+ calculate_date_metrics,
15
+ create_table_if_not_exists,
16
+ deserialize_eval_record,
17
+ deserialize_from_dynamodb_item,
18
+ deserialize_knowledge_row,
19
+ deserialize_session,
20
+ deserialize_session_result,
21
+ execute_query_with_pagination,
22
+ fetch_all_sessions_data,
23
+ get_dates_to_calculate_metrics_for,
24
+ merge_with_existing_session,
25
+ prepare_session_data,
26
+ serialize_eval_record,
27
+ serialize_knowledge_row,
28
+ serialize_to_dynamo_item,
29
+ )
30
+ from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType
31
+ from agno.db.schemas.knowledge import KnowledgeRow
32
+ from agno.db.schemas.memory import UserMemory
33
+ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
34
+ from agno.utils.log import log_debug, log_error
35
+
36
+ try:
37
+ import boto3 # type: ignore[import-untyped]
38
+ except ImportError:
39
+ raise ImportError("`boto3` not installed. Please install it using `pip install boto3`")
40
+
41
+
42
+ # DynamoDB batch_write_item has a hard limit of 25 items per request
43
+ DYNAMO_BATCH_SIZE_LIMIT = 25
44
+
45
+
46
+ class DynamoDb(BaseDb):
47
+ def __init__(
48
+ self,
49
+ db_client=None,
50
+ region_name: Optional[str] = None,
51
+ aws_access_key_id: Optional[str] = None,
52
+ aws_secret_access_key: Optional[str] = None,
53
+ session_table: Optional[str] = None,
54
+ memory_table: Optional[str] = None,
55
+ metrics_table: Optional[str] = None,
56
+ eval_table: Optional[str] = None,
57
+ knowledge_table: Optional[str] = None,
58
+ ):
59
+ """
60
+ Interface for interacting with a DynamoDB database.
61
+
62
+ Args:
63
+ db_client: The DynamoDB client to use.
64
+ region_name: AWS region name.
65
+ aws_access_key_id: AWS access key ID.
66
+ aws_secret_access_key: AWS secret access key.
67
+ session_table: The name of the session table.
68
+ memory_table: The name of the memory table.
69
+ metrics_table: The name of the metrics table.
70
+ eval_table: The name of the eval table.
71
+ knowledge_table: The name of the knowledge table.
72
+ """
73
+ super().__init__(
74
+ session_table=session_table,
75
+ memory_table=memory_table,
76
+ metrics_table=metrics_table,
77
+ eval_table=eval_table,
78
+ knowledge_table=knowledge_table,
79
+ )
80
+
81
+ if db_client is not None:
82
+ self.client = db_client
83
+ else:
84
+ if not region_name and not getenv("AWS_REGION"):
85
+ raise ValueError("AWS_REGION is not set. Please set the AWS_REGION environment variable.")
86
+ if not aws_access_key_id and not getenv("AWS_ACCESS_KEY_ID"):
87
+ raise ValueError("AWS_ACCESS_KEY_ID is not set. Please set the AWS_ACCESS_KEY_ID environment variable.")
88
+ if not aws_secret_access_key and not getenv("AWS_SECRET_ACCESS_KEY"):
89
+ raise ValueError(
90
+ "AWS_SECRET_ACCESS_KEY is not set. Please set the AWS_SECRET_ACCESS_KEY environment variable."
91
+ )
92
+
93
+ session_kwargs = {}
94
+ session_kwargs["region_name"] = region_name or getenv("AWS_REGION")
95
+ session_kwargs["aws_access_key_id"] = aws_access_key_id or getenv("AWS_ACCESS_KEY_ID")
96
+ session_kwargs["aws_secret_access_key"] = aws_secret_access_key or getenv("AWS_SECRET_ACCESS_KEY")
97
+
98
+ session = boto3.Session(**session_kwargs)
99
+ self.client = session.client("dynamodb")
100
+
101
+ def _create_tables(self):
102
+ tables_to_create = [
103
+ (self.session_table_name, "sessions"),
104
+ (self.memory_table_name, "memories"),
105
+ (self.metrics_table_name, "metrics"),
106
+ (self.eval_table_name, "evals"),
107
+ (self.knowledge_table_name, "knowledge_sources"),
108
+ ]
109
+
110
+ for table_name, table_type in tables_to_create:
111
+ if table_name:
112
+ try:
113
+ schema = get_table_schema_definition(table_type)
114
+ schema["TableName"] = table_name
115
+ create_table_if_not_exists(self.client, table_name, schema)
116
+
117
+ except Exception as e:
118
+ log_error(f"Failed to create table {table_name}: {e}")
119
+
120
+ def _table_exists(self, table_name: str) -> bool:
121
+ """Check if a DynamoDB table with the given name exists.
122
+
123
+ Args:
124
+ table_name: The name of the table to check
125
+
126
+ Returns:
127
+ bool: True if the table exists, False otherwise
128
+ """
129
+ try:
130
+ self.client.describe_table(TableName=table_name)
131
+ return True
132
+ except self.client.exceptions.ResourceNotFoundException:
133
+ return False
134
+ except Exception as e:
135
+ log_error(f"Error checking if table {table_name} exists: {e}")
136
+ return False
137
+
138
+ def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = True) -> Optional[str]:
139
+ """
140
+ Get table name and ensure the table exists, creating it if needed.
141
+
142
+ Args:
143
+ table_type: Type of table ("sessions", "memories", "metrics", "evals", "knowledge_sources")
144
+
145
+ Returns:
146
+ str: The table name
147
+
148
+ Raises:
149
+ ValueError: If table name is not configured or table type is unknown
150
+ """
151
+ table_name = None
152
+
153
+ if table_type == "sessions":
154
+ table_name = self.session_table_name
155
+ elif table_type == "memories":
156
+ table_name = self.memory_table_name
157
+ elif table_type == "metrics":
158
+ table_name = self.metrics_table_name
159
+ elif table_type == "evals":
160
+ table_name = self.eval_table_name
161
+ elif table_type == "knowledge":
162
+ table_name = self.knowledge_table_name
163
+ else:
164
+ raise ValueError(f"Unknown table type: {table_type}")
165
+
166
+ # Check if table exists, create if it doesn't
167
+ if not self._table_exists(table_name) and create_table_if_not_found:
168
+ schema = get_table_schema_definition(table_type)
169
+ schema["TableName"] = table_name
170
+ create_table_if_not_exists(self.client, table_name, schema)
171
+
172
+ return table_name
173
+
174
+ # --- Sessions ---
175
+
176
+ def delete_session(self, session_id: Optional[str] = None, session_type: Optional[SessionType] = None) -> bool:
177
+ """
178
+ Delete a session from the database.
179
+
180
+ Args:
181
+ session_id: The ID of the session to delete.
182
+
183
+ Raises:
184
+ Exception: If any error occurs while deleting the session.
185
+ """
186
+ if not session_id:
187
+ return False
188
+
189
+ try:
190
+ self.client.delete_item(
191
+ TableName=self.session_table_name,
192
+ Key={"session_id": {"S": session_id}},
193
+ )
194
+ return True
195
+
196
+ except Exception as e:
197
+ log_error(f"Failed to delete session {session_id}: {e}")
198
+ raise e
199
+
200
+ def delete_sessions(self, session_ids: List[str]) -> None:
201
+ """
202
+ Delete sessions from the database in batches.
203
+
204
+ Args:
205
+ session_ids: List of session IDs to delete
206
+
207
+ Raises:
208
+ Exception: If any error occurs while deleting the sessions.
209
+ """
210
+ if not session_ids or not self.session_table_name:
211
+ return
212
+
213
+ try:
214
+ # Process the items to delete in batches of the max allowed size or less
215
+ for i in range(0, len(session_ids), DYNAMO_BATCH_SIZE_LIMIT):
216
+ batch = session_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT]
217
+ delete_requests = []
218
+
219
+ for session_id in batch:
220
+ delete_requests.append({"DeleteRequest": {"Key": {"session_id": {"S": session_id}}}})
221
+
222
+ if delete_requests:
223
+ self.client.batch_write_item(RequestItems={self.session_table_name: delete_requests})
224
+
225
+ except Exception as e:
226
+ log_error(f"Failed to delete sessions: {e}")
227
+
228
+ def get_session(
229
+ self,
230
+ session_id: str,
231
+ session_type: Optional[SessionType] = None,
232
+ user_id: Optional[str] = None,
233
+ deserialize: Optional[bool] = True,
234
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
235
+ """
236
+ Get a session from the database as a Session object.
237
+
238
+ Args:
239
+ session_id (str): The ID of the session to get.
240
+ session_type (Optional[SessionType]): The type of session to get.
241
+ user_id (Optional[str]): The ID of the user to get the session for.
242
+ deserialize (Optional[bool]): Whether to deserialize the session.
243
+
244
+ Returns:
245
+ Optional[Session]: The session data as a Session object.
246
+
247
+ Raises:
248
+ Exception: If any error occurs while getting the session.
249
+ """
250
+ try:
251
+ table_name = self._get_table("sessions")
252
+ response = self.client.get_item(
253
+ TableName=table_name,
254
+ Key={"session_id": {"S": session_id}},
255
+ )
256
+
257
+ item = response.get("Item")
258
+ if not item:
259
+ return None
260
+
261
+ session = deserialize_from_dynamodb_item(item)
262
+
263
+ if session_type and session.get("session_type") != session_type.value:
264
+ return None
265
+ if user_id and session.get("user_id") != user_id:
266
+ return None
267
+
268
+ if not session:
269
+ return None
270
+
271
+ if not deserialize:
272
+ return session
273
+
274
+ if session_type == SessionType.AGENT:
275
+ return AgentSession.from_dict(session)
276
+ elif session_type == SessionType.TEAM:
277
+ return TeamSession.from_dict(session)
278
+ else:
279
+ return WorkflowSession.from_dict(session)
280
+
281
+ except Exception as e:
282
+ log_error(f"Failed to get session {session_id}: {e}")
283
+ return None
284
+
285
+ def get_sessions(
286
+ self,
287
+ session_type: SessionType,
288
+ user_id: Optional[str] = None,
289
+ component_id: Optional[str] = None,
290
+ session_name: Optional[str] = None,
291
+ start_timestamp: Optional[int] = None,
292
+ end_timestamp: Optional[int] = None,
293
+ limit: Optional[int] = None,
294
+ page: Optional[int] = None,
295
+ sort_by: Optional[str] = None,
296
+ sort_order: Optional[str] = None,
297
+ deserialize: Optional[bool] = True,
298
+ ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]:
299
+ try:
300
+ table_name = self._get_table("sessions")
301
+ if table_name is None:
302
+ return [] if deserialize else ([], 0)
303
+
304
+ # Build filter expression for additional filters
305
+ filter_expression = None
306
+ expression_attribute_names = {}
307
+ expression_attribute_values = {":session_type": {"S": session_type.value}}
308
+
309
+ if user_id:
310
+ filter_expression = "#user_id = :user_id"
311
+ expression_attribute_names["#user_id"] = "user_id"
312
+ expression_attribute_values[":user_id"] = {"S": user_id}
313
+
314
+ if component_id:
315
+ # Map component_id to the appropriate field based on session type
316
+ if session_type == SessionType.AGENT:
317
+ component_filter = "#agent_id = :component_id"
318
+ expression_attribute_names["#agent_id"] = "agent_id"
319
+ elif session_type == SessionType.TEAM:
320
+ component_filter = "#team_id = :component_id"
321
+ expression_attribute_names["#team_id"] = "team_id"
322
+ else:
323
+ component_filter = "#workflow_id = :component_id"
324
+ expression_attribute_names["#workflow_id"] = "workflow_id"
325
+
326
+ if component_filter:
327
+ expression_attribute_values[":component_id"] = {"S": component_id}
328
+ if filter_expression:
329
+ filter_expression += f" AND {component_filter}"
330
+ else:
331
+ filter_expression = component_filter
332
+
333
+ if session_name:
334
+ name_filter = "#session_name = :session_name"
335
+ expression_attribute_names["#session_name"] = "session_name"
336
+ expression_attribute_values[":session_name"] = {"S": session_name}
337
+ if filter_expression:
338
+ filter_expression += f" AND {name_filter}"
339
+ else:
340
+ filter_expression = name_filter
341
+
342
+ # Use GSI query for session_type
343
+ query_kwargs = {
344
+ "TableName": table_name,
345
+ "IndexName": "session_type-created_at-index",
346
+ "KeyConditionExpression": "session_type = :session_type",
347
+ "ExpressionAttributeValues": expression_attribute_values,
348
+ }
349
+ if filter_expression:
350
+ query_kwargs["FilterExpression"] = filter_expression
351
+ if expression_attribute_names:
352
+ query_kwargs["ExpressionAttributeNames"] = expression_attribute_names
353
+
354
+ # Apply sorting
355
+ if sort_by == "created_at":
356
+ query_kwargs["ScanIndexForward"] = sort_order != "desc" # type: ignore
357
+
358
+ # Apply limit at DynamoDB level
359
+ if limit and not page:
360
+ query_kwargs["Limit"] = limit # type: ignore
361
+
362
+ items = []
363
+ response = self.client.query(**query_kwargs)
364
+ items.extend(response.get("Items", []))
365
+
366
+ # Handle pagination
367
+ while "LastEvaluatedKey" in response:
368
+ query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]
369
+ response = self.client.query(**query_kwargs)
370
+ items.extend(response.get("Items", []))
371
+
372
+ # Convert DynamoDB items to session data
373
+ sessions_data = []
374
+ for item in items:
375
+ session_data = deserialize_from_dynamodb_item(item)
376
+ if session_data:
377
+ sessions_data.append(session_data)
378
+
379
+ # Apply in-memory sorting for fields not supported by DynamoDB
380
+ if sort_by and sort_by != "created_at":
381
+ sessions_data = apply_sorting(sessions_data, sort_by, sort_order)
382
+
383
+ # Get total count before pagination
384
+ total_count = len(sessions_data)
385
+
386
+ # Apply pagination
387
+ if page:
388
+ sessions_data = apply_pagination(sessions_data, limit, page)
389
+
390
+ if not deserialize:
391
+ return sessions_data, total_count
392
+
393
+ sessions = []
394
+ for session_data in sessions_data:
395
+ session = deserialize_session(session_data)
396
+ if session:
397
+ sessions.append(session)
398
+
399
+ return sessions
400
+
401
+ except Exception as e:
402
+ log_error(f"Failed to get sessions: {e}")
403
+ return []
404
+
405
+ def rename_session(
406
+ self,
407
+ session_id: str,
408
+ session_type: SessionType,
409
+ session_name: str,
410
+ deserialize: Optional[bool] = True,
411
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
412
+ """
413
+ Rename a session in the database.
414
+
415
+ Args:
416
+ session_id: The ID of the session to rename.
417
+ session_type: The type of session to rename.
418
+ session_name: The new name for the session.
419
+
420
+ Returns:
421
+ Optional[Session]: The renamed session if successful, None otherwise.
422
+
423
+ Raises:
424
+ Exception: If any error occurs while renaming the session.
425
+ """
426
+ try:
427
+ if not self.session_table_name:
428
+ raise Exception("Sessions table not found")
429
+
430
+ # Get current session_data
431
+ get_response = self.client.get_item(
432
+ TableName=self.session_table_name,
433
+ Key={"session_id": {"S": session_id}},
434
+ )
435
+ current_item = get_response.get("Item")
436
+ if not current_item:
437
+ return None
438
+
439
+ # Update session_data with the new session_name
440
+ session_data = deserialize_from_dynamodb_item(current_item).get("session_data", {})
441
+ session_data["session_name"] = session_name
442
+ response = self.client.update_item(
443
+ TableName=self.session_table_name,
444
+ Key={"session_id": {"S": session_id}},
445
+ UpdateExpression="SET session_data = :session_data, updated_at = :updated_at",
446
+ ConditionExpression="session_type = :session_type",
447
+ ExpressionAttributeValues={
448
+ ":session_data": {"S": json.dumps(session_data)},
449
+ ":session_type": {"S": session_type.value},
450
+ ":updated_at": {"N": str(int(time.time()))},
451
+ },
452
+ ReturnValues="ALL_NEW",
453
+ )
454
+ item = response.get("Attributes")
455
+ if not item:
456
+ return None
457
+
458
+ session = deserialize_from_dynamodb_item(item)
459
+ if not deserialize:
460
+ return session
461
+
462
+ if session_type == SessionType.AGENT:
463
+ return AgentSession.from_dict(session)
464
+ elif session_type == SessionType.TEAM:
465
+ return TeamSession.from_dict(session)
466
+ else:
467
+ return WorkflowSession.from_dict(session)
468
+
469
+ except Exception as e:
470
+ log_error(f"Failed to rename session {session_id}: {e}")
471
+ return None
472
+
473
+ def upsert_session(
474
+ self, session: Session, deserialize: Optional[bool] = True
475
+ ) -> Optional[Union[Session, Dict[str, Any]]]:
476
+ """
477
+ Upsert a session into the database.
478
+
479
+ This method provides true upsert behavior: creates a new session if it doesn't exist,
480
+ or updates an existing session while preserving important fields.
481
+
482
+ Args:
483
+ session (Session): The session to upsert.
484
+ deserialize (Optional[bool]): Whether to deserialize the session.
485
+
486
+ Returns:
487
+ Optional[Session]: The upserted session if successful, None otherwise.
488
+ """
489
+ try:
490
+ table_name = self._get_table("sessions", create_table_if_not_found=True)
491
+
492
+ # Get session if it already exists in the db.
493
+ # We need to do this to handle updating nested fields.
494
+ response = self.client.get_item(TableName=table_name, Key={"session_id": {"S": session.session_id}})
495
+ existing_item = response.get("Item")
496
+
497
+ # Prepare the session to upsert, merging with existing session if it exists.
498
+ serialized_session = prepare_session_data(session)
499
+ if existing_item:
500
+ serialized_session = merge_with_existing_session(serialized_session, existing_item)
501
+ serialized_session["updated_at"] = int(time.time())
502
+ else:
503
+ serialized_session["updated_at"] = serialized_session["created_at"]
504
+
505
+ # Upsert
506
+ item = serialize_to_dynamo_item(serialized_session)
507
+ self.client.put_item(TableName=table_name, Item=item)
508
+
509
+ return deserialize_session_result(serialized_session, session, deserialize)
510
+
511
+ except Exception as e:
512
+ log_error(f"Failed to upsert session {session.session_id}: {e}")
513
+ return None
514
+
515
+ # --- User Memory ---
516
+
517
+ def delete_user_memory(self, memory_id: str) -> None:
518
+ """
519
+ Delete a user memory from the database.
520
+
521
+ Args:
522
+ memory_id: The ID of the memory to delete.
523
+
524
+ Raises:
525
+ Exception: If any error occurs while deleting the user memory.
526
+ """
527
+ try:
528
+ self.client.delete_item(
529
+ TableName=self.memory_table_name,
530
+ Key={"memory_id": {"S": memory_id}},
531
+ )
532
+ log_debug(f"Deleted user memory {memory_id}")
533
+
534
+ except Exception as e:
535
+ log_error(f"Failed to delete user memory {memory_id}: {e}")
536
+
537
+ def delete_user_memories(self, memory_ids: List[str]) -> None:
538
+ """
539
+ Delete user memories from the database in batches.
540
+
541
+ Args:
542
+ memory_ids: List of memory IDs to delete
543
+
544
+ Raises:
545
+ Exception: If any error occurs while deleting the user memories.
546
+ """
547
+
548
+ try:
549
+ for i in range(0, len(memory_ids), DYNAMO_BATCH_SIZE_LIMIT):
550
+ batch = memory_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT]
551
+
552
+ delete_requests = []
553
+ for memory_id in batch:
554
+ delete_requests.append({"DeleteRequest": {"Key": {"memory_id": {"S": memory_id}}}})
555
+
556
+ self.client.batch_write_item(RequestItems={self.memory_table_name: delete_requests})
557
+
558
+ except Exception as e:
559
+ log_error(f"Failed to delete user memories: {e}")
560
+
561
+ def get_all_memory_topics(self) -> List[str]:
562
+ """Get all memory topics from the database.
563
+
564
+ Returns:
565
+ List[str]: List of unique memory topics.
566
+ """
567
+ try:
568
+ table_name = self._get_table("memories")
569
+ if table_name is None:
570
+ return []
571
+
572
+ # Scan the entire table to get all memories
573
+ response = self.client.scan(TableName=table_name)
574
+ items = response.get("Items", [])
575
+
576
+ # Handle pagination
577
+ while "LastEvaluatedKey" in response:
578
+ response = self.client.scan(TableName=table_name, ExclusiveStartKey=response["LastEvaluatedKey"])
579
+ items.extend(response.get("Items", []))
580
+
581
+ # Extract topics from all memories
582
+ all_topics = set()
583
+ for item in items:
584
+ memory_data = deserialize_from_dynamodb_item(item)
585
+ topics = memory_data.get("memory", {}).get("topics", [])
586
+ all_topics.update(topics)
587
+
588
+ return list(all_topics)
589
+
590
+ except Exception as e:
591
+ log_error(f"Exception reading from memory table: {e}")
592
+ return []
593
+
594
+ def get_user_memory(
595
+ self, memory_id: str, deserialize: Optional[bool] = True
596
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
597
+ """
598
+ Get a user memory from the database as a UserMemory object.
599
+
600
+ Args:
601
+ memory_id: The ID of the memory to get.
602
+
603
+ Returns:
604
+ Optional[UserMemory]: The user memory data if found, None otherwise.
605
+
606
+ Raises:
607
+ Exception: If any error occurs while getting the user memory.
608
+ """
609
+ try:
610
+ table_name = self._get_table("memories")
611
+ response = self.client.get_item(TableName=table_name, Key={"memory_id": {"S": memory_id}})
612
+
613
+ item = response.get("Item")
614
+ if not item:
615
+ return None
616
+
617
+ item = deserialize_from_dynamodb_item(item)
618
+ if not deserialize:
619
+ return item
620
+
621
+ return UserMemory.from_dict(item)
622
+
623
+ except Exception as e:
624
+ log_error(f"Failed to get user memory {memory_id}: {e}")
625
+ return None
626
+
627
+ def get_user_memories(
628
+ self,
629
+ user_id: Optional[str] = None,
630
+ agent_id: Optional[str] = None,
631
+ team_id: Optional[str] = None,
632
+ topics: Optional[List[str]] = None,
633
+ search_content: Optional[str] = None,
634
+ limit: Optional[int] = None,
635
+ page: Optional[int] = None,
636
+ sort_by: Optional[str] = None,
637
+ sort_order: Optional[str] = None,
638
+ deserialize: Optional[bool] = True,
639
+ ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]:
640
+ """
641
+ Get user memories from the database as a list of UserMemory objects.
642
+
643
+ Args:
644
+ user_id: The ID of the user to get the memories for.
645
+ agent_id: The ID of the agent to get the memories for.
646
+ team_id: The ID of the team to get the memories for.
647
+ workflow_id: The ID of the workflow to get the memories for.
648
+ topics: The topics to filter the memories by.
649
+ search_content: The content to search for in the memories.
650
+ limit: The maximum number of memories to return.
651
+ page: The page number to return.
652
+ sort_by: The field to sort the memories by.
653
+ sort_order: The order to sort the memories by.
654
+ deserialize: Whether to deserialize the memories.
655
+
656
+ Returns:
657
+ Union[List[UserMemory], List[Dict[str, Any]], Tuple[List[Dict[str, Any]], int]]: The user memories data.
658
+
659
+ Raises:
660
+ Exception: If any error occurs while getting the user memories.
661
+ """
662
+ try:
663
+ table_name = self._get_table("memories")
664
+ if table_name is None:
665
+ return [] if deserialize else ([], 0)
666
+
667
+ # Build filter expressions for component filters
668
+ (
669
+ filter_expression,
670
+ expression_attribute_names,
671
+ expression_attribute_values,
672
+ ) = build_query_filter_expression(filters={"agent_id": agent_id, "team_id": team_id})
673
+
674
+ # Build topic filter expression if topics provided
675
+ if topics:
676
+ topic_filter, topic_values = build_topic_filter_expression(topics)
677
+ expression_attribute_values.update(topic_values)
678
+ filter_expression = f"{filter_expression} AND {topic_filter}" if filter_expression else topic_filter
679
+
680
+ # Add search content filter if provided
681
+ if search_content:
682
+ search_filter = "contains(memory, :search_content)"
683
+ expression_attribute_values[":search_content"] = {"S": search_content}
684
+ filter_expression = f"{filter_expression} AND {search_filter}" if filter_expression else search_filter
685
+
686
+ # Determine whether to use GSI query or table scan
687
+ if user_id:
688
+ # Use GSI query when user_id is provided
689
+ key_condition_expression = "#user_id = :user_id"
690
+
691
+ # Set up expression attributes for GSI key condition
692
+ expression_attribute_names["#user_id"] = "user_id"
693
+ expression_attribute_values[":user_id"] = {"S": user_id}
694
+
695
+ # Execute query with pagination
696
+ items = execute_query_with_pagination(
697
+ self.client,
698
+ table_name,
699
+ "user_id-updated_at-index",
700
+ key_condition_expression,
701
+ expression_attribute_names,
702
+ expression_attribute_values,
703
+ filter_expression,
704
+ sort_by,
705
+ sort_order,
706
+ limit,
707
+ page,
708
+ )
709
+ else:
710
+ # Use table scan when user_id is None
711
+ scan_kwargs = {"TableName": table_name}
712
+
713
+ if filter_expression:
714
+ scan_kwargs["FilterExpression"] = filter_expression
715
+ if expression_attribute_names:
716
+ scan_kwargs["ExpressionAttributeNames"] = expression_attribute_names # type: ignore
717
+ if expression_attribute_values:
718
+ scan_kwargs["ExpressionAttributeValues"] = expression_attribute_values # type: ignore
719
+
720
+ # Execute scan
721
+ response = self.client.scan(**scan_kwargs)
722
+ items = response.get("Items", [])
723
+
724
+ # Handle pagination for scan
725
+ while "LastEvaluatedKey" in response:
726
+ scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]
727
+ response = self.client.scan(**scan_kwargs)
728
+ items.extend(response.get("Items", []))
729
+
730
+ items = [deserialize_from_dynamodb_item(item) for item in items]
731
+
732
+ if sort_by and sort_by != "updated_at":
733
+ items = apply_sorting(items, sort_by, sort_order)
734
+
735
+ if page:
736
+ paginated_items = apply_pagination(items, limit, page)
737
+
738
+ if not deserialize:
739
+ return paginated_items, len(items)
740
+
741
+ return [UserMemory.from_dict(item) for item in items]
742
+
743
+ except Exception as e:
744
+ log_error(f"Failed to get user memories: {e}")
745
+ return [] if deserialize else ([], 0)
746
+
747
+ def get_user_memory_stats(
748
+ self,
749
+ limit: Optional[int] = None,
750
+ page: Optional[int] = None,
751
+ ) -> Tuple[List[Dict[str, Any]], int]:
752
+ """Get user memories stats.
753
+
754
+ Args:
755
+ limit (Optional[int]): The maximum number of user stats to return.
756
+ page (Optional[int]): The page number.
757
+
758
+ Returns:
759
+ Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count.
760
+
761
+ Example:
762
+ (
763
+ [
764
+ {
765
+ "user_id": "123",
766
+ "total_memories": 10,
767
+ "last_memory_updated_at": 1714560000,
768
+ },
769
+ ],
770
+ total_count: 1,
771
+ )
772
+ """
773
+ try:
774
+ table_name = self._get_table("memories")
775
+
776
+ response = self.client.scan(TableName=table_name)
777
+ items = response.get("Items", [])
778
+
779
+ # Handle pagination
780
+ while "LastEvaluatedKey" in response:
781
+ response = self.client.scan(TableName=table_name, ExclusiveStartKey=response["LastEvaluatedKey"])
782
+ items.extend(response.get("Items", []))
783
+
784
+ # Aggregate stats by user_id
785
+ user_stats = {}
786
+ for item in items:
787
+ memory_data = deserialize_from_dynamodb_item(item)
788
+ user_id = memory_data.get("user_id")
789
+
790
+ if user_id:
791
+ if user_id not in user_stats:
792
+ user_stats[user_id] = {
793
+ "user_id": user_id,
794
+ "total_memories": 0,
795
+ "last_memory_updated_at": None,
796
+ }
797
+
798
+ user_stats[user_id]["total_memories"] += 1
799
+
800
+ updated_at = memory_data.get("updated_at")
801
+ if updated_at:
802
+ updated_at_dt = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
803
+ updated_at_timestamp = int(updated_at_dt.timestamp())
804
+
805
+ if updated_at_timestamp and (
806
+ user_stats[user_id]["last_memory_updated_at"] is None
807
+ or updated_at_timestamp > user_stats[user_id]["last_memory_updated_at"]
808
+ ):
809
+ user_stats[user_id]["last_memory_updated_at"] = updated_at_timestamp
810
+
811
+ # Convert to list and apply sorting
812
+ stats_list = list(user_stats.values())
813
+ stats_list.sort(
814
+ key=lambda x: (x["last_memory_updated_at"] if x["last_memory_updated_at"] is not None else 0),
815
+ reverse=True,
816
+ )
817
+
818
+ total_count = len(stats_list)
819
+
820
+ # Apply pagination
821
+ if limit is not None:
822
+ start_index = 0
823
+ if page is not None and page > 1:
824
+ start_index = (page - 1) * limit
825
+ stats_list = stats_list[start_index : start_index + limit]
826
+
827
+ return stats_list, total_count
828
+
829
+ except Exception as e:
830
+ log_error(f"Failed to get user memory stats: {e}")
831
+ return [], 0
832
+
833
+ def upsert_user_memory(
834
+ self, memory: UserMemory, deserialize: Optional[bool] = True
835
+ ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
836
+ """
837
+ Upsert a user memory into the database.
838
+
839
+ Args:
840
+ memory: The memory to upsert.
841
+
842
+ Returns:
843
+ Optional[Dict[str, Any]]: The upserted memory data if successful, None otherwise.
844
+ """
845
+ try:
846
+ table_name = self._get_table("memories", create_table_if_not_found=True)
847
+ memory_dict = memory.to_dict()
848
+ memory_dict["updated_at"] = datetime.now(timezone.utc).isoformat()
849
+ item = serialize_to_dynamo_item(memory_dict)
850
+
851
+ self.client.put_item(TableName=table_name, Item=item)
852
+
853
+ if not deserialize:
854
+ return memory_dict
855
+
856
+ return UserMemory.from_dict(memory_dict)
857
+
858
+ except Exception as e:
859
+ log_error(f"Failed to upsert user memory: {e}")
860
+ return None
861
+
862
+ def clear_memories(self) -> None:
863
+ """Delete all memories from the database.
864
+
865
+ Raises:
866
+ Exception: If an error occurs during deletion.
867
+ """
868
+ try:
869
+ table_name = self._get_table("memories")
870
+
871
+ # Scan the table to get all items
872
+ response = self.client.scan(TableName=table_name)
873
+ items = response.get("Items", [])
874
+
875
+ # Handle pagination for scan
876
+ while "LastEvaluatedKey" in response:
877
+ response = self.client.scan(TableName=table_name, ExclusiveStartKey=response["LastEvaluatedKey"])
878
+ items.extend(response.get("Items", []))
879
+
880
+ if not items:
881
+ return
882
+
883
+ # Delete items in batches
884
+ for i in range(0, len(items), DYNAMO_BATCH_SIZE_LIMIT):
885
+ batch = items[i : i + DYNAMO_BATCH_SIZE_LIMIT]
886
+
887
+ delete_requests = []
888
+ for item in batch:
889
+ # Extract the memory_id from the item
890
+ memory_id = item.get("memory_id", {}).get("S")
891
+ if memory_id:
892
+ delete_requests.append({"DeleteRequest": {"Key": {"memory_id": {"S": memory_id}}}})
893
+
894
+ if delete_requests:
895
+ self.client.batch_write_item(RequestItems={table_name: delete_requests})
896
+
897
+ except Exception as e:
898
+ from agno.utils.log import log_warning
899
+
900
+ log_warning(f"Exception deleting all memories: {e}")
901
+
902
+ # --- Metrics ---
903
+
904
+ def calculate_metrics(self) -> Optional[Any]:
905
+ """Calculate metrics for all dates without complete metrics.
906
+
907
+ Returns:
908
+ Optional[Any]: The calculated metrics or None if no metrics table.
909
+
910
+ Raises:
911
+ Exception: If an error occurs during metrics calculation.
912
+ """
913
+ if not self.metrics_table_name:
914
+ return None
915
+
916
+ try:
917
+ from agno.utils.log import log_info
918
+
919
+ # Get starting date for metrics calculation
920
+ starting_date = self._get_metrics_calculation_starting_date()
921
+ if starting_date is None:
922
+ log_info("No session data found. Won't calculate metrics.")
923
+ return None
924
+
925
+ # Get dates that need metrics calculation
926
+ dates_to_process = get_dates_to_calculate_metrics_for(starting_date)
927
+ if not dates_to_process:
928
+ log_info("Metrics already calculated for all relevant dates.")
929
+ return None
930
+
931
+ # Get timestamp range for session data
932
+ start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp())
933
+ end_timestamp = int(
934
+ datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp()
935
+ )
936
+
937
+ # Get all sessions for the date range
938
+ sessions = self._get_all_sessions_for_metrics_calculation(
939
+ start_timestamp=start_timestamp, end_timestamp=end_timestamp
940
+ )
941
+
942
+ # Process session data for metrics calculation
943
+
944
+ all_sessions_data = fetch_all_sessions_data(
945
+ sessions=sessions,
946
+ dates_to_process=dates_to_process,
947
+ start_timestamp=start_timestamp,
948
+ )
949
+
950
+ if not all_sessions_data:
951
+ log_info("No new session data found. Won't calculate metrics.")
952
+ return None
953
+
954
+ # Calculate metrics for each date
955
+ results = []
956
+ metrics_records = []
957
+ for date_to_process in dates_to_process:
958
+ date_key = date_to_process.isoformat()
959
+ sessions_for_date = all_sessions_data.get(date_key, {})
960
+
961
+ # Skip dates with no sessions
962
+ if not any(len(sessions) > 0 for sessions in sessions_for_date.values()):
963
+ continue
964
+
965
+ metrics_record = calculate_date_metrics(date_to_process, sessions_for_date)
966
+ metrics_records.append(metrics_record)
967
+
968
+ # Store metrics in DynamoDB
969
+ if metrics_records:
970
+ results = self._bulk_upsert_metrics(metrics_records)
971
+
972
+ log_debug("Updated metrics calculations")
973
+
974
+ return results
975
+
976
+ except Exception as e:
977
+ log_error(f"Failed to calculate metrics: {e}")
978
+ return None
979
+
980
+ def _get_metrics_calculation_starting_date(self) -> Optional[date]:
981
+ """Get the first date for which metrics calculation is needed:
982
+ 1. If there are metrics records, return the date of the first day without a complete metrics record.
983
+ 2. If there are no metrics records, return the date of the first recorded session.
984
+ 3. If there are no metrics records and no sessions records, return None.
985
+
986
+ Returns:
987
+ Optional[date]: The starting date for which metrics calculation is needed.
988
+ """
989
+ try:
990
+ metrics_table_name = self._get_table("metrics")
991
+
992
+ # 1. Check for existing metrics records
993
+ response = self.client.scan(
994
+ TableName=metrics_table_name,
995
+ ProjectionExpression="#date, completed",
996
+ ExpressionAttributeNames={"#date": "date"},
997
+ Limit=1000, # Get reasonable number of records to find incomplete ones
998
+ )
999
+
1000
+ metrics_items = response.get("Items", [])
1001
+
1002
+ # Handle pagination to get all metrics records
1003
+ while "LastEvaluatedKey" in response:
1004
+ response = self.client.scan(
1005
+ TableName=metrics_table_name,
1006
+ ProjectionExpression="#date, completed",
1007
+ ExpressionAttributeNames={"#date": "date"},
1008
+ ExclusiveStartKey=response["LastEvaluatedKey"],
1009
+ Limit=1000,
1010
+ )
1011
+ metrics_items.extend(response.get("Items", []))
1012
+
1013
+ if metrics_items:
1014
+ # Find the latest date with metrics
1015
+ latest_complete_date = None
1016
+ incomplete_dates = []
1017
+
1018
+ for item in metrics_items:
1019
+ metrics_data = deserialize_from_dynamodb_item(item)
1020
+ record_date = datetime.fromisoformat(metrics_data["date"]).date()
1021
+ is_completed = metrics_data.get("completed", False)
1022
+
1023
+ if is_completed:
1024
+ if latest_complete_date is None or record_date > latest_complete_date:
1025
+ latest_complete_date = record_date
1026
+ else:
1027
+ incomplete_dates.append(record_date)
1028
+
1029
+ # Return the earliest incomplete date, or the day after the latest complete date
1030
+ if incomplete_dates:
1031
+ return min(incomplete_dates)
1032
+ elif latest_complete_date:
1033
+ return latest_complete_date + timedelta(days=1)
1034
+
1035
+ # 2. No metrics records. Return the date of the first recorded session.
1036
+ sessions_table_name = self._get_table("sessions")
1037
+
1038
+ earliest_session_date = None
1039
+ for session_type in ["agent", "team", "workflow"]:
1040
+ response = self.client.query(
1041
+ TableName=sessions_table_name,
1042
+ IndexName="session_type-created_at-index",
1043
+ KeyConditionExpression="session_type = :session_type",
1044
+ ExpressionAttributeValues={":session_type": {"S": session_type}},
1045
+ ScanIndexForward=True, # Ascending order to get earliest
1046
+ Limit=1,
1047
+ )
1048
+
1049
+ items = response.get("Items", [])
1050
+ if items:
1051
+ first_session = deserialize_from_dynamodb_item(items[0])
1052
+ first_session_timestamp = first_session.get("created_at")
1053
+
1054
+ if first_session_timestamp:
1055
+ session_date = datetime.fromtimestamp(first_session_timestamp, tz=timezone.utc).date()
1056
+ if earliest_session_date is None or session_date < earliest_session_date:
1057
+ earliest_session_date = session_date
1058
+
1059
+ # 3. Return the earliest session date or None if no sessions exist
1060
+ return earliest_session_date
1061
+
1062
+ except Exception as e:
1063
+ log_error(f"Failed to get metrics calculation starting date: {e}")
1064
+ return None
1065
+
1066
+ def _get_all_sessions_for_metrics_calculation(
1067
+ self, start_timestamp: int, end_timestamp: int
1068
+ ) -> List[Dict[str, Any]]:
1069
+ """Get all sessions within a timestamp range for metrics calculation.
1070
+
1071
+ Args:
1072
+ start_timestamp: Start timestamp (inclusive)
1073
+ end_timestamp: End timestamp (exclusive)
1074
+
1075
+ Returns:
1076
+ List[Dict[str, Any]]: List of session data dictionaries
1077
+ """
1078
+ try:
1079
+ table_name = self._get_table("sessions")
1080
+ all_sessions = []
1081
+
1082
+ # Query sessions by different types within the time range
1083
+ for session_type in ["agent", "team", "workflow"]:
1084
+ response = self.client.query(
1085
+ TableName=table_name,
1086
+ IndexName="session_type-created_at-index",
1087
+ KeyConditionExpression="session_type = :session_type AND created_at BETWEEN :start_ts AND :end_ts",
1088
+ ExpressionAttributeValues={
1089
+ ":session_type": {"S": session_type},
1090
+ ":start_ts": {"N": str(start_timestamp)},
1091
+ ":end_ts": {"N": str(end_timestamp)},
1092
+ },
1093
+ )
1094
+
1095
+ items = response.get("Items", [])
1096
+
1097
+ # Handle pagination
1098
+ while "LastEvaluatedKey" in response:
1099
+ response = self.client.query(
1100
+ TableName=table_name,
1101
+ IndexName="session_type-created_at-index",
1102
+ KeyConditionExpression="session_type = :session_type AND created_at BETWEEN :start_ts AND :end_ts",
1103
+ ExpressionAttributeValues={
1104
+ ":session_type": {"S": session_type},
1105
+ ":start_ts": {"N": str(start_timestamp)},
1106
+ ":end_ts": {"N": str(end_timestamp)},
1107
+ },
1108
+ ExclusiveStartKey=response["LastEvaluatedKey"],
1109
+ )
1110
+ items.extend(response.get("Items", []))
1111
+
1112
+ # Deserialize sessions
1113
+ for item in items:
1114
+ session_data = deserialize_from_dynamodb_item(item)
1115
+ if session_data:
1116
+ all_sessions.append(session_data)
1117
+
1118
+ return all_sessions
1119
+
1120
+ except Exception as e:
1121
+ log_error(f"Failed to get sessions for metrics calculation: {e}")
1122
+ return []
1123
+
1124
+ def _bulk_upsert_metrics(self, metrics_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1125
+ """Bulk upsert metrics records into DynamoDB with proper deduplication.
1126
+
1127
+ Args:
1128
+ metrics_records: List of metrics records to upsert
1129
+
1130
+ Returns:
1131
+ List[Dict[str, Any]]: List of upserted records
1132
+ """
1133
+ try:
1134
+ table_name = self._get_table("metrics")
1135
+ if table_name is None:
1136
+ return []
1137
+
1138
+ results = []
1139
+
1140
+ # Process each record individually to handle proper upsert
1141
+ for record in metrics_records:
1142
+ upserted_record = self._upsert_single_metrics_record(table_name, record)
1143
+ if upserted_record:
1144
+ results.append(upserted_record)
1145
+
1146
+ return results
1147
+
1148
+ except Exception as e:
1149
+ log_error(f"Failed to bulk upsert metrics: {e}")
1150
+ return []
1151
+
1152
+ def _upsert_single_metrics_record(self, table_name: str, record: Dict[str, Any]) -> Optional[Dict[str, Any]]:
1153
+ """Upsert a single metrics record, checking for existing records with the same date.
1154
+
1155
+ Args:
1156
+ table_name: The DynamoDB table name
1157
+ record: The metrics record to upsert
1158
+
1159
+ Returns:
1160
+ Optional[Dict[str, Any]]: The upserted record or None if failed
1161
+ """
1162
+ try:
1163
+ date_str = record.get("date")
1164
+ if not date_str:
1165
+ log_error("Metrics record missing date field")
1166
+ return None
1167
+
1168
+ # Convert date object to string if needed
1169
+ if hasattr(date_str, "isoformat"):
1170
+ date_str = date_str.isoformat()
1171
+
1172
+ # Check if a record already exists for this date
1173
+ existing_record = self._get_existing_metrics_record(table_name, date_str)
1174
+
1175
+ if existing_record:
1176
+ return self._update_existing_metrics_record(table_name, existing_record, record)
1177
+ else:
1178
+ return self._create_new_metrics_record(table_name, record)
1179
+
1180
+ except Exception as e:
1181
+ log_error(f"Failed to upsert single metrics record: {e}")
1182
+ return None
1183
+
1184
+ def _get_existing_metrics_record(self, table_name: str, date_str: str) -> Optional[Dict[str, Any]]:
1185
+ """Get existing metrics record for a given date.
1186
+
1187
+ Args:
1188
+ table_name: The DynamoDB table name
1189
+ date_str: The date string to search for
1190
+
1191
+ Returns:
1192
+ Optional[Dict[str, Any]]: The existing record or None if not found
1193
+ """
1194
+ try:
1195
+ # Query using the date-aggregation_period-index
1196
+ response = self.client.query(
1197
+ TableName=table_name,
1198
+ IndexName="date-aggregation_period-index",
1199
+ KeyConditionExpression="#date = :date AND aggregation_period = :period",
1200
+ ExpressionAttributeNames={"#date": "date"},
1201
+ ExpressionAttributeValues={
1202
+ ":date": {"S": date_str},
1203
+ ":period": {"S": "daily"},
1204
+ },
1205
+ Limit=1,
1206
+ )
1207
+
1208
+ items = response.get("Items", [])
1209
+ if items:
1210
+ return deserialize_from_dynamodb_item(items[0])
1211
+ return None
1212
+
1213
+ except Exception as e:
1214
+ log_error(f"Failed to get existing metrics record for date {date_str}: {e}")
1215
+ return None
1216
+
1217
+ def _update_existing_metrics_record(
1218
+ self,
1219
+ table_name: str,
1220
+ existing_record: Dict[str, Any],
1221
+ new_record: Dict[str, Any],
1222
+ ) -> Optional[Dict[str, Any]]:
1223
+ """Update an existing metrics record.
1224
+
1225
+ Args:
1226
+ table_name: The DynamoDB table name
1227
+ existing_record: The existing record
1228
+ new_record: The new record data
1229
+
1230
+ Returns:
1231
+ Optional[Dict[str, Any]]: The updated record or None if failed
1232
+ """
1233
+ try:
1234
+ # Use the existing record's ID
1235
+ new_record["id"] = existing_record["id"]
1236
+ new_record["updated_at"] = int(time.time())
1237
+
1238
+ # Prepare and serialize the record
1239
+ prepared_record = self._prepare_metrics_record_for_dynamo(new_record)
1240
+ item = self._serialize_metrics_to_dynamo_item(prepared_record)
1241
+
1242
+ # Update the record
1243
+ self.client.put_item(TableName=table_name, Item=item)
1244
+
1245
+ return new_record
1246
+
1247
+ except Exception as e:
1248
+ log_error(f"Failed to update existing metrics record: {e}")
1249
+ return None
1250
+
1251
+ def _create_new_metrics_record(self, table_name: str, record: Dict[str, Any]) -> Optional[Dict[str, Any]]:
1252
+ """Create a new metrics record.
1253
+
1254
+ Args:
1255
+ table_name: The DynamoDB table name
1256
+ record: The record to create
1257
+
1258
+ Returns:
1259
+ Optional[Dict[str, Any]]: The created record or None if failed
1260
+ """
1261
+ try:
1262
+ # Prepare and serialize the record
1263
+ prepared_record = self._prepare_metrics_record_for_dynamo(record)
1264
+ item = self._serialize_metrics_to_dynamo_item(prepared_record)
1265
+
1266
+ # Create the record
1267
+ self.client.put_item(TableName=table_name, Item=item)
1268
+
1269
+ return record
1270
+
1271
+ except Exception as e:
1272
+ log_error(f"Failed to create new metrics record: {e}")
1273
+ return None
1274
+
1275
+ def _prepare_metrics_record_for_dynamo(self, record: Dict[str, Any]) -> Dict[str, Any]:
1276
+ """Prepare a metrics record for DynamoDB serialization by converting all data types properly.
1277
+
1278
+ Args:
1279
+ record: The metrics record to prepare
1280
+
1281
+ Returns:
1282
+ Dict[str, Any]: The prepared record ready for DynamoDB serialization
1283
+ """
1284
+
1285
+ def convert_value(value):
1286
+ """Recursively convert values to DynamoDB-compatible types."""
1287
+ if value is None:
1288
+ return None
1289
+ elif isinstance(value, bool):
1290
+ return value
1291
+ elif isinstance(value, (int, float)):
1292
+ return value
1293
+ elif isinstance(value, str):
1294
+ return value
1295
+ elif hasattr(value, "isoformat"): # date/datetime objects
1296
+ return value.isoformat()
1297
+ elif isinstance(value, dict):
1298
+ return {k: convert_value(v) for k, v in value.items()}
1299
+ elif isinstance(value, list):
1300
+ return [convert_value(item) for item in value]
1301
+ else:
1302
+ return str(value)
1303
+
1304
+ return {key: convert_value(value) for key, value in record.items()}
1305
+
1306
+ def _serialize_metrics_to_dynamo_item(self, data: Dict[str, Any]) -> Dict[str, Any]:
1307
+ """Serialize metrics data to DynamoDB item format with proper boolean handling.
1308
+
1309
+ Args:
1310
+ data: The metrics data to serialize
1311
+
1312
+ Returns:
1313
+ Dict[str, Any]: DynamoDB-ready item
1314
+ """
1315
+ import json
1316
+
1317
+ item = {}
1318
+ for key, value in data.items():
1319
+ if value is not None:
1320
+ if isinstance(value, bool):
1321
+ item[key] = {"BOOL": str(value)}
1322
+ elif isinstance(value, (int, float)):
1323
+ item[key] = {"N": str(value)}
1324
+ elif isinstance(value, str):
1325
+ item[key] = {"S": str(value)}
1326
+ elif isinstance(value, (dict, list)):
1327
+ item[key] = {"S": json.dumps(str(value))}
1328
+ else:
1329
+ item[key] = {"S": str(value)}
1330
+ return item
1331
+
1332
+ def get_metrics(
1333
+ self,
1334
+ starting_date: Optional[date] = None,
1335
+ ending_date: Optional[date] = None,
1336
+ ) -> Tuple[List[Any], Optional[int]]:
1337
+ """
1338
+ Get metrics from the database.
1339
+
1340
+ Args:
1341
+ starting_date: The starting date to filter metrics by.
1342
+ ending_date: The ending date to filter metrics by.
1343
+
1344
+ Returns:
1345
+ Tuple[List[Any], Optional[int]]: A tuple containing the metrics data and the total count.
1346
+
1347
+ Raises:
1348
+ Exception: If any error occurs while getting the metrics.
1349
+ """
1350
+
1351
+ try:
1352
+ table_name = self._get_table("metrics")
1353
+ if table_name is None:
1354
+ return ([], None)
1355
+
1356
+ # Build query parameters
1357
+ scan_kwargs: Dict[str, Any] = {"TableName": table_name}
1358
+
1359
+ if starting_date or ending_date:
1360
+ filter_expressions = []
1361
+ expression_values = {}
1362
+
1363
+ if starting_date:
1364
+ filter_expressions.append("#date >= :start_date")
1365
+ expression_values[":start_date"] = {"S": starting_date.isoformat()}
1366
+
1367
+ if ending_date:
1368
+ filter_expressions.append("#date <= :end_date")
1369
+ expression_values[":end_date"] = {"S": ending_date.isoformat()}
1370
+
1371
+ scan_kwargs["FilterExpression"] = " AND ".join(filter_expressions)
1372
+ scan_kwargs["ExpressionAttributeNames"] = {"#date": "date"}
1373
+ scan_kwargs["ExpressionAttributeValues"] = expression_values
1374
+
1375
+ # Execute scan
1376
+ response = self.client.scan(**scan_kwargs)
1377
+ items = response.get("Items", [])
1378
+
1379
+ # Handle pagination
1380
+ while "LastEvaluatedKey" in response:
1381
+ scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]
1382
+ response = self.client.scan(**scan_kwargs)
1383
+ items.extend(response.get("Items", []))
1384
+
1385
+ # Convert to metrics data
1386
+ metrics_data = []
1387
+ for item in items:
1388
+ metric_data = deserialize_from_dynamodb_item(item)
1389
+ if metric_data:
1390
+ metrics_data.append(metric_data)
1391
+
1392
+ return metrics_data, len(metrics_data)
1393
+
1394
+ except Exception as e:
1395
+ log_error(f"Failed to get metrics: {e}")
1396
+ return [], 0
1397
+
1398
+ # --- Knowledge methods ---
1399
+
1400
+ def delete_knowledge_content(self, id: str):
1401
+ """Delete a knowledge row from the database.
1402
+
1403
+ Args:
1404
+ id (str): The ID of the knowledge row to delete.
1405
+
1406
+ Raises:
1407
+ Exception: If an error occurs during deletion.
1408
+ """
1409
+ try:
1410
+ table_name = self._get_table("knowledge")
1411
+
1412
+ self.client.delete_item(TableName=table_name, Key={"id": {"S": id}})
1413
+
1414
+ log_debug(f"Deleted knowledge content {id}")
1415
+
1416
+ except Exception as e:
1417
+ log_error(f"Failed to delete knowledge content {id}: {e}")
1418
+
1419
+ def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]:
1420
+ """Get a knowledge row from the database.
1421
+
1422
+ Args:
1423
+ id (str): The ID of the knowledge row to get.
1424
+
1425
+ Returns:
1426
+ Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist.
1427
+ """
1428
+ try:
1429
+ table_name = self._get_table("knowledge")
1430
+ response = self.client.get_item(TableName=table_name, Key={"id": {"S": id}})
1431
+
1432
+ item = response.get("Item")
1433
+ if item:
1434
+ return deserialize_knowledge_row(item)
1435
+
1436
+ return None
1437
+
1438
+ except Exception as e:
1439
+ log_error(f"Failed to get knowledge content {id}: {e}")
1440
+ return None
1441
+
1442
+ def get_knowledge_contents(
1443
+ self,
1444
+ limit: Optional[int] = None,
1445
+ page: Optional[int] = None,
1446
+ sort_by: Optional[str] = None,
1447
+ sort_order: Optional[str] = None,
1448
+ ) -> Tuple[List[KnowledgeRow], int]:
1449
+ """Get all knowledge contents from the database.
1450
+
1451
+ Args:
1452
+ limit (Optional[int]): The maximum number of knowledge contents to return.
1453
+ page (Optional[int]): The page number.
1454
+ sort_by (Optional[str]): The column to sort by.
1455
+ sort_order (Optional[str]): The order to sort by.
1456
+ create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist.
1457
+
1458
+ Returns:
1459
+ Tuple[List[KnowledgeRow], int]: The knowledge contents and total count.
1460
+
1461
+ Raises:
1462
+ Exception: If an error occurs during retrieval.
1463
+ """
1464
+ try:
1465
+ table_name = self._get_table("knowledge")
1466
+ if table_name is None:
1467
+ return [], 0
1468
+
1469
+ response = self.client.scan(TableName=table_name)
1470
+ items = response.get("Items", [])
1471
+
1472
+ # Handle pagination
1473
+ while "LastEvaluatedKey" in response:
1474
+ response = self.client.scan(
1475
+ TableName=table_name,
1476
+ ExclusiveStartKey=response["LastEvaluatedKey"],
1477
+ )
1478
+ items.extend(response.get("Items", []))
1479
+
1480
+ # Convert to knowledge rows
1481
+ knowledge_rows = []
1482
+ for item in items:
1483
+ try:
1484
+ knowledge_row = deserialize_knowledge_row(item)
1485
+ knowledge_rows.append(knowledge_row)
1486
+ except Exception as e:
1487
+ log_error(f"Failed to deserialize knowledge row: {e}")
1488
+
1489
+ # Apply sorting
1490
+ if sort_by:
1491
+ reverse = sort_order == "desc"
1492
+ knowledge_rows = sorted(
1493
+ knowledge_rows,
1494
+ key=lambda x: getattr(x, sort_by, ""),
1495
+ reverse=reverse,
1496
+ )
1497
+
1498
+ # Get total count before pagination
1499
+ total_count = len(knowledge_rows)
1500
+
1501
+ # Apply pagination
1502
+ if limit:
1503
+ start_index = 0
1504
+ if page and page > 1:
1505
+ start_index = (page - 1) * limit
1506
+ knowledge_rows = knowledge_rows[start_index : start_index + limit]
1507
+
1508
+ return knowledge_rows, total_count
1509
+
1510
+ except Exception as e:
1511
+ log_error(f"Failed to get knowledge contents: {e}")
1512
+ return [], 0
1513
+
1514
+ def upsert_knowledge_content(self, knowledge_row: KnowledgeRow):
1515
+ """Upsert knowledge content in the database.
1516
+
1517
+ Args:
1518
+ knowledge_row (KnowledgeRow): The knowledge row to upsert.
1519
+
1520
+ Returns:
1521
+ Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails.
1522
+ """
1523
+ try:
1524
+ table_name = self._get_table("knowledge", create_table_if_not_found=True)
1525
+ item = serialize_knowledge_row(knowledge_row)
1526
+
1527
+ self.client.put_item(TableName=table_name, Item=item)
1528
+
1529
+ return knowledge_row
1530
+
1531
+ except Exception as e:
1532
+ log_error(f"Failed to upsert knowledge content {knowledge_row.id}: {e}")
1533
+ return None
1534
+
1535
+ # --- Eval ---
1536
+
1537
+ def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]:
1538
+ """Create an eval run in the database.
1539
+
1540
+ Args:
1541
+ eval_run (EvalRunRecord): The eval run to create.
1542
+
1543
+ Returns:
1544
+ Optional[EvalRunRecord]: The created eval run, or None if the operation fails.
1545
+
1546
+ Raises:
1547
+ Exception: If an error occurs during creation.
1548
+ """
1549
+ try:
1550
+ table_name = self._get_table("evals", create_table_if_not_found=True)
1551
+
1552
+ item = serialize_eval_record(eval_run)
1553
+ current_time = int(datetime.now(timezone.utc).timestamp())
1554
+ item["created_at"] = {"N": str(current_time)}
1555
+ item["updated_at"] = {"N": str(current_time)}
1556
+
1557
+ self.client.put_item(TableName=table_name, Item=item)
1558
+
1559
+ return eval_run
1560
+
1561
+ except Exception as e:
1562
+ log_error(f"Failed to create eval run: {e}")
1563
+ return None
1564
+
1565
+ def delete_eval_runs(self, eval_run_ids: List[str]) -> None:
1566
+ if not eval_run_ids or not self.eval_table_name:
1567
+ return
1568
+
1569
+ try:
1570
+ for i in range(0, len(eval_run_ids), DYNAMO_BATCH_SIZE_LIMIT):
1571
+ batch = eval_run_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT]
1572
+
1573
+ delete_requests = []
1574
+ for eval_run_id in batch:
1575
+ delete_requests.append({"DeleteRequest": {"Key": {"run_id": {"S": eval_run_id}}}})
1576
+
1577
+ self.client.batch_write_item(RequestItems={self.eval_table_name: delete_requests})
1578
+
1579
+ except Exception as e:
1580
+ log_error(f"Failed to delete eval runs: {e}")
1581
+
1582
+ def get_eval_run_raw(self, eval_run_id: str, table: Optional[Any] = None) -> Optional[Dict[str, Any]]:
1583
+ if not self.eval_table_name:
1584
+ return None
1585
+
1586
+ try:
1587
+ response = self.client.get_item(TableName=self.eval_table_name, Key={"run_id": {"S": eval_run_id}})
1588
+
1589
+ item = response.get("Item")
1590
+ if item:
1591
+ return deserialize_from_dynamodb_item(item)
1592
+ return None
1593
+
1594
+ except Exception as e:
1595
+ log_error(f"Failed to get eval run {eval_run_id}: {e}")
1596
+ return None
1597
+
1598
+ def get_eval_run(self, eval_run_id: str, table: Optional[Any] = None) -> Optional[EvalRunRecord]:
1599
+ if not self.eval_table_name:
1600
+ return None
1601
+
1602
+ try:
1603
+ response = self.client.get_item(TableName=self.eval_table_name, Key={"run_id": {"S": eval_run_id}})
1604
+
1605
+ item = response.get("Item")
1606
+ if item:
1607
+ return deserialize_eval_record(item)
1608
+ return None
1609
+
1610
+ except Exception as e:
1611
+ log_error(f"Failed to get eval run {eval_run_id}: {e}")
1612
+ return None
1613
+
1614
+ def get_eval_runs(
1615
+ self,
1616
+ limit: Optional[int] = None,
1617
+ page: Optional[int] = None,
1618
+ sort_by: Optional[str] = None,
1619
+ sort_order: Optional[str] = None,
1620
+ agent_id: Optional[str] = None,
1621
+ team_id: Optional[str] = None,
1622
+ workflow_id: Optional[str] = None,
1623
+ model_id: Optional[str] = None,
1624
+ filter_type: Optional[EvalFilterType] = None,
1625
+ eval_type: Optional[List[EvalType]] = None,
1626
+ deserialize: Optional[bool] = True,
1627
+ ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]:
1628
+ try:
1629
+ table_name = self._get_table("evals")
1630
+ if table_name is None:
1631
+ return [] if deserialize else ([], 0)
1632
+
1633
+ scan_kwargs = {"TableName": table_name}
1634
+
1635
+ filter_expressions = []
1636
+ expression_values = {}
1637
+
1638
+ if agent_id:
1639
+ filter_expressions.append("agent_id = :agent_id")
1640
+ expression_values[":agent_id"] = {"S": agent_id}
1641
+
1642
+ if team_id:
1643
+ filter_expressions.append("team_id = :team_id")
1644
+ expression_values[":team_id"] = {"S": team_id}
1645
+
1646
+ if workflow_id:
1647
+ filter_expressions.append("workflow_id = :workflow_id")
1648
+ expression_values[":workflow_id"] = {"S": workflow_id}
1649
+
1650
+ if model_id:
1651
+ filter_expressions.append("model_id = :model_id")
1652
+ expression_values[":model_id"] = {"S": model_id}
1653
+
1654
+ if eval_type is not None and len(eval_type) > 0:
1655
+ eval_type_conditions = []
1656
+ for i, et in enumerate(eval_type):
1657
+ param_name = f":eval_type_{i}"
1658
+ eval_type_conditions.append(f"eval_type = {param_name}")
1659
+ expression_values[param_name] = {"S": str(et.value)}
1660
+ filter_expressions.append(f"({' OR '.join(eval_type_conditions)})")
1661
+
1662
+ if filter_type is not None:
1663
+ if filter_type == EvalFilterType.AGENT:
1664
+ filter_expressions.append("agent_id IS NOT NULL")
1665
+ elif filter_type == EvalFilterType.TEAM:
1666
+ filter_expressions.append("team_id IS NOT NULL")
1667
+ elif filter_type == EvalFilterType.WORKFLOW:
1668
+ filter_expressions.append("workflow_id IS NOT NULL")
1669
+
1670
+ if filter_expressions:
1671
+ scan_kwargs["FilterExpression"] = " AND ".join(filter_expressions)
1672
+ scan_kwargs["ExpressionAttributeValues"] = expression_values # type: ignore
1673
+
1674
+ # Execute scan
1675
+ response = self.client.scan(**scan_kwargs)
1676
+ items = response.get("Items", [])
1677
+
1678
+ # Handle pagination
1679
+ while "LastEvaluatedKey" in response:
1680
+ scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"]
1681
+ response = self.client.scan(**scan_kwargs)
1682
+ items.extend(response.get("Items", []))
1683
+
1684
+ # Convert to eval data
1685
+ eval_data = []
1686
+ for item in items:
1687
+ eval_item = deserialize_from_dynamodb_item(item)
1688
+ if eval_item:
1689
+ eval_data.append(eval_item)
1690
+
1691
+ # Apply sorting
1692
+ eval_data = apply_sorting(eval_data, sort_by, sort_order)
1693
+
1694
+ # Get total count before pagination
1695
+ total_count = len(eval_data)
1696
+
1697
+ # Apply pagination
1698
+ eval_data = apply_pagination(eval_data, limit, page)
1699
+
1700
+ if not deserialize:
1701
+ return eval_data, total_count
1702
+
1703
+ eval_runs = []
1704
+ for eval_item in eval_data:
1705
+ eval_run = EvalRunRecord.model_validate(eval_item)
1706
+ eval_runs.append(eval_run)
1707
+ return eval_runs
1708
+
1709
+ except Exception as e:
1710
+ log_error(f"Failed to get eval runs: {e}")
1711
+ return [] if deserialize else ([], 0)
1712
+
1713
+ def rename_eval_run(
1714
+ self, eval_run_id: str, name: str, deserialize: Optional[bool] = True
1715
+ ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]:
1716
+ if not self.eval_table_name:
1717
+ return None
1718
+
1719
+ try:
1720
+ response = self.client.update_item(
1721
+ TableName=self.eval_table_name,
1722
+ Key={"run_id": {"S": eval_run_id}},
1723
+ UpdateExpression="SET #name = :name, updated_at = :updated_at",
1724
+ ExpressionAttributeNames={"#name": "name"},
1725
+ ExpressionAttributeValues={
1726
+ ":name": {"S": name},
1727
+ ":updated_at": {"N": str(int(time.time()))},
1728
+ },
1729
+ ReturnValues="ALL_NEW",
1730
+ )
1731
+
1732
+ item = response.get("Attributes")
1733
+ if item is None:
1734
+ return None
1735
+
1736
+ log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'")
1737
+
1738
+ item = deserialize_from_dynamodb_item(item)
1739
+ return EvalRunRecord.model_validate(item) if deserialize else item
1740
+
1741
+ except Exception as e:
1742
+ log_error(f"Failed to rename eval run {eval_run_id}: {e}")
1743
+ return None