agno 2.3.3__py3-none-any.whl → 2.3.5__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 (108) hide show
  1. agno/agent/agent.py +177 -41
  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 +546 -14
  17. agno/db/postgres/postgres.py +535 -2
  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 +548 -9
  24. agno/db/sqlite/schemas.py +38 -0
  25. agno/db/sqlite/sqlite.py +537 -5
  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 +10 -4
  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/knowledge/chunking/semantic.py +2 -2
  36. agno/models/aimlapi/aimlapi.py +17 -0
  37. agno/models/anthropic/claude.py +19 -12
  38. agno/models/aws/bedrock.py +3 -4
  39. agno/models/aws/claude.py +5 -1
  40. agno/models/azure/ai_foundry.py +2 -2
  41. agno/models/azure/openai_chat.py +8 -0
  42. agno/models/cerebras/cerebras.py +61 -4
  43. agno/models/cerebras/cerebras_openai.py +17 -0
  44. agno/models/cohere/chat.py +5 -1
  45. agno/models/cometapi/cometapi.py +18 -1
  46. agno/models/dashscope/dashscope.py +2 -3
  47. agno/models/deepinfra/deepinfra.py +18 -1
  48. agno/models/deepseek/deepseek.py +2 -3
  49. agno/models/fireworks/fireworks.py +18 -1
  50. agno/models/google/gemini.py +8 -2
  51. agno/models/groq/groq.py +5 -2
  52. agno/models/internlm/internlm.py +18 -1
  53. agno/models/langdb/langdb.py +13 -1
  54. agno/models/litellm/chat.py +2 -2
  55. agno/models/litellm/litellm_openai.py +18 -1
  56. agno/models/meta/llama_openai.py +19 -2
  57. agno/models/nebius/nebius.py +2 -3
  58. agno/models/nvidia/nvidia.py +20 -3
  59. agno/models/openai/chat.py +17 -2
  60. agno/models/openai/responses.py +17 -2
  61. agno/models/openrouter/openrouter.py +21 -2
  62. agno/models/perplexity/perplexity.py +17 -1
  63. agno/models/portkey/portkey.py +7 -6
  64. agno/models/requesty/requesty.py +19 -2
  65. agno/models/response.py +2 -1
  66. agno/models/sambanova/sambanova.py +20 -3
  67. agno/models/siliconflow/siliconflow.py +19 -2
  68. agno/models/together/together.py +20 -3
  69. agno/models/vercel/v0.py +20 -3
  70. agno/models/vllm/vllm.py +19 -14
  71. agno/models/xai/xai.py +19 -2
  72. agno/os/app.py +104 -0
  73. agno/os/config.py +13 -0
  74. agno/os/interfaces/whatsapp/router.py +0 -1
  75. agno/os/mcp.py +1 -0
  76. agno/os/router.py +31 -0
  77. agno/os/routers/traces/__init__.py +3 -0
  78. agno/os/routers/traces/schemas.py +414 -0
  79. agno/os/routers/traces/traces.py +499 -0
  80. agno/os/schema.py +22 -1
  81. agno/os/utils.py +57 -0
  82. agno/run/agent.py +1 -0
  83. agno/run/base.py +17 -0
  84. agno/run/team.py +4 -0
  85. agno/session/team.py +1 -0
  86. agno/table.py +10 -0
  87. agno/team/team.py +215 -65
  88. agno/tools/function.py +10 -8
  89. agno/tools/nano_banana.py +1 -1
  90. agno/tracing/__init__.py +12 -0
  91. agno/tracing/exporter.py +157 -0
  92. agno/tracing/schemas.py +276 -0
  93. agno/tracing/setup.py +111 -0
  94. agno/utils/agent.py +4 -4
  95. agno/utils/hooks.py +56 -1
  96. agno/vectordb/qdrant/qdrant.py +22 -22
  97. agno/workflow/condition.py +8 -0
  98. agno/workflow/loop.py +8 -0
  99. agno/workflow/parallel.py +8 -0
  100. agno/workflow/router.py +8 -0
  101. agno/workflow/step.py +20 -0
  102. agno/workflow/steps.py +8 -0
  103. agno/workflow/workflow.py +83 -17
  104. {agno-2.3.3.dist-info → agno-2.3.5.dist-info}/METADATA +2 -2
  105. {agno-2.3.3.dist-info → agno-2.3.5.dist-info}/RECORD +108 -98
  106. {agno-2.3.3.dist-info → agno-2.3.5.dist-info}/WHEEL +0 -0
  107. {agno-2.3.3.dist-info → agno-2.3.5.dist-info}/licenses/LICENSE +0 -0
  108. {agno-2.3.3.dist-info → agno-2.3.5.dist-info}/top_level.txt +0 -0
@@ -1,8 +1,11 @@
1
1
  import time
2
2
  from datetime import date, datetime, timedelta, timezone
3
- from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
3
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
4
4
  from uuid import uuid4
5
5
 
6
+ if TYPE_CHECKING:
7
+ from agno.tracing.schemas import Span, Trace
8
+
6
9
  from agno.db.base import BaseDb, SessionType
7
10
  from agno.db.migrations.manager import MigrationManager
8
11
  from agno.db.postgres.schemas import get_table_schema_definition
@@ -27,7 +30,7 @@ from agno.utils.log import log_debug, log_error, log_info, log_warning
27
30
  from agno.utils.string import generate_id
28
31
 
29
32
  try:
30
- from sqlalchemy import Index, String, UniqueConstraint, func, select, update
33
+ from sqlalchemy import ForeignKey, Index, String, UniqueConstraint, func, select, update
31
34
  from sqlalchemy.dialects import postgresql
32
35
  from sqlalchemy.engine import Engine, create_engine
33
36
  from sqlalchemy.orm import scoped_session, sessionmaker
@@ -49,6 +52,8 @@ class PostgresDb(BaseDb):
49
52
  metrics_table: Optional[str] = None,
50
53
  eval_table: Optional[str] = None,
51
54
  knowledge_table: Optional[str] = None,
55
+ traces_table: Optional[str] = None,
56
+ spans_table: Optional[str] = None,
52
57
  versions_table: Optional[str] = None,
53
58
  id: Optional[str] = None,
54
59
  ):
@@ -70,6 +75,8 @@ class PostgresDb(BaseDb):
70
75
  eval_table (Optional[str]): Name of the table to store evaluation runs data.
71
76
  knowledge_table (Optional[str]): Name of the table to store knowledge content.
72
77
  culture_table (Optional[str]): Name of the table to store cultural knowledge.
78
+ traces_table (Optional[str]): Name of the table to store run traces.
79
+ spans_table (Optional[str]): Name of the table to store span events.
73
80
  versions_table (Optional[str]): Name of the table to store schema versions.
74
81
  id (Optional[str]): ID of the database.
75
82
 
@@ -100,6 +107,8 @@ class PostgresDb(BaseDb):
100
107
  eval_table=eval_table,
101
108
  knowledge_table=knowledge_table,
102
109
  culture_table=culture_table,
110
+ traces_table=traces_table,
111
+ spans_table=spans_table,
103
112
  versions_table=versions_table,
104
113
  )
105
114
 
@@ -168,6 +177,16 @@ class PostgresDb(BaseDb):
168
177
  if col_config.get("unique", False):
169
178
  column_kwargs["unique"] = True
170
179
  unique_constraints.append(col_name)
180
+
181
+ # Handle foreign key constraint
182
+ if "foreign_key" in col_config:
183
+ fk_ref = col_config["foreign_key"]
184
+ # For spans table, dynamically replace the traces table reference
185
+ # with the actual trace table name configured for this db instance
186
+ if table_type == "spans" and "trace_id" in fk_ref:
187
+ fk_ref = f"{self.db_schema}.{self.trace_table_name}.trace_id"
188
+ column_args.append(ForeignKey(fk_ref))
189
+
171
190
  columns.append(Column(*column_args, **column_kwargs)) # type: ignore
172
191
 
173
192
  # Create the table object
@@ -287,6 +306,26 @@ class PostgresDb(BaseDb):
287
306
  )
288
307
  return self.versions_table
289
308
 
309
+ if table_type == "traces":
310
+ self.traces_table = self._get_or_create_table(
311
+ table_name=self.trace_table_name,
312
+ table_type="traces",
313
+ create_table_if_not_found=create_table_if_not_found,
314
+ )
315
+ return self.traces_table
316
+
317
+ if table_type == "spans":
318
+ # Ensure traces table exists first (spans has FK to traces)
319
+ if create_table_if_not_found:
320
+ self._get_table(table_type="traces", create_table_if_not_found=True)
321
+
322
+ self.spans_table = self._get_or_create_table(
323
+ table_name=self.span_table_name,
324
+ table_type="spans",
325
+ create_table_if_not_found=create_table_if_not_found,
326
+ )
327
+ return self.spans_table
328
+
290
329
  raise ValueError(f"Unknown table type: {table_type}")
291
330
 
292
331
  def _get_or_create_table(
@@ -2319,3 +2358,497 @@ class PostgresDb(BaseDb):
2319
2358
  for memory in memories:
2320
2359
  self.upsert_user_memory(memory)
2321
2360
  log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}")
2361
+
2362
+ # --- Traces ---
2363
+ def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None):
2364
+ """Build base query for traces with aggregated span counts.
2365
+
2366
+ Args:
2367
+ table: The traces table.
2368
+ spans_table: The spans table (optional).
2369
+
2370
+ Returns:
2371
+ SQLAlchemy select statement with total_spans and error_count calculated dynamically.
2372
+ """
2373
+ from sqlalchemy import case, literal
2374
+
2375
+ if spans_table is not None:
2376
+ # JOIN with spans table to calculate total_spans and error_count
2377
+ return (
2378
+ select(
2379
+ table,
2380
+ func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"),
2381
+ func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label(
2382
+ "error_count"
2383
+ ),
2384
+ )
2385
+ .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id))
2386
+ .group_by(table.c.trace_id)
2387
+ )
2388
+ else:
2389
+ # Fallback if spans table doesn't exist
2390
+ return select(table, literal(0).label("total_spans"), literal(0).label("error_count"))
2391
+
2392
+ def create_trace(self, trace: "Trace") -> None:
2393
+ """Create a single trace record in the database.
2394
+
2395
+ Args:
2396
+ trace: The Trace object to store (one per trace_id).
2397
+ """
2398
+ try:
2399
+ table = self._get_table(table_type="traces", create_table_if_not_found=True)
2400
+ if table is None:
2401
+ return
2402
+
2403
+ with self.Session() as sess, sess.begin():
2404
+ # Check if trace exists
2405
+ existing = sess.execute(select(table).where(table.c.trace_id == trace.trace_id)).fetchone()
2406
+
2407
+ if existing:
2408
+ # workflow (level 3) > team (level 2) > agent (level 1) > child/unknown (level 0)
2409
+
2410
+ def get_component_level(workflow_id, team_id, agent_id, name):
2411
+ # Check if name indicates a root span
2412
+ is_root_name = ".run" in name or ".arun" in name
2413
+
2414
+ if not is_root_name:
2415
+ return 0 # Child span (not a root)
2416
+ elif workflow_id:
2417
+ return 3 # Workflow root
2418
+ elif team_id:
2419
+ return 2 # Team root
2420
+ elif agent_id:
2421
+ return 1 # Agent root
2422
+ else:
2423
+ return 0 # Unknown
2424
+
2425
+ existing_level = get_component_level(
2426
+ existing.workflow_id, existing.team_id, existing.agent_id, existing.name
2427
+ )
2428
+ new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name)
2429
+
2430
+ # Only update name if new trace is from a higher or equal level
2431
+ should_update_name = new_level > existing_level
2432
+
2433
+ # Parse existing start_time to calculate correct duration
2434
+ existing_start_time_str = existing.start_time
2435
+ if isinstance(existing_start_time_str, str):
2436
+ existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00"))
2437
+ else:
2438
+ existing_start_time = trace.start_time
2439
+
2440
+ recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000)
2441
+
2442
+ update_values = {
2443
+ "end_time": trace.end_time.isoformat(),
2444
+ "duration_ms": recalculated_duration_ms,
2445
+ "status": trace.status,
2446
+ "name": trace.name if should_update_name else existing.name,
2447
+ }
2448
+
2449
+ # Update context fields ONLY if new value is not None (preserve non-null values)
2450
+ if trace.run_id is not None:
2451
+ update_values["run_id"] = trace.run_id
2452
+ if trace.session_id is not None:
2453
+ update_values["session_id"] = trace.session_id
2454
+ if trace.user_id is not None:
2455
+ update_values["user_id"] = trace.user_id
2456
+ if trace.agent_id is not None:
2457
+ update_values["agent_id"] = trace.agent_id
2458
+ if trace.team_id is not None:
2459
+ update_values["team_id"] = trace.team_id
2460
+ if trace.workflow_id is not None:
2461
+ update_values["workflow_id"] = trace.workflow_id
2462
+
2463
+ log_debug(
2464
+ f" Updating trace with context: run_id={update_values.get('run_id', 'unchanged')}, "
2465
+ f"session_id={update_values.get('session_id', 'unchanged')}, "
2466
+ f"user_id={update_values.get('user_id', 'unchanged')}, "
2467
+ f"agent_id={update_values.get('agent_id', 'unchanged')}, "
2468
+ f"team_id={update_values.get('team_id', 'unchanged')}, "
2469
+ )
2470
+
2471
+ stmt = update(table).where(table.c.trace_id == trace.trace_id).values(**update_values)
2472
+ sess.execute(stmt)
2473
+ else:
2474
+ trace_dict = trace.to_dict()
2475
+ trace_dict.pop("total_spans", None)
2476
+ trace_dict.pop("error_count", None)
2477
+ stmt = postgresql.insert(table).values(trace_dict)
2478
+ sess.execute(stmt)
2479
+
2480
+ except Exception as e:
2481
+ log_error(f"Error creating trace: {e}")
2482
+ # Don't raise - tracing should not break the main application flow
2483
+
2484
+ def get_trace(
2485
+ self,
2486
+ trace_id: Optional[str] = None,
2487
+ run_id: Optional[str] = None,
2488
+ ):
2489
+ """Get a single trace by trace_id or other filters.
2490
+
2491
+ Args:
2492
+ trace_id: The unique trace identifier.
2493
+ run_id: Filter by run ID (returns first match).
2494
+
2495
+ Returns:
2496
+ Optional[Trace]: The trace if found, None otherwise.
2497
+
2498
+ Note:
2499
+ If multiple filters are provided, trace_id takes precedence.
2500
+ For other filters, the most recent trace is returned.
2501
+ """
2502
+ try:
2503
+ from agno.tracing.schemas import Trace
2504
+
2505
+ table = self._get_table(table_type="traces")
2506
+ if table is None:
2507
+ return None
2508
+
2509
+ # Get spans table for JOIN
2510
+ spans_table = self._get_table(table_type="spans")
2511
+
2512
+ with self.Session() as sess:
2513
+ # Build query with aggregated span counts
2514
+ stmt = self._get_traces_base_query(table, spans_table)
2515
+
2516
+ if trace_id:
2517
+ stmt = stmt.where(table.c.trace_id == trace_id)
2518
+ elif run_id:
2519
+ stmt = stmt.where(table.c.run_id == run_id)
2520
+ else:
2521
+ log_debug("get_trace called without any filter parameters")
2522
+ return None
2523
+
2524
+ # Order by most recent and get first result
2525
+ stmt = stmt.order_by(table.c.start_time.desc()).limit(1)
2526
+ result = sess.execute(stmt).fetchone()
2527
+
2528
+ if result:
2529
+ return Trace.from_dict(dict(result._mapping))
2530
+ return None
2531
+
2532
+ except Exception as e:
2533
+ log_error(f"Error getting trace: {e}")
2534
+ return None
2535
+
2536
+ def get_traces(
2537
+ self,
2538
+ run_id: Optional[str] = None,
2539
+ session_id: Optional[str] = None,
2540
+ user_id: Optional[str] = None,
2541
+ agent_id: Optional[str] = None,
2542
+ team_id: Optional[str] = None,
2543
+ workflow_id: Optional[str] = None,
2544
+ status: Optional[str] = None,
2545
+ start_time: Optional[datetime] = None,
2546
+ end_time: Optional[datetime] = None,
2547
+ limit: Optional[int] = 20,
2548
+ page: Optional[int] = 1,
2549
+ ) -> tuple[List, int]:
2550
+ """Get traces matching the provided filters with pagination.
2551
+
2552
+ Args:
2553
+ run_id: Filter by run ID.
2554
+ session_id: Filter by session ID.
2555
+ user_id: Filter by user ID.
2556
+ agent_id: Filter by agent ID.
2557
+ team_id: Filter by team ID.
2558
+ workflow_id: Filter by workflow ID.
2559
+ status: Filter by status (OK, ERROR, UNSET).
2560
+ start_time: Filter traces starting after this datetime.
2561
+ end_time: Filter traces ending before this datetime.
2562
+ limit: Maximum number of traces to return per page.
2563
+ page: Page number (1-indexed).
2564
+
2565
+ Returns:
2566
+ tuple[List[Trace], int]: Tuple of (list of matching traces, total count).
2567
+ """
2568
+ try:
2569
+ from agno.tracing.schemas import Trace
2570
+
2571
+ log_debug(
2572
+ 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}"
2573
+ )
2574
+
2575
+ table = self._get_table(table_type="traces")
2576
+ if table is None:
2577
+ log_debug("Traces table not found")
2578
+ return [], 0
2579
+
2580
+ # Get spans table for JOIN
2581
+ spans_table = self._get_table(table_type="spans")
2582
+
2583
+ with self.Session() as sess:
2584
+ # Build base query with aggregated span counts
2585
+ base_stmt = self._get_traces_base_query(table, spans_table)
2586
+
2587
+ # Apply filters
2588
+ if run_id:
2589
+ base_stmt = base_stmt.where(table.c.run_id == run_id)
2590
+ if session_id:
2591
+ log_debug(f"Filtering by session_id={session_id}")
2592
+ base_stmt = base_stmt.where(table.c.session_id == session_id)
2593
+ if user_id:
2594
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2595
+ if agent_id:
2596
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2597
+ if team_id:
2598
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2599
+ if workflow_id:
2600
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2601
+ if status:
2602
+ base_stmt = base_stmt.where(table.c.status == status)
2603
+ if start_time:
2604
+ # Convert datetime to ISO string for comparison
2605
+ base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat())
2606
+ if end_time:
2607
+ # Convert datetime to ISO string for comparison
2608
+ base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat())
2609
+
2610
+ # Get total count
2611
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2612
+ total_count = sess.execute(count_stmt).scalar() or 0
2613
+ log_debug(f"Total matching traces: {total_count}")
2614
+
2615
+ # Apply pagination
2616
+ offset = (page - 1) * limit if page and limit else 0
2617
+ paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset)
2618
+
2619
+ results = sess.execute(paginated_stmt).fetchall()
2620
+ log_debug(f"Returning page {page} with {len(results)} traces")
2621
+
2622
+ traces = [Trace.from_dict(dict(row._mapping)) for row in results]
2623
+ return traces, total_count
2624
+
2625
+ except Exception as e:
2626
+ log_error(f"Error getting traces: {e}")
2627
+ return [], 0
2628
+
2629
+ def get_trace_stats(
2630
+ self,
2631
+ user_id: Optional[str] = None,
2632
+ agent_id: Optional[str] = None,
2633
+ team_id: Optional[str] = None,
2634
+ workflow_id: Optional[str] = None,
2635
+ start_time: Optional[datetime] = None,
2636
+ end_time: Optional[datetime] = None,
2637
+ limit: Optional[int] = 20,
2638
+ page: Optional[int] = 1,
2639
+ ) -> tuple[List[Dict[str, Any]], int]:
2640
+ """Get trace statistics grouped by session.
2641
+
2642
+ Args:
2643
+ user_id: Filter by user ID.
2644
+ agent_id: Filter by agent ID.
2645
+ team_id: Filter by team ID.
2646
+ workflow_id: Filter by workflow ID.
2647
+ start_time: Filter sessions with traces created after this datetime.
2648
+ end_time: Filter sessions with traces created before this datetime.
2649
+ limit: Maximum number of sessions to return per page.
2650
+ page: Page number (1-indexed).
2651
+
2652
+ Returns:
2653
+ tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count).
2654
+ Each dict contains: session_id, user_id, agent_id, team_id, total_traces,
2655
+ first_trace_at, last_trace_at.
2656
+ """
2657
+ try:
2658
+ log_debug(
2659
+ f"get_trace_stats called with filters: user_id={user_id}, agent_id={agent_id}, "
2660
+ f"workflow_id={workflow_id}, team_id={team_id}, "
2661
+ f"start_time={start_time}, end_time={end_time}, page={page}, limit={limit}"
2662
+ )
2663
+
2664
+ table = self._get_table(table_type="traces")
2665
+ if table is None:
2666
+ log_debug("Traces table not found")
2667
+ return [], 0
2668
+
2669
+ with self.Session() as sess:
2670
+ # Build base query grouped by session_id
2671
+ base_stmt = (
2672
+ select(
2673
+ table.c.session_id,
2674
+ table.c.user_id,
2675
+ table.c.agent_id,
2676
+ table.c.team_id,
2677
+ table.c.workflow_id,
2678
+ func.count(table.c.trace_id).label("total_traces"),
2679
+ func.min(table.c.created_at).label("first_trace_at"),
2680
+ func.max(table.c.created_at).label("last_trace_at"),
2681
+ )
2682
+ .where(table.c.session_id.isnot(None)) # Only sessions with session_id
2683
+ .group_by(
2684
+ table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id
2685
+ )
2686
+ )
2687
+
2688
+ # Apply filters
2689
+ if user_id:
2690
+ base_stmt = base_stmt.where(table.c.user_id == user_id)
2691
+ if workflow_id:
2692
+ base_stmt = base_stmt.where(table.c.workflow_id == workflow_id)
2693
+ if team_id:
2694
+ base_stmt = base_stmt.where(table.c.team_id == team_id)
2695
+ if agent_id:
2696
+ base_stmt = base_stmt.where(table.c.agent_id == agent_id)
2697
+ if start_time:
2698
+ # Convert datetime to ISO string for comparison
2699
+ base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat())
2700
+ if end_time:
2701
+ # Convert datetime to ISO string for comparison
2702
+ base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat())
2703
+
2704
+ # Get total count of sessions
2705
+ count_stmt = select(func.count()).select_from(base_stmt.alias())
2706
+ total_count = sess.execute(count_stmt).scalar() or 0
2707
+ log_debug(f"Total matching sessions: {total_count}")
2708
+
2709
+ # Apply pagination and ordering
2710
+ offset = (page - 1) * limit if page and limit else 0
2711
+ paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset)
2712
+
2713
+ results = sess.execute(paginated_stmt).fetchall()
2714
+ log_debug(f"Returning page {page} with {len(results)} session stats")
2715
+
2716
+ # Convert to list of dicts with datetime objects
2717
+ stats_list = []
2718
+ for row in results:
2719
+ # Convert ISO strings to datetime objects
2720
+ first_trace_at_str = row.first_trace_at
2721
+ last_trace_at_str = row.last_trace_at
2722
+
2723
+ # Parse ISO format strings to datetime objects
2724
+ first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00"))
2725
+ last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00"))
2726
+
2727
+ stats_list.append(
2728
+ {
2729
+ "session_id": row.session_id,
2730
+ "user_id": row.user_id,
2731
+ "agent_id": row.agent_id,
2732
+ "team_id": row.team_id,
2733
+ "workflow_id": row.workflow_id,
2734
+ "total_traces": row.total_traces,
2735
+ "first_trace_at": first_trace_at,
2736
+ "last_trace_at": last_trace_at,
2737
+ }
2738
+ )
2739
+
2740
+ return stats_list, total_count
2741
+
2742
+ except Exception as e:
2743
+ log_error(f"Error getting trace stats: {e}")
2744
+ return [], 0
2745
+
2746
+ # --- Spans ---
2747
+ def create_span(self, span: "Span") -> None:
2748
+ """Create a single span in the database.
2749
+
2750
+ Args:
2751
+ span: The Span object to store.
2752
+ """
2753
+ try:
2754
+ table = self._get_table(table_type="spans", create_table_if_not_found=True)
2755
+ if table is None:
2756
+ return
2757
+
2758
+ with self.Session() as sess, sess.begin():
2759
+ stmt = postgresql.insert(table).values(span.to_dict())
2760
+ sess.execute(stmt)
2761
+
2762
+ except Exception as e:
2763
+ log_error(f"Error creating span: {e}")
2764
+
2765
+ def create_spans(self, spans: List) -> None:
2766
+ """Create multiple spans in the database as a batch.
2767
+
2768
+ Args:
2769
+ spans: List of Span objects to store.
2770
+ """
2771
+ if not spans:
2772
+ return
2773
+
2774
+ try:
2775
+ table = self._get_table(table_type="spans", create_table_if_not_found=True)
2776
+ if table is None:
2777
+ return
2778
+
2779
+ with self.Session() as sess, sess.begin():
2780
+ for span in spans:
2781
+ stmt = postgresql.insert(table).values(span.to_dict())
2782
+ sess.execute(stmt)
2783
+
2784
+ except Exception as e:
2785
+ log_error(f"Error creating spans batch: {e}")
2786
+
2787
+ def get_span(self, span_id: str):
2788
+ """Get a single span by its span_id.
2789
+
2790
+ Args:
2791
+ span_id: The unique span identifier.
2792
+
2793
+ Returns:
2794
+ Optional[Span]: The span if found, None otherwise.
2795
+ """
2796
+ try:
2797
+ from agno.tracing.schemas import Span
2798
+
2799
+ table = self._get_table(table_type="spans")
2800
+ if table is None:
2801
+ return None
2802
+
2803
+ with self.Session() as sess:
2804
+ stmt = select(table).where(table.c.span_id == span_id)
2805
+ result = sess.execute(stmt).fetchone()
2806
+ if result:
2807
+ return Span.from_dict(dict(result._mapping))
2808
+ return None
2809
+
2810
+ except Exception as e:
2811
+ log_error(f"Error getting span: {e}")
2812
+ return None
2813
+
2814
+ def get_spans(
2815
+ self,
2816
+ trace_id: Optional[str] = None,
2817
+ parent_span_id: Optional[str] = None,
2818
+ limit: Optional[int] = 1000,
2819
+ ) -> List:
2820
+ """Get spans matching the provided filters.
2821
+
2822
+ Args:
2823
+ trace_id: Filter by trace ID.
2824
+ parent_span_id: Filter by parent span ID.
2825
+ limit: Maximum number of spans to return.
2826
+
2827
+ Returns:
2828
+ List[Span]: List of matching spans.
2829
+ """
2830
+ try:
2831
+ from agno.tracing.schemas import Span
2832
+
2833
+ table = self._get_table(table_type="spans")
2834
+ if table is None:
2835
+ return []
2836
+
2837
+ with self.Session() as sess:
2838
+ stmt = select(table)
2839
+
2840
+ # Apply filters
2841
+ if trace_id:
2842
+ stmt = stmt.where(table.c.trace_id == trace_id)
2843
+ if parent_span_id:
2844
+ stmt = stmt.where(table.c.parent_span_id == parent_span_id)
2845
+
2846
+ if limit:
2847
+ stmt = stmt.limit(limit)
2848
+
2849
+ results = sess.execute(stmt).fetchall()
2850
+ return [Span.from_dict(dict(row._mapping)) for row in results]
2851
+
2852
+ except Exception as e:
2853
+ log_error(f"Error getting spans: {e}")
2854
+ return []
@@ -121,6 +121,42 @@ VERSIONS_TABLE_SCHEMA = {
121
121
  "updated_at": {"type": String, "nullable": True},
122
122
  }
123
123
 
124
+ TRACE_TABLE_SCHEMA = {
125
+ "trace_id": {"type": String, "primary_key": True, "nullable": False},
126
+ "name": {"type": String, "nullable": False},
127
+ "status": {"type": String, "nullable": False, "index": True},
128
+ "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string
129
+ "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string
130
+ "duration_ms": {"type": BigInteger, "nullable": False},
131
+ "run_id": {"type": String, "nullable": True, "index": True},
132
+ "session_id": {"type": String, "nullable": True, "index": True},
133
+ "user_id": {"type": String, "nullable": True, "index": True},
134
+ "agent_id": {"type": String, "nullable": True, "index": True},
135
+ "team_id": {"type": String, "nullable": True, "index": True},
136
+ "workflow_id": {"type": String, "nullable": True, "index": True},
137
+ "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string
138
+ }
139
+
140
+ SPAN_TABLE_SCHEMA = {
141
+ "span_id": {"type": String, "primary_key": True, "nullable": False},
142
+ "trace_id": {
143
+ "type": String,
144
+ "nullable": False,
145
+ "index": True,
146
+ "foreign_key": "agno_traces.trace_id", # Foreign key to traces table
147
+ },
148
+ "parent_span_id": {"type": String, "nullable": True, "index": True},
149
+ "name": {"type": String, "nullable": False},
150
+ "span_kind": {"type": String, "nullable": False},
151
+ "status_code": {"type": String, "nullable": False},
152
+ "status_message": {"type": Text, "nullable": True},
153
+ "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string
154
+ "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string
155
+ "duration_ms": {"type": BigInteger, "nullable": False},
156
+ "attributes": {"type": JSONB, "nullable": True},
157
+ "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string
158
+ }
159
+
124
160
 
125
161
  def get_table_schema_definition(table_type: str) -> dict[str, Any]:
126
162
  """
@@ -140,6 +176,8 @@ def get_table_schema_definition(table_type: str) -> dict[str, Any]:
140
176
  "knowledge": KNOWLEDGE_TABLE_SCHEMA,
141
177
  "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA,
142
178
  "versions": VERSIONS_TABLE_SCHEMA,
179
+ "traces": TRACE_TABLE_SCHEMA,
180
+ "spans": SPAN_TABLE_SCHEMA,
143
181
  }
144
182
 
145
183
  schema = schemas.get(table_type, {})