agno 2.3.4__py3-none-any.whl → 2.3.6__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 (116) hide show
  1. agno/agent/agent.py +184 -45
  2. agno/culture/manager.py +2 -2
  3. agno/db/base.py +330 -8
  4. agno/db/dynamo/dynamo.py +722 -2
  5. agno/db/dynamo/schemas.py +127 -0
  6. agno/db/firestore/firestore.py +573 -1
  7. agno/db/firestore/schemas.py +40 -0
  8. agno/db/gcs_json/gcs_json_db.py +446 -1
  9. agno/db/in_memory/in_memory_db.py +143 -1
  10. agno/db/json/json_db.py +438 -1
  11. agno/db/mongo/async_mongo.py +522 -0
  12. agno/db/mongo/mongo.py +523 -1
  13. agno/db/mongo/schemas.py +29 -0
  14. agno/db/mysql/mysql.py +536 -3
  15. agno/db/mysql/schemas.py +38 -0
  16. agno/db/postgres/async_postgres.py +553 -15
  17. agno/db/postgres/postgres.py +544 -5
  18. agno/db/postgres/schemas.py +38 -0
  19. agno/db/redis/redis.py +468 -1
  20. agno/db/redis/schemas.py +32 -0
  21. agno/db/singlestore/schemas.py +38 -0
  22. agno/db/singlestore/singlestore.py +523 -1
  23. agno/db/sqlite/async_sqlite.py +549 -10
  24. agno/db/sqlite/schemas.py +38 -0
  25. agno/db/sqlite/sqlite.py +540 -9
  26. agno/db/sqlite/utils.py +6 -8
  27. agno/db/surrealdb/models.py +25 -0
  28. agno/db/surrealdb/surrealdb.py +548 -1
  29. agno/eval/accuracy.py +18 -8
  30. agno/eval/performance.py +10 -4
  31. agno/eval/reliability.py +22 -13
  32. agno/exceptions.py +11 -0
  33. agno/hooks/__init__.py +3 -0
  34. agno/hooks/decorator.py +164 -0
  35. agno/integrations/discord/client.py +1 -1
  36. agno/knowledge/chunking/semantic.py +2 -2
  37. agno/models/aimlapi/aimlapi.py +2 -3
  38. agno/models/anthropic/claude.py +18 -13
  39. agno/models/aws/bedrock.py +3 -4
  40. agno/models/aws/claude.py +5 -1
  41. agno/models/azure/ai_foundry.py +2 -2
  42. agno/models/azure/openai_chat.py +8 -0
  43. agno/models/cerebras/cerebras.py +62 -11
  44. agno/models/cerebras/cerebras_openai.py +2 -3
  45. agno/models/cohere/chat.py +1 -5
  46. agno/models/cometapi/cometapi.py +2 -3
  47. agno/models/dashscope/dashscope.py +2 -3
  48. agno/models/deepinfra/deepinfra.py +2 -3
  49. agno/models/deepseek/deepseek.py +2 -3
  50. agno/models/fireworks/fireworks.py +2 -3
  51. agno/models/google/gemini.py +9 -7
  52. agno/models/groq/groq.py +2 -3
  53. agno/models/huggingface/huggingface.py +1 -5
  54. agno/models/ibm/watsonx.py +1 -5
  55. agno/models/internlm/internlm.py +2 -3
  56. agno/models/langdb/langdb.py +6 -4
  57. agno/models/litellm/chat.py +2 -2
  58. agno/models/litellm/litellm_openai.py +2 -3
  59. agno/models/meta/llama.py +1 -5
  60. agno/models/meta/llama_openai.py +4 -5
  61. agno/models/mistral/mistral.py +1 -5
  62. agno/models/nebius/nebius.py +2 -3
  63. agno/models/nvidia/nvidia.py +4 -5
  64. agno/models/openai/chat.py +14 -3
  65. agno/models/openai/responses.py +14 -3
  66. agno/models/openrouter/openrouter.py +4 -5
  67. agno/models/perplexity/perplexity.py +2 -3
  68. agno/models/portkey/portkey.py +7 -6
  69. agno/models/requesty/requesty.py +4 -5
  70. agno/models/response.py +2 -1
  71. agno/models/sambanova/sambanova.py +4 -5
  72. agno/models/siliconflow/siliconflow.py +3 -4
  73. agno/models/together/together.py +4 -5
  74. agno/models/vercel/v0.py +4 -5
  75. agno/models/vllm/vllm.py +19 -14
  76. agno/models/xai/xai.py +4 -5
  77. agno/os/app.py +104 -0
  78. agno/os/config.py +13 -0
  79. agno/os/interfaces/whatsapp/router.py +0 -1
  80. agno/os/interfaces/whatsapp/security.py +3 -1
  81. agno/os/mcp.py +1 -0
  82. agno/os/router.py +31 -0
  83. agno/os/routers/traces/__init__.py +3 -0
  84. agno/os/routers/traces/schemas.py +414 -0
  85. agno/os/routers/traces/traces.py +499 -0
  86. agno/os/schema.py +12 -2
  87. agno/os/utils.py +57 -0
  88. agno/run/agent.py +1 -0
  89. agno/run/base.py +17 -0
  90. agno/run/team.py +4 -0
  91. agno/table.py +10 -0
  92. agno/team/team.py +221 -69
  93. agno/tools/function.py +10 -8
  94. agno/tools/google_drive.py +4 -3
  95. agno/tools/nano_banana.py +1 -1
  96. agno/tools/spotify.py +922 -0
  97. agno/tracing/__init__.py +12 -0
  98. agno/tracing/exporter.py +157 -0
  99. agno/tracing/schemas.py +276 -0
  100. agno/tracing/setup.py +111 -0
  101. agno/utils/agent.py +6 -6
  102. agno/utils/hooks.py +56 -1
  103. agno/utils/mcp.py +1 -1
  104. agno/vectordb/qdrant/qdrant.py +22 -22
  105. agno/workflow/condition.py +8 -0
  106. agno/workflow/loop.py +8 -0
  107. agno/workflow/parallel.py +8 -0
  108. agno/workflow/router.py +8 -0
  109. agno/workflow/step.py +20 -0
  110. agno/workflow/steps.py +8 -0
  111. agno/workflow/workflow.py +88 -19
  112. {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/METADATA +38 -33
  113. {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/RECORD +116 -105
  114. {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/WHEEL +0 -0
  115. {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/licenses/LICENSE +0 -0
  116. {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/top_level.txt +0 -0
@@ -1,9 +1,12 @@
1
1
  import time
2
2
  import warnings
3
3
  from datetime import date, datetime, timedelta, timezone
4
- from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
4
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
5
5
  from uuid import uuid4
6
6
 
7
+ if TYPE_CHECKING:
8
+ from agno.tracing.schemas import Span, Trace
9
+
7
10
  from agno.db.base import AsyncBaseDb, SessionType
8
11
  from agno.db.migrations.manager import MigrationManager
9
12
  from agno.db.postgres.schemas import get_table_schema_definition
@@ -27,10 +30,11 @@ from agno.session import AgentSession, Session, TeamSession, WorkflowSession
27
30
  from agno.utils.log import log_debug, log_error, log_info, log_warning
28
31
 
29
32
  try:
30
- from sqlalchemy import Index, String, UniqueConstraint, func, update
33
+ from sqlalchemy import Index, String, Table, UniqueConstraint, func, update
31
34
  from sqlalchemy.dialects import postgresql
35
+ from sqlalchemy.exc import ProgrammingError
32
36
  from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
33
- from sqlalchemy.schema import Column, MetaData, Table
37
+ from sqlalchemy.schema import Column, MetaData
34
38
  from sqlalchemy.sql.expression import select, text
35
39
  except ImportError:
36
40
  raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`")
@@ -49,6 +53,8 @@ class AsyncPostgresDb(AsyncBaseDb):
49
53
  eval_table: Optional[str] = None,
50
54
  knowledge_table: Optional[str] = None,
51
55
  culture_table: Optional[str] = None,
56
+ traces_table: Optional[str] = None,
57
+ spans_table: Optional[str] = None,
52
58
  versions_table: Optional[str] = None,
53
59
  db_id: Optional[str] = None, # Deprecated, use id instead.
54
60
  ):
@@ -71,6 +77,8 @@ class AsyncPostgresDb(AsyncBaseDb):
71
77
  eval_table (Optional[str]): Name of the table to store evaluation runs data.
72
78
  knowledge_table (Optional[str]): Name of the table to store knowledge content.
73
79
  culture_table (Optional[str]): Name of the table to store cultural knowledge.
80
+ traces_table (Optional[str]): Name of the table to store run traces.
81
+ spans_table (Optional[str]): Name of the table to store span events.
74
82
  versions_table (Optional[str]): Name of the table to store schema versions.
75
83
  db_id: Deprecated, use id instead.
76
84
 
@@ -93,6 +101,8 @@ class AsyncPostgresDb(AsyncBaseDb):
93
101
  eval_table=eval_table,
94
102
  knowledge_table=knowledge_table,
95
103
  culture_table=culture_table,
104
+ traces_table=traces_table,
105
+ spans_table=spans_table,
96
106
  versions_table=versions_table,
97
107
  )
98
108
 
@@ -138,7 +148,9 @@ class AsyncPostgresDb(AsyncBaseDb):
138
148
  ]
139
149
 
140
150
  for table_name, table_type in tables_to_create:
141
- await self._get_or_create_table(table_name=table_name, table_type=table_type)
151
+ await self._get_or_create_table(
152
+ table_name=table_name, table_type=table_type, create_table_if_not_found=True
153
+ )
142
154
 
143
155
  async def _create_table(self, table_name: str, table_type: str) -> Table:
144
156
  """
@@ -239,7 +251,7 @@ class AsyncPostgresDb(AsyncBaseDb):
239
251
  log_error(f"Could not create table {self.db_schema}.{table_name}: {e}")
240
252
  raise
241
253
 
242
- async def _get_table(self, table_type: str) -> Table:
254
+ async def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Table:
243
255
  if table_type == "sessions":
244
256
  if not hasattr(self, "session_table"):
245
257
  self.session_table = await self._get_or_create_table(
@@ -287,9 +299,31 @@ class AsyncPostgresDb(AsyncBaseDb):
287
299
  )
288
300
  return self.versions_table
289
301
 
302
+ if table_type == "traces":
303
+ if not hasattr(self, "traces_table"):
304
+ self.traces_table = await self._get_or_create_table(
305
+ table_name=self.trace_table_name,
306
+ table_type="traces",
307
+ create_table_if_not_found=create_table_if_not_found,
308
+ )
309
+ return self.traces_table
310
+
311
+ if table_type == "spans":
312
+ if not hasattr(self, "spans_table"):
313
+ # Ensure traces table exists first (spans has FK to traces)
314
+ await self._get_table(table_type="traces", create_table_if_not_found=True)
315
+ self.spans_table = await self._get_or_create_table(
316
+ table_name=self.span_table_name,
317
+ table_type="spans",
318
+ create_table_if_not_found=create_table_if_not_found,
319
+ )
320
+ return self.spans_table
321
+
290
322
  raise ValueError(f"Unknown table type: {table_type}")
291
323
 
292
- async def _get_or_create_table(self, table_name: str, table_type: str) -> Table:
324
+ async def _get_or_create_table(
325
+ self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False
326
+ ) -> Table:
293
327
  """
294
328
  Check if the table exists and is valid, else create it.
295
329
 
@@ -306,7 +340,7 @@ class AsyncPostgresDb(AsyncBaseDb):
306
340
  session=sess, table_name=table_name, db_schema=self.db_schema
307
341
  )
308
342
 
309
- if not table_is_available:
343
+ if (not table_is_available) and create_table_if_not_found:
310
344
  return await self._create_table(table_name=table_name, table_type=table_type)
311
345
 
312
346
  if not await ais_valid_table(
@@ -333,7 +367,7 @@ class AsyncPostgresDb(AsyncBaseDb):
333
367
 
334
368
  async def get_latest_schema_version(self, table_name: str) -> str:
335
369
  """Get the latest version of the database schema."""
336
- table = await self._get_table(table_type="versions")
370
+ table = await self._get_table(table_type="versions", create_table_if_not_found=True)
337
371
  if table is None:
338
372
  return "2.0.0"
339
373
 
@@ -352,7 +386,7 @@ class AsyncPostgresDb(AsyncBaseDb):
352
386
 
353
387
  async def upsert_schema_version(self, table_name: str, version: str) -> None:
354
388
  """Upsert the schema version into the database."""
355
- table = await self._get_table(table_type="versions")
389
+ table = await self._get_table(table_type="versions", create_table_if_not_found=True)
356
390
  if table is None:
357
391
  return
358
392
  current_datetime = datetime.now().isoformat()
@@ -665,7 +699,7 @@ class AsyncPostgresDb(AsyncBaseDb):
665
699
  Exception: If an error occurs during upsert.
666
700
  """
667
701
  try:
668
- table = await self._get_table(table_type="sessions")
702
+ table = await self._get_table(table_type="sessions", create_table_if_not_found=True)
669
703
  session_dict = session.to_dict()
670
704
 
671
705
  if isinstance(session, AgentSession):
@@ -796,7 +830,7 @@ class AsyncPostgresDb(AsyncBaseDb):
796
830
  return None
797
831
 
798
832
  # -- Memory methods --
799
- async def delete_user_memory(self, memory_id: str):
833
+ async def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None):
800
834
  """Delete a user memory from the database.
801
835
 
802
836
  Returns:
@@ -810,6 +844,8 @@ class AsyncPostgresDb(AsyncBaseDb):
810
844
 
811
845
  async with self.async_session_factory() as sess, sess.begin():
812
846
  delete_stmt = table.delete().where(table.c.memory_id == memory_id)
847
+ if user_id is not None:
848
+ delete_stmt = delete_stmt.where(table.c.user_id == user_id)
813
849
  result = await sess.execute(delete_stmt)
814
850
 
815
851
  success = result.rowcount > 0 # type: ignore
@@ -849,9 +885,12 @@ class AsyncPostgresDb(AsyncBaseDb):
849
885
  except Exception as e:
850
886
  log_error(f"Error deleting user memories: {e}")
851
887
 
852
- async def get_all_memory_topics(self) -> List[str]:
888
+ async def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]:
853
889
  """Get all memory topics from the database.
854
890
 
891
+ Args:
892
+ user_id (Optional[str]): The ID of the user to filter by.
893
+
855
894
  Returns:
856
895
  List[str]: List of memory topics.
857
896
  """
@@ -859,8 +898,19 @@ class AsyncPostgresDb(AsyncBaseDb):
859
898
  table = await self._get_table(table_type="memories")
860
899
 
861
900
  async with self.async_session_factory() as sess, sess.begin():
862
- stmt = select(func.json_array_elements_text(table.c.topics))
863
- result = await sess.execute(stmt)
901
+ try:
902
+ stmt = select(func.jsonb_array_elements_text(table.c.topics))
903
+ if user_id is not None:
904
+ stmt = stmt.where(table.c.user_id == user_id)
905
+ result = await sess.execute(stmt)
906
+ except ProgrammingError:
907
+ # Retrying with json_array_elements_text. This works in older versions,
908
+ # where the topics column was of type JSON instead of JSONB
909
+ stmt = select(func.json_array_elements_text(table.c.topics))
910
+ if user_id is not None:
911
+ stmt = stmt.where(table.c.user_id == user_id)
912
+ result = await sess.execute(stmt)
913
+
864
914
  records = result.fetchall()
865
915
 
866
916
  return list(set([record[0] for record in records]))
@@ -870,13 +920,17 @@ class AsyncPostgresDb(AsyncBaseDb):
870
920
  return []
871
921
 
872
922
  async def get_user_memory(
873
- self, memory_id: str, deserialize: Optional[bool] = True
923
+ self,
924
+ memory_id: str,
925
+ deserialize: Optional[bool] = True,
926
+ user_id: Optional[str] = None,
874
927
  ) -> Optional[Union[UserMemory, Dict[str, Any]]]:
875
928
  """Get a memory from the database.
876
929
 
877
930
  Args:
878
931
  memory_id (str): The ID of the memory to get.
879
932
  deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True.
933
+ user_id (Optional[str]): The ID of the user to filter by.
880
934
 
881
935
  Returns:
882
936
  Union[UserMemory, Dict[str, Any], None]:
@@ -891,6 +945,8 @@ class AsyncPostgresDb(AsyncBaseDb):
891
945
 
892
946
  async with self.async_session_factory() as sess, sess.begin():
893
947
  stmt = select(table).where(table.c.memory_id == memory_id)
948
+ if user_id is not None:
949
+ stmt = stmt.where(table.c.user_id == user_id)
894
950
 
895
951
  result = await sess.execute(stmt)
896
952
  row = result.fetchone()
@@ -2013,3 +2069,485 @@ class AsyncPostgresDb(AsyncBaseDb):
2013
2069
  for memory in memories:
2014
2070
  await self.upsert_user_memory(memory)
2015
2071
  log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}")
2072
+
2073
+ # --- Traces ---
2074
+ def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None):
2075
+ """Build base query for traces with aggregated span counts.
2076
+
2077
+ Args:
2078
+ table: The traces table.
2079
+ spans_table: The spans table (optional).
2080
+
2081
+ Returns:
2082
+ SQLAlchemy select statement with total_spans and error_count calculated dynamically.
2083
+ """
2084
+ from sqlalchemy import case, literal
2085
+
2086
+ if spans_table is not None:
2087
+ # JOIN with spans table to calculate total_spans and error_count
2088
+ return (
2089
+ select(
2090
+ table,
2091
+ func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"),
2092
+ func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label(
2093
+ "error_count"
2094
+ ),
2095
+ )
2096
+ .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id))
2097
+ .group_by(table.c.trace_id)
2098
+ )
2099
+ else:
2100
+ # Fallback if spans table doesn't exist
2101
+ return select(table, literal(0).label("total_spans"), literal(0).label("error_count"))
2102
+
2103
+ async def create_trace(self, trace: "Trace") -> None:
2104
+ """Create a single trace record in the database.
2105
+
2106
+ Args:
2107
+ trace: The Trace object to store (one per trace_id).
2108
+ """
2109
+ try:
2110
+ table = await self._get_table(table_type="traces", create_table_if_not_found=True)
2111
+
2112
+ async with self.async_session_factory() as sess, sess.begin():
2113
+ # Check if trace exists
2114
+ result = await sess.execute(select(table).where(table.c.trace_id == trace.trace_id))
2115
+ existing = result.fetchone()
2116
+
2117
+ if existing:
2118
+ # workflow (level 3) > team (level 2) > agent (level 1) > child/unknown (level 0)
2119
+
2120
+ def get_component_level(workflow_id, team_id, agent_id, name):
2121
+ # Check if name indicates a root span
2122
+ is_root_name = ".run" in name or ".arun" in name
2123
+
2124
+ if not is_root_name:
2125
+ return 0 # Child span (not a root)
2126
+ elif workflow_id:
2127
+ return 3 # Workflow root
2128
+ elif team_id:
2129
+ return 2 # Team root
2130
+ elif agent_id:
2131
+ return 1 # Agent root
2132
+ else:
2133
+ return 0 # Unknown
2134
+
2135
+ existing_level = get_component_level(
2136
+ existing.workflow_id, existing.team_id, existing.agent_id, existing.name
2137
+ )
2138
+ new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name)
2139
+
2140
+ # Only update name if new trace is from a higher or equal level
2141
+ should_update_name = new_level > existing_level
2142
+
2143
+ # Parse existing start_time to calculate correct duration
2144
+ existing_start_time_str = existing.start_time
2145
+ if isinstance(existing_start_time_str, str):
2146
+ existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00"))
2147
+ else:
2148
+ existing_start_time = trace.start_time
2149
+
2150
+ recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000)
2151
+
2152
+ update_values = {
2153
+ "end_time": trace.end_time.isoformat(),
2154
+ "duration_ms": recalculated_duration_ms,
2155
+ "status": trace.status,
2156
+ "name": trace.name if should_update_name else existing.name,
2157
+ }
2158
+
2159
+ # Update context fields ONLY if new value is not None (preserve non-null values)
2160
+ if trace.run_id is not None:
2161
+ update_values["run_id"] = trace.run_id
2162
+ if trace.session_id is not None:
2163
+ update_values["session_id"] = trace.session_id
2164
+ if trace.user_id is not None:
2165
+ update_values["user_id"] = trace.user_id
2166
+ if trace.agent_id is not None:
2167
+ update_values["agent_id"] = trace.agent_id
2168
+ if trace.team_id is not None:
2169
+ update_values["team_id"] = trace.team_id
2170
+ if trace.workflow_id is not None:
2171
+ update_values["workflow_id"] = trace.workflow_id
2172
+
2173
+ log_debug(
2174
+ f" Updating trace with context: run_id={update_values.get('run_id', 'unchanged')}, "
2175
+ f"session_id={update_values.get('session_id', 'unchanged')}, "
2176
+ f"user_id={update_values.get('user_id', 'unchanged')}, "
2177
+ f"agent_id={update_values.get('agent_id', 'unchanged')}, "
2178
+ f"team_id={update_values.get('team_id', 'unchanged')}, "
2179
+ )
2180
+
2181
+ stmt = update(table).where(table.c.trace_id == trace.trace_id).values(**update_values)
2182
+ await sess.execute(stmt)
2183
+ else:
2184
+ trace_dict = trace.to_dict()
2185
+ trace_dict.pop("total_spans", None)
2186
+ trace_dict.pop("error_count", None)
2187
+ stmt = postgresql.insert(table).values(trace_dict)
2188
+ await sess.execute(stmt)
2189
+
2190
+ except Exception as e:
2191
+ log_error(f"Error creating trace: {e}")
2192
+ # Don't raise - tracing should not break the main application flow
2193
+
2194
+ async def get_trace(
2195
+ self,
2196
+ trace_id: Optional[str] = None,
2197
+ run_id: Optional[str] = None,
2198
+ ):
2199
+ """Get a single trace by trace_id or other filters.
2200
+
2201
+ Args:
2202
+ trace_id: The unique trace identifier.
2203
+ run_id: Filter by run ID (returns first match).
2204
+
2205
+ Returns:
2206
+ Optional[Trace]: The trace if found, None otherwise.
2207
+
2208
+ Note:
2209
+ If multiple filters are provided, trace_id takes precedence.
2210
+ For other filters, the most recent trace is returned.
2211
+ """
2212
+ try:
2213
+ from agno.tracing.schemas import Trace
2214
+
2215
+ table = await self._get_table(table_type="traces")
2216
+
2217
+ # Get spans table for JOIN
2218
+ spans_table = await self._get_table(table_type="spans")
2219
+
2220
+ async with self.async_session_factory() as sess:
2221
+ # Build query with aggregated span counts
2222
+ stmt = self._get_traces_base_query(table, spans_table)
2223
+
2224
+ if trace_id:
2225
+ stmt = stmt.where(table.c.trace_id == trace_id)
2226
+ elif run_id:
2227
+ stmt = stmt.where(table.c.run_id == run_id)
2228
+ else:
2229
+ log_debug("get_trace called without any filter parameters")
2230
+ return None
2231
+
2232
+ # Order by most recent and get first result
2233
+ stmt = stmt.order_by(table.c.start_time.desc()).limit(1)
2234
+ result = await sess.execute(stmt)
2235
+ row = result.fetchone()
2236
+
2237
+ if row:
2238
+ return Trace.from_dict(dict(row._mapping))
2239
+ return None
2240
+
2241
+ except Exception as e:
2242
+ log_error(f"Error getting trace: {e}")
2243
+ return None
2244
+
2245
+ async def get_traces(
2246
+ self,
2247
+ run_id: Optional[str] = None,
2248
+ session_id: Optional[str] = None,
2249
+ user_id: Optional[str] = None,
2250
+ agent_id: Optional[str] = None,
2251
+ team_id: Optional[str] = None,
2252
+ workflow_id: Optional[str] = None,
2253
+ status: Optional[str] = None,
2254
+ start_time: Optional[datetime] = None,
2255
+ end_time: Optional[datetime] = None,
2256
+ limit: Optional[int] = 20,
2257
+ page: Optional[int] = 1,
2258
+ ) -> tuple[List, int]:
2259
+ """Get traces matching the provided filters with pagination.
2260
+
2261
+ Args:
2262
+ run_id: Filter by run ID.
2263
+ session_id: Filter by session ID.
2264
+ user_id: Filter by user ID.
2265
+ agent_id: Filter by agent ID.
2266
+ team_id: Filter by team ID.
2267
+ workflow_id: Filter by workflow ID.
2268
+ status: Filter by status (OK, ERROR, UNSET).
2269
+ start_time: Filter traces starting after this datetime.
2270
+ end_time: Filter traces ending before this datetime.
2271
+ limit: Maximum number of traces to return per page.
2272
+ page: Page number (1-indexed).
2273
+
2274
+ Returns:
2275
+ tuple[List[Trace], int]: Tuple of (list of matching traces, total count).
2276
+ """
2277
+ try:
2278
+ from agno.tracing.schemas import Trace
2279
+
2280
+ log_debug(
2281
+ f"get_traces called with filters: run_id={run_id}, session_id={session_id}, user_id={user_id}, agent_id={agent_id}, page={page}, limit={limit}"
2282
+ )
2283
+
2284
+ table = await self._get_table(table_type="traces")
2285
+
2286
+ # Get spans table for JOIN
2287
+ spans_table = await self._get_table(table_type="spans")
2288
+
2289
+ async with self.async_session_factory() as sess:
2290
+ # Build base query with aggregated span counts
2291
+ base_stmt = self._get_traces_base_query(table, spans_table)
2292
+
2293
+ # Apply filters
2294
+ if run_id:
2295
+ base_stmt = base_stmt.where(table.c.run_id == run_id)
2296
+ if session_id:
2297
+ log_debug(f"Filtering by session_id={session_id}")
2298
+ base_stmt = base_stmt.where(table.c.session_id == session_id)
2299
+ if user_id:
2300
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2301
+ if agent_id:
2302
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2303
+ if team_id:
2304
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2305
+ if workflow_id:
2306
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2307
+ if status:
2308
+ base_stmt = base_stmt.where(table.c.status == status)
2309
+ if start_time:
2310
+ # Convert datetime to ISO string for comparison
2311
+ base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat())
2312
+ if end_time:
2313
+ # Convert datetime to ISO string for comparison
2314
+ base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat())
2315
+
2316
+ # Get total count
2317
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2318
+ total_count = await sess.scalar(count_stmt) or 0
2319
+ log_debug(f"Total matching traces: {total_count}")
2320
+
2321
+ # Apply pagination
2322
+ offset = (page - 1) * limit if page and limit else 0
2323
+ paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset)
2324
+
2325
+ result = await sess.execute(paginated_stmt)
2326
+ results = result.fetchall()
2327
+ log_debug(f"Returning page {page} with {len(results)} traces")
2328
+
2329
+ traces = [Trace.from_dict(dict(row._mapping)) for row in results]
2330
+ return traces, total_count
2331
+
2332
+ except Exception as e:
2333
+ log_error(f"Error getting traces: {e}")
2334
+ return [], 0
2335
+
2336
+ async def get_trace_stats(
2337
+ self,
2338
+ user_id: Optional[str] = None,
2339
+ agent_id: Optional[str] = None,
2340
+ team_id: Optional[str] = None,
2341
+ workflow_id: Optional[str] = None,
2342
+ start_time: Optional[datetime] = None,
2343
+ end_time: Optional[datetime] = None,
2344
+ limit: Optional[int] = 20,
2345
+ page: Optional[int] = 1,
2346
+ ) -> tuple[List[Dict[str, Any]], int]:
2347
+ """Get trace statistics grouped by session.
2348
+
2349
+ Args:
2350
+ user_id: Filter by user ID.
2351
+ agent_id: Filter by agent ID.
2352
+ team_id: Filter by team ID.
2353
+ workflow_id: Filter by workflow ID.
2354
+ start_time: Filter sessions with traces created after this datetime.
2355
+ end_time: Filter sessions with traces created before this datetime.
2356
+ limit: Maximum number of sessions to return per page.
2357
+ page: Page number (1-indexed).
2358
+
2359
+ Returns:
2360
+ tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count).
2361
+ Each dict contains: session_id, user_id, agent_id, team_id, total_traces,
2362
+ workflow_id, first_trace_at, last_trace_at.
2363
+ """
2364
+ try:
2365
+ log_debug(
2366
+ f"get_trace_stats called with filters: user_id={user_id}, agent_id={agent_id}, "
2367
+ f"workflow_id={workflow_id}, team_id={team_id}, "
2368
+ f"start_time={start_time}, end_time={end_time}, page={page}, limit={limit}"
2369
+ )
2370
+
2371
+ table = await self._get_table(table_type="traces")
2372
+
2373
+ async with self.async_session_factory() as sess:
2374
+ # Build base query grouped by session_id
2375
+ base_stmt = (
2376
+ select(
2377
+ table.c.session_id,
2378
+ table.c.user_id,
2379
+ table.c.agent_id,
2380
+ table.c.team_id,
2381
+ table.c.workflow_id,
2382
+ func.count(table.c.trace_id).label("total_traces"),
2383
+ func.min(table.c.created_at).label("first_trace_at"),
2384
+ func.max(table.c.created_at).label("last_trace_at"),
2385
+ )
2386
+ .where(table.c.session_id.isnot(None)) # Only sessions with session_id
2387
+ .group_by(
2388
+ table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id
2389
+ )
2390
+ )
2391
+
2392
+ # Apply filters
2393
+ if user_id:
2394
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2395
+ if workflow_id:
2396
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2397
+ if team_id:
2398
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2399
+ if agent_id:
2400
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2401
+ if start_time:
2402
+ # Convert datetime to ISO string for comparison
2403
+ base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat())
2404
+ if end_time:
2405
+ # Convert datetime to ISO string for comparison
2406
+ base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat())
2407
+
2408
+ # Get total count of sessions
2409
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2410
+ total_count = await sess.scalar(count_stmt) or 0
2411
+ log_debug(f"Total matching sessions: {total_count}")
2412
+
2413
+ # Apply pagination and ordering
2414
+ offset = (page - 1) * limit if page and limit else 0
2415
+ paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset)
2416
+
2417
+ result = await sess.execute(paginated_stmt)
2418
+ results = result.fetchall()
2419
+ log_debug(f"Returning page {page} with {len(results)} session stats")
2420
+
2421
+ # Convert to list of dicts with datetime objects
2422
+ stats_list = []
2423
+ for row in results:
2424
+ # Convert ISO strings to datetime objects
2425
+ first_trace_at_str = row.first_trace_at
2426
+ last_trace_at_str = row.last_trace_at
2427
+
2428
+ # Parse ISO format strings to datetime objects
2429
+ first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00"))
2430
+ last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00"))
2431
+
2432
+ stats_list.append(
2433
+ {
2434
+ "session_id": row.session_id,
2435
+ "user_id": row.user_id,
2436
+ "agent_id": row.agent_id,
2437
+ "team_id": row.team_id,
2438
+ "workflow_id": row.workflow_id,
2439
+ "total_traces": row.total_traces,
2440
+ "first_trace_at": first_trace_at,
2441
+ "last_trace_at": last_trace_at,
2442
+ }
2443
+ )
2444
+
2445
+ return stats_list, total_count
2446
+
2447
+ except Exception as e:
2448
+ log_error(f"Error getting trace stats: {e}")
2449
+ return [], 0
2450
+
2451
+ # --- Spans ---
2452
+ async def create_span(self, span: "Span") -> None:
2453
+ """Create a single span in the database.
2454
+
2455
+ Args:
2456
+ span: The Span object to store.
2457
+ """
2458
+ try:
2459
+ table = await self._get_table(table_type="spans", create_table_if_not_found=True)
2460
+
2461
+ async with self.async_session_factory() as sess, sess.begin():
2462
+ stmt = postgresql.insert(table).values(span.to_dict())
2463
+ await sess.execute(stmt)
2464
+
2465
+ except Exception as e:
2466
+ log_error(f"Error creating span: {e}")
2467
+
2468
+ async def create_spans(self, spans: List) -> None:
2469
+ """Create multiple spans in the database as a batch.
2470
+
2471
+ Args:
2472
+ spans: List of Span objects to store.
2473
+ """
2474
+ if not spans:
2475
+ return
2476
+
2477
+ try:
2478
+ table = await self._get_table(table_type="spans", create_table_if_not_found=True)
2479
+
2480
+ async with self.async_session_factory() as sess, sess.begin():
2481
+ for span in spans:
2482
+ stmt = postgresql.insert(table).values(span.to_dict())
2483
+ await sess.execute(stmt)
2484
+
2485
+ except Exception as e:
2486
+ log_error(f"Error creating spans batch: {e}")
2487
+
2488
+ async def get_span(self, span_id: str):
2489
+ """Get a single span by its span_id.
2490
+
2491
+ Args:
2492
+ span_id: The unique span identifier.
2493
+
2494
+ Returns:
2495
+ Optional[Span]: The span if found, None otherwise.
2496
+ """
2497
+ try:
2498
+ from agno.tracing.schemas import Span
2499
+
2500
+ table = await self._get_table(table_type="spans")
2501
+
2502
+ async with self.async_session_factory() as sess:
2503
+ stmt = select(table).where(table.c.span_id == span_id)
2504
+ result = await sess.execute(stmt)
2505
+ row = result.fetchone()
2506
+ if row:
2507
+ return Span.from_dict(dict(row._mapping))
2508
+ return None
2509
+
2510
+ except Exception as e:
2511
+ log_error(f"Error getting span: {e}")
2512
+ return None
2513
+
2514
+ async def get_spans(
2515
+ self,
2516
+ trace_id: Optional[str] = None,
2517
+ parent_span_id: Optional[str] = None,
2518
+ limit: Optional[int] = 1000,
2519
+ ) -> List:
2520
+ """Get spans matching the provided filters.
2521
+
2522
+ Args:
2523
+ trace_id: Filter by trace ID.
2524
+ parent_span_id: Filter by parent span ID.
2525
+ limit: Maximum number of spans to return.
2526
+
2527
+ Returns:
2528
+ List[Span]: List of matching spans.
2529
+ """
2530
+ try:
2531
+ from agno.tracing.schemas import Span
2532
+
2533
+ table = await self._get_table(table_type="spans")
2534
+
2535
+ async with self.async_session_factory() as sess:
2536
+ stmt = select(table)
2537
+
2538
+ # Apply filters
2539
+ if trace_id:
2540
+ stmt = stmt.where(table.c.trace_id == trace_id)
2541
+ if parent_span_id:
2542
+ stmt = stmt.where(table.c.parent_span_id == parent_span_id)
2543
+
2544
+ if limit:
2545
+ stmt = stmt.limit(limit)
2546
+
2547
+ result = await sess.execute(stmt)
2548
+ results = result.fetchall()
2549
+ return [Span.from_dict(dict(row._mapping)) for row in results]
2550
+
2551
+ except Exception as e:
2552
+ log_error(f"Error getting spans: {e}")
2553
+ return []