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.
- agno/agent/agent.py +184 -45
- agno/culture/manager.py +2 -2
- agno/db/base.py +330 -8
- agno/db/dynamo/dynamo.py +722 -2
- agno/db/dynamo/schemas.py +127 -0
- agno/db/firestore/firestore.py +573 -1
- agno/db/firestore/schemas.py +40 -0
- agno/db/gcs_json/gcs_json_db.py +446 -1
- agno/db/in_memory/in_memory_db.py +143 -1
- agno/db/json/json_db.py +438 -1
- agno/db/mongo/async_mongo.py +522 -0
- agno/db/mongo/mongo.py +523 -1
- agno/db/mongo/schemas.py +29 -0
- agno/db/mysql/mysql.py +536 -3
- agno/db/mysql/schemas.py +38 -0
- agno/db/postgres/async_postgres.py +553 -15
- agno/db/postgres/postgres.py +544 -5
- agno/db/postgres/schemas.py +38 -0
- agno/db/redis/redis.py +468 -1
- agno/db/redis/schemas.py +32 -0
- agno/db/singlestore/schemas.py +38 -0
- agno/db/singlestore/singlestore.py +523 -1
- agno/db/sqlite/async_sqlite.py +549 -10
- agno/db/sqlite/schemas.py +38 -0
- agno/db/sqlite/sqlite.py +540 -9
- agno/db/sqlite/utils.py +6 -8
- agno/db/surrealdb/models.py +25 -0
- agno/db/surrealdb/surrealdb.py +548 -1
- agno/eval/accuracy.py +18 -8
- agno/eval/performance.py +10 -4
- agno/eval/reliability.py +22 -13
- agno/exceptions.py +11 -0
- agno/hooks/__init__.py +3 -0
- agno/hooks/decorator.py +164 -0
- agno/integrations/discord/client.py +1 -1
- agno/knowledge/chunking/semantic.py +2 -2
- agno/models/aimlapi/aimlapi.py +2 -3
- agno/models/anthropic/claude.py +18 -13
- agno/models/aws/bedrock.py +3 -4
- agno/models/aws/claude.py +5 -1
- agno/models/azure/ai_foundry.py +2 -2
- agno/models/azure/openai_chat.py +8 -0
- agno/models/cerebras/cerebras.py +62 -11
- agno/models/cerebras/cerebras_openai.py +2 -3
- agno/models/cohere/chat.py +1 -5
- agno/models/cometapi/cometapi.py +2 -3
- agno/models/dashscope/dashscope.py +2 -3
- agno/models/deepinfra/deepinfra.py +2 -3
- agno/models/deepseek/deepseek.py +2 -3
- agno/models/fireworks/fireworks.py +2 -3
- agno/models/google/gemini.py +9 -7
- agno/models/groq/groq.py +2 -3
- agno/models/huggingface/huggingface.py +1 -5
- agno/models/ibm/watsonx.py +1 -5
- agno/models/internlm/internlm.py +2 -3
- agno/models/langdb/langdb.py +6 -4
- agno/models/litellm/chat.py +2 -2
- agno/models/litellm/litellm_openai.py +2 -3
- agno/models/meta/llama.py +1 -5
- agno/models/meta/llama_openai.py +4 -5
- agno/models/mistral/mistral.py +1 -5
- agno/models/nebius/nebius.py +2 -3
- agno/models/nvidia/nvidia.py +4 -5
- agno/models/openai/chat.py +14 -3
- agno/models/openai/responses.py +14 -3
- agno/models/openrouter/openrouter.py +4 -5
- agno/models/perplexity/perplexity.py +2 -3
- agno/models/portkey/portkey.py +7 -6
- agno/models/requesty/requesty.py +4 -5
- agno/models/response.py +2 -1
- agno/models/sambanova/sambanova.py +4 -5
- agno/models/siliconflow/siliconflow.py +3 -4
- agno/models/together/together.py +4 -5
- agno/models/vercel/v0.py +4 -5
- agno/models/vllm/vllm.py +19 -14
- agno/models/xai/xai.py +4 -5
- agno/os/app.py +104 -0
- agno/os/config.py +13 -0
- agno/os/interfaces/whatsapp/router.py +0 -1
- agno/os/interfaces/whatsapp/security.py +3 -1
- agno/os/mcp.py +1 -0
- agno/os/router.py +31 -0
- agno/os/routers/traces/__init__.py +3 -0
- agno/os/routers/traces/schemas.py +414 -0
- agno/os/routers/traces/traces.py +499 -0
- agno/os/schema.py +12 -2
- agno/os/utils.py +57 -0
- agno/run/agent.py +1 -0
- agno/run/base.py +17 -0
- agno/run/team.py +4 -0
- agno/table.py +10 -0
- agno/team/team.py +221 -69
- agno/tools/function.py +10 -8
- agno/tools/google_drive.py +4 -3
- agno/tools/nano_banana.py +1 -1
- agno/tools/spotify.py +922 -0
- agno/tracing/__init__.py +12 -0
- agno/tracing/exporter.py +157 -0
- agno/tracing/schemas.py +276 -0
- agno/tracing/setup.py +111 -0
- agno/utils/agent.py +6 -6
- agno/utils/hooks.py +56 -1
- agno/utils/mcp.py +1 -1
- agno/vectordb/qdrant/qdrant.py +22 -22
- agno/workflow/condition.py +8 -0
- agno/workflow/loop.py +8 -0
- agno/workflow/parallel.py +8 -0
- agno/workflow/router.py +8 -0
- agno/workflow/step.py +20 -0
- agno/workflow/steps.py +8 -0
- agno/workflow/workflow.py +88 -19
- {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/METADATA +38 -33
- {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/RECORD +116 -105
- {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/WHEEL +0 -0
- {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/licenses/LICENSE +0 -0
- {agno-2.3.4.dist-info → agno-2.3.6.dist-info}/top_level.txt +0 -0
agno/db/firestore/firestore.py
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import json
|
|
1
2
|
import time
|
|
2
3
|
from datetime import date, datetime, timedelta, timezone
|
|
3
|
-
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
|
|
4
5
|
from uuid import uuid4
|
|
5
6
|
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from agno.tracing.schemas import Span, Trace
|
|
9
|
+
|
|
6
10
|
from agno.db.base import BaseDb, SessionType
|
|
7
11
|
from agno.db.firestore.utils import (
|
|
8
12
|
apply_pagination,
|
|
@@ -45,6 +49,8 @@ class FirestoreDb(BaseDb):
|
|
|
45
49
|
eval_collection: Optional[str] = None,
|
|
46
50
|
knowledge_collection: Optional[str] = None,
|
|
47
51
|
culture_collection: Optional[str] = None,
|
|
52
|
+
traces_collection: Optional[str] = None,
|
|
53
|
+
spans_collection: Optional[str] = None,
|
|
48
54
|
id: Optional[str] = None,
|
|
49
55
|
):
|
|
50
56
|
"""
|
|
@@ -59,6 +65,8 @@ class FirestoreDb(BaseDb):
|
|
|
59
65
|
eval_collection (Optional[str]): Name of the collection to store evaluation runs.
|
|
60
66
|
knowledge_collection (Optional[str]): Name of the collection to store knowledge documents.
|
|
61
67
|
culture_collection (Optional[str]): Name of the collection to store cultural knowledge.
|
|
68
|
+
traces_collection (Optional[str]): Name of the collection to store traces.
|
|
69
|
+
spans_collection (Optional[str]): Name of the collection to store spans.
|
|
62
70
|
id (Optional[str]): ID of the database.
|
|
63
71
|
|
|
64
72
|
Raises:
|
|
@@ -76,6 +84,8 @@ class FirestoreDb(BaseDb):
|
|
|
76
84
|
eval_table=eval_collection,
|
|
77
85
|
knowledge_table=knowledge_collection,
|
|
78
86
|
culture_table=culture_collection,
|
|
87
|
+
traces_table=traces_collection,
|
|
88
|
+
spans_table=spans_collection,
|
|
79
89
|
)
|
|
80
90
|
|
|
81
91
|
_client: Optional[Client] = db_client
|
|
@@ -176,6 +186,30 @@ class FirestoreDb(BaseDb):
|
|
|
176
186
|
)
|
|
177
187
|
return self.culture_collection
|
|
178
188
|
|
|
189
|
+
if table_type == "traces":
|
|
190
|
+
if not hasattr(self, "traces_collection"):
|
|
191
|
+
if self.trace_table_name is None:
|
|
192
|
+
raise ValueError("Traces collection was not provided on initialization")
|
|
193
|
+
self.traces_collection = self._get_or_create_collection(
|
|
194
|
+
collection_name=self.trace_table_name,
|
|
195
|
+
collection_type="traces",
|
|
196
|
+
create_collection_if_not_found=create_collection_if_not_found,
|
|
197
|
+
)
|
|
198
|
+
return self.traces_collection
|
|
199
|
+
|
|
200
|
+
if table_type == "spans":
|
|
201
|
+
# Ensure traces collection exists first (spans reference traces)
|
|
202
|
+
self._get_collection("traces", create_collection_if_not_found=create_collection_if_not_found)
|
|
203
|
+
if not hasattr(self, "spans_collection"):
|
|
204
|
+
if self.span_table_name is None:
|
|
205
|
+
raise ValueError("Spans collection was not provided on initialization")
|
|
206
|
+
self.spans_collection = self._get_or_create_collection(
|
|
207
|
+
collection_name=self.span_table_name,
|
|
208
|
+
collection_type="spans",
|
|
209
|
+
create_collection_if_not_found=create_collection_if_not_found,
|
|
210
|
+
)
|
|
211
|
+
return self.spans_collection
|
|
212
|
+
|
|
179
213
|
raise ValueError(f"Unknown table type: {table_type}")
|
|
180
214
|
|
|
181
215
|
def _get_or_create_collection(
|
|
@@ -1805,3 +1839,541 @@ class FirestoreDb(BaseDb):
|
|
|
1805
1839
|
except Exception as e:
|
|
1806
1840
|
log_error(f"Error updating eval run name {eval_run_id}: {e}")
|
|
1807
1841
|
raise e
|
|
1842
|
+
|
|
1843
|
+
# --- Traces ---
|
|
1844
|
+
def create_trace(self, trace: "Trace") -> None:
|
|
1845
|
+
"""Create a single trace record in the database.
|
|
1846
|
+
|
|
1847
|
+
Args:
|
|
1848
|
+
trace: The Trace object to store (one per trace_id).
|
|
1849
|
+
"""
|
|
1850
|
+
try:
|
|
1851
|
+
collection_ref = self._get_collection(table_type="traces", create_collection_if_not_found=True)
|
|
1852
|
+
if collection_ref is None:
|
|
1853
|
+
return
|
|
1854
|
+
|
|
1855
|
+
# Check if trace already exists
|
|
1856
|
+
docs = collection_ref.where(filter=FieldFilter("trace_id", "==", trace.trace_id)).limit(1).stream()
|
|
1857
|
+
existing_doc = None
|
|
1858
|
+
existing_data = None
|
|
1859
|
+
for doc in docs:
|
|
1860
|
+
existing_doc = doc
|
|
1861
|
+
existing_data = doc.to_dict()
|
|
1862
|
+
break
|
|
1863
|
+
|
|
1864
|
+
if existing_data and existing_doc is not None:
|
|
1865
|
+
# Update existing trace
|
|
1866
|
+
def get_component_level(workflow_id, team_id, agent_id, name):
|
|
1867
|
+
is_root_name = ".run" in name or ".arun" in name
|
|
1868
|
+
if not is_root_name:
|
|
1869
|
+
return 0
|
|
1870
|
+
elif workflow_id:
|
|
1871
|
+
return 3
|
|
1872
|
+
elif team_id:
|
|
1873
|
+
return 2
|
|
1874
|
+
elif agent_id:
|
|
1875
|
+
return 1
|
|
1876
|
+
else:
|
|
1877
|
+
return 0
|
|
1878
|
+
|
|
1879
|
+
existing_level = get_component_level(
|
|
1880
|
+
existing_data.get("workflow_id"),
|
|
1881
|
+
existing_data.get("team_id"),
|
|
1882
|
+
existing_data.get("agent_id"),
|
|
1883
|
+
existing_data.get("name", ""),
|
|
1884
|
+
)
|
|
1885
|
+
new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name)
|
|
1886
|
+
should_update_name = new_level > existing_level
|
|
1887
|
+
|
|
1888
|
+
# Parse existing start_time to calculate correct duration
|
|
1889
|
+
existing_start_time_str = existing_data.get("start_time")
|
|
1890
|
+
if isinstance(existing_start_time_str, str):
|
|
1891
|
+
existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00"))
|
|
1892
|
+
else:
|
|
1893
|
+
existing_start_time = trace.start_time
|
|
1894
|
+
|
|
1895
|
+
recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000)
|
|
1896
|
+
|
|
1897
|
+
update_values: Dict[str, Any] = {
|
|
1898
|
+
"end_time": trace.end_time.isoformat(),
|
|
1899
|
+
"duration_ms": recalculated_duration_ms,
|
|
1900
|
+
"status": trace.status,
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
if should_update_name:
|
|
1904
|
+
update_values["name"] = trace.name
|
|
1905
|
+
|
|
1906
|
+
# Update context fields only if new value is not None
|
|
1907
|
+
if trace.run_id is not None:
|
|
1908
|
+
update_values["run_id"] = trace.run_id
|
|
1909
|
+
if trace.session_id is not None:
|
|
1910
|
+
update_values["session_id"] = trace.session_id
|
|
1911
|
+
if trace.user_id is not None:
|
|
1912
|
+
update_values["user_id"] = trace.user_id
|
|
1913
|
+
if trace.agent_id is not None:
|
|
1914
|
+
update_values["agent_id"] = trace.agent_id
|
|
1915
|
+
if trace.team_id is not None:
|
|
1916
|
+
update_values["team_id"] = trace.team_id
|
|
1917
|
+
if trace.workflow_id is not None:
|
|
1918
|
+
update_values["workflow_id"] = trace.workflow_id
|
|
1919
|
+
|
|
1920
|
+
existing_doc.reference.update(update_values)
|
|
1921
|
+
else:
|
|
1922
|
+
# Create new trace with initialized counters
|
|
1923
|
+
trace_dict = trace.to_dict()
|
|
1924
|
+
trace_dict["total_spans"] = 0
|
|
1925
|
+
trace_dict["error_count"] = 0
|
|
1926
|
+
collection_ref.add(trace_dict)
|
|
1927
|
+
|
|
1928
|
+
except Exception as e:
|
|
1929
|
+
log_error(f"Error creating trace: {e}")
|
|
1930
|
+
|
|
1931
|
+
def get_trace(
|
|
1932
|
+
self,
|
|
1933
|
+
trace_id: Optional[str] = None,
|
|
1934
|
+
run_id: Optional[str] = None,
|
|
1935
|
+
):
|
|
1936
|
+
"""Get a single trace by trace_id or other filters.
|
|
1937
|
+
|
|
1938
|
+
Args:
|
|
1939
|
+
trace_id: The unique trace identifier.
|
|
1940
|
+
run_id: Filter by run ID (returns first match).
|
|
1941
|
+
|
|
1942
|
+
Returns:
|
|
1943
|
+
Optional[Trace]: The trace if found, None otherwise.
|
|
1944
|
+
|
|
1945
|
+
Note:
|
|
1946
|
+
If multiple filters are provided, trace_id takes precedence.
|
|
1947
|
+
For other filters, the most recent trace is returned.
|
|
1948
|
+
"""
|
|
1949
|
+
try:
|
|
1950
|
+
from agno.tracing.schemas import Trace
|
|
1951
|
+
|
|
1952
|
+
collection_ref = self._get_collection(table_type="traces")
|
|
1953
|
+
if collection_ref is None:
|
|
1954
|
+
return None
|
|
1955
|
+
|
|
1956
|
+
if trace_id:
|
|
1957
|
+
docs = collection_ref.where(filter=FieldFilter("trace_id", "==", trace_id)).limit(1).stream()
|
|
1958
|
+
elif run_id:
|
|
1959
|
+
from google.cloud.firestore import Query
|
|
1960
|
+
|
|
1961
|
+
docs = (
|
|
1962
|
+
collection_ref.where(filter=FieldFilter("run_id", "==", run_id))
|
|
1963
|
+
.order_by("start_time", direction=Query.DESCENDING)
|
|
1964
|
+
.limit(1)
|
|
1965
|
+
.stream()
|
|
1966
|
+
)
|
|
1967
|
+
else:
|
|
1968
|
+
log_debug("get_trace called without any filter parameters")
|
|
1969
|
+
return None
|
|
1970
|
+
|
|
1971
|
+
for doc in docs:
|
|
1972
|
+
trace_data = doc.to_dict()
|
|
1973
|
+
# Use stored values (default to 0 if not present)
|
|
1974
|
+
trace_data.setdefault("total_spans", 0)
|
|
1975
|
+
trace_data.setdefault("error_count", 0)
|
|
1976
|
+
return Trace.from_dict(trace_data)
|
|
1977
|
+
|
|
1978
|
+
return None
|
|
1979
|
+
|
|
1980
|
+
except Exception as e:
|
|
1981
|
+
log_error(f"Error getting trace: {e}")
|
|
1982
|
+
return None
|
|
1983
|
+
|
|
1984
|
+
def get_traces(
|
|
1985
|
+
self,
|
|
1986
|
+
run_id: Optional[str] = None,
|
|
1987
|
+
session_id: Optional[str] = None,
|
|
1988
|
+
user_id: Optional[str] = None,
|
|
1989
|
+
agent_id: Optional[str] = None,
|
|
1990
|
+
team_id: Optional[str] = None,
|
|
1991
|
+
workflow_id: Optional[str] = None,
|
|
1992
|
+
status: Optional[str] = None,
|
|
1993
|
+
start_time: Optional[datetime] = None,
|
|
1994
|
+
end_time: Optional[datetime] = None,
|
|
1995
|
+
limit: Optional[int] = 20,
|
|
1996
|
+
page: Optional[int] = 1,
|
|
1997
|
+
) -> tuple[List, int]:
|
|
1998
|
+
"""Get traces matching the provided filters.
|
|
1999
|
+
|
|
2000
|
+
Args:
|
|
2001
|
+
run_id: Filter by run ID.
|
|
2002
|
+
session_id: Filter by session ID.
|
|
2003
|
+
user_id: Filter by user ID.
|
|
2004
|
+
agent_id: Filter by agent ID.
|
|
2005
|
+
team_id: Filter by team ID.
|
|
2006
|
+
workflow_id: Filter by workflow ID.
|
|
2007
|
+
status: Filter by status (OK, ERROR, UNSET).
|
|
2008
|
+
start_time: Filter traces starting after this datetime.
|
|
2009
|
+
end_time: Filter traces ending before this datetime.
|
|
2010
|
+
limit: Maximum number of traces to return per page.
|
|
2011
|
+
page: Page number (1-indexed).
|
|
2012
|
+
|
|
2013
|
+
Returns:
|
|
2014
|
+
tuple[List[Trace], int]: Tuple of (list of matching traces, total count).
|
|
2015
|
+
"""
|
|
2016
|
+
try:
|
|
2017
|
+
from agno.tracing.schemas import Trace
|
|
2018
|
+
|
|
2019
|
+
collection_ref = self._get_collection(table_type="traces")
|
|
2020
|
+
if collection_ref is None:
|
|
2021
|
+
return [], 0
|
|
2022
|
+
|
|
2023
|
+
query = collection_ref
|
|
2024
|
+
|
|
2025
|
+
# Apply filters
|
|
2026
|
+
if run_id:
|
|
2027
|
+
query = query.where(filter=FieldFilter("run_id", "==", run_id))
|
|
2028
|
+
if session_id:
|
|
2029
|
+
query = query.where(filter=FieldFilter("session_id", "==", session_id))
|
|
2030
|
+
if user_id:
|
|
2031
|
+
query = query.where(filter=FieldFilter("user_id", "==", user_id))
|
|
2032
|
+
if agent_id:
|
|
2033
|
+
query = query.where(filter=FieldFilter("agent_id", "==", agent_id))
|
|
2034
|
+
if team_id:
|
|
2035
|
+
query = query.where(filter=FieldFilter("team_id", "==", team_id))
|
|
2036
|
+
if workflow_id:
|
|
2037
|
+
query = query.where(filter=FieldFilter("workflow_id", "==", workflow_id))
|
|
2038
|
+
if status:
|
|
2039
|
+
query = query.where(filter=FieldFilter("status", "==", status))
|
|
2040
|
+
if start_time:
|
|
2041
|
+
query = query.where(filter=FieldFilter("start_time", ">=", start_time.isoformat()))
|
|
2042
|
+
if end_time:
|
|
2043
|
+
query = query.where(filter=FieldFilter("end_time", "<=", end_time.isoformat()))
|
|
2044
|
+
|
|
2045
|
+
# Get all matching documents
|
|
2046
|
+
docs = query.stream()
|
|
2047
|
+
all_records = [doc.to_dict() for doc in docs]
|
|
2048
|
+
|
|
2049
|
+
# Sort by start_time descending
|
|
2050
|
+
all_records.sort(key=lambda x: x.get("start_time", ""), reverse=True)
|
|
2051
|
+
|
|
2052
|
+
# Get total count
|
|
2053
|
+
total_count = len(all_records)
|
|
2054
|
+
|
|
2055
|
+
# Apply pagination
|
|
2056
|
+
if limit and page:
|
|
2057
|
+
offset = (page - 1) * limit
|
|
2058
|
+
paginated_records = all_records[offset : offset + limit]
|
|
2059
|
+
elif limit:
|
|
2060
|
+
paginated_records = all_records[:limit]
|
|
2061
|
+
else:
|
|
2062
|
+
paginated_records = all_records
|
|
2063
|
+
|
|
2064
|
+
# Convert to Trace objects with stored span counts
|
|
2065
|
+
traces = []
|
|
2066
|
+
for trace_data in paginated_records:
|
|
2067
|
+
trace_data.setdefault("total_spans", 0)
|
|
2068
|
+
trace_data.setdefault("error_count", 0)
|
|
2069
|
+
traces.append(Trace.from_dict(trace_data))
|
|
2070
|
+
|
|
2071
|
+
return traces, total_count
|
|
2072
|
+
|
|
2073
|
+
except Exception as e:
|
|
2074
|
+
log_error(f"Error getting traces: {e}")
|
|
2075
|
+
return [], 0
|
|
2076
|
+
|
|
2077
|
+
def get_trace_stats(
|
|
2078
|
+
self,
|
|
2079
|
+
user_id: Optional[str] = None,
|
|
2080
|
+
agent_id: Optional[str] = None,
|
|
2081
|
+
team_id: Optional[str] = None,
|
|
2082
|
+
workflow_id: Optional[str] = None,
|
|
2083
|
+
start_time: Optional[datetime] = None,
|
|
2084
|
+
end_time: Optional[datetime] = None,
|
|
2085
|
+
limit: Optional[int] = 20,
|
|
2086
|
+
page: Optional[int] = 1,
|
|
2087
|
+
) -> tuple[List[Dict[str, Any]], int]:
|
|
2088
|
+
"""Get trace statistics grouped by session.
|
|
2089
|
+
|
|
2090
|
+
Args:
|
|
2091
|
+
user_id: Filter by user ID.
|
|
2092
|
+
agent_id: Filter by agent ID.
|
|
2093
|
+
team_id: Filter by team ID.
|
|
2094
|
+
workflow_id: Filter by workflow ID.
|
|
2095
|
+
start_time: Filter sessions with traces created after this datetime.
|
|
2096
|
+
end_time: Filter sessions with traces created before this datetime.
|
|
2097
|
+
limit: Maximum number of sessions to return per page.
|
|
2098
|
+
page: Page number (1-indexed).
|
|
2099
|
+
|
|
2100
|
+
Returns:
|
|
2101
|
+
tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count).
|
|
2102
|
+
Each dict contains: session_id, user_id, agent_id, team_id, workflow_id, total_traces,
|
|
2103
|
+
first_trace_at, last_trace_at.
|
|
2104
|
+
"""
|
|
2105
|
+
try:
|
|
2106
|
+
collection_ref = self._get_collection(table_type="traces")
|
|
2107
|
+
if collection_ref is None:
|
|
2108
|
+
return [], 0
|
|
2109
|
+
|
|
2110
|
+
query = collection_ref
|
|
2111
|
+
|
|
2112
|
+
# Apply filters
|
|
2113
|
+
if user_id:
|
|
2114
|
+
query = query.where(filter=FieldFilter("user_id", "==", user_id))
|
|
2115
|
+
if agent_id:
|
|
2116
|
+
query = query.where(filter=FieldFilter("agent_id", "==", agent_id))
|
|
2117
|
+
if team_id:
|
|
2118
|
+
query = query.where(filter=FieldFilter("team_id", "==", team_id))
|
|
2119
|
+
if workflow_id:
|
|
2120
|
+
query = query.where(filter=FieldFilter("workflow_id", "==", workflow_id))
|
|
2121
|
+
if start_time:
|
|
2122
|
+
query = query.where(filter=FieldFilter("created_at", ">=", start_time.isoformat()))
|
|
2123
|
+
if end_time:
|
|
2124
|
+
query = query.where(filter=FieldFilter("created_at", "<=", end_time.isoformat()))
|
|
2125
|
+
|
|
2126
|
+
# Get all matching documents
|
|
2127
|
+
docs = query.stream()
|
|
2128
|
+
|
|
2129
|
+
# Aggregate by session_id
|
|
2130
|
+
session_stats: Dict[str, Dict[str, Any]] = {}
|
|
2131
|
+
for doc in docs:
|
|
2132
|
+
trace_data = doc.to_dict()
|
|
2133
|
+
session_id = trace_data.get("session_id")
|
|
2134
|
+
if not session_id:
|
|
2135
|
+
continue
|
|
2136
|
+
|
|
2137
|
+
if session_id not in session_stats:
|
|
2138
|
+
session_stats[session_id] = {
|
|
2139
|
+
"session_id": session_id,
|
|
2140
|
+
"user_id": trace_data.get("user_id"),
|
|
2141
|
+
"agent_id": trace_data.get("agent_id"),
|
|
2142
|
+
"team_id": trace_data.get("team_id"),
|
|
2143
|
+
"workflow_id": trace_data.get("workflow_id"),
|
|
2144
|
+
"total_traces": 0,
|
|
2145
|
+
"first_trace_at": trace_data.get("created_at"),
|
|
2146
|
+
"last_trace_at": trace_data.get("created_at"),
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
session_stats[session_id]["total_traces"] += 1
|
|
2150
|
+
|
|
2151
|
+
created_at = trace_data.get("created_at")
|
|
2152
|
+
if (
|
|
2153
|
+
created_at
|
|
2154
|
+
and session_stats[session_id]["first_trace_at"]
|
|
2155
|
+
and session_stats[session_id]["last_trace_at"]
|
|
2156
|
+
):
|
|
2157
|
+
if created_at < session_stats[session_id]["first_trace_at"]:
|
|
2158
|
+
session_stats[session_id]["first_trace_at"] = created_at
|
|
2159
|
+
if created_at > session_stats[session_id]["last_trace_at"]:
|
|
2160
|
+
session_stats[session_id]["last_trace_at"] = created_at
|
|
2161
|
+
|
|
2162
|
+
# Convert to list and sort by last_trace_at descending
|
|
2163
|
+
stats_list = list(session_stats.values())
|
|
2164
|
+
stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True)
|
|
2165
|
+
|
|
2166
|
+
# Convert datetime strings to datetime objects
|
|
2167
|
+
for stat in stats_list:
|
|
2168
|
+
first_trace_at = stat["first_trace_at"]
|
|
2169
|
+
last_trace_at = stat["last_trace_at"]
|
|
2170
|
+
if isinstance(first_trace_at, str):
|
|
2171
|
+
stat["first_trace_at"] = datetime.fromisoformat(first_trace_at.replace("Z", "+00:00"))
|
|
2172
|
+
if isinstance(last_trace_at, str):
|
|
2173
|
+
stat["last_trace_at"] = datetime.fromisoformat(last_trace_at.replace("Z", "+00:00"))
|
|
2174
|
+
|
|
2175
|
+
# Get total count
|
|
2176
|
+
total_count = len(stats_list)
|
|
2177
|
+
|
|
2178
|
+
# Apply pagination
|
|
2179
|
+
if limit and page:
|
|
2180
|
+
offset = (page - 1) * limit
|
|
2181
|
+
paginated_stats = stats_list[offset : offset + limit]
|
|
2182
|
+
elif limit:
|
|
2183
|
+
paginated_stats = stats_list[:limit]
|
|
2184
|
+
else:
|
|
2185
|
+
paginated_stats = stats_list
|
|
2186
|
+
|
|
2187
|
+
return paginated_stats, total_count
|
|
2188
|
+
|
|
2189
|
+
except Exception as e:
|
|
2190
|
+
log_error(f"Error getting trace stats: {e}")
|
|
2191
|
+
return [], 0
|
|
2192
|
+
|
|
2193
|
+
# --- Spans ---
|
|
2194
|
+
def create_span(self, span: "Span") -> None:
|
|
2195
|
+
"""Create a single span in the database.
|
|
2196
|
+
|
|
2197
|
+
Args:
|
|
2198
|
+
span: The Span object to store.
|
|
2199
|
+
"""
|
|
2200
|
+
try:
|
|
2201
|
+
collection_ref = self._get_collection(table_type="spans", create_collection_if_not_found=True)
|
|
2202
|
+
if collection_ref is None:
|
|
2203
|
+
return
|
|
2204
|
+
|
|
2205
|
+
span_dict = span.to_dict()
|
|
2206
|
+
# Serialize attributes as JSON string
|
|
2207
|
+
if "attributes" in span_dict and isinstance(span_dict["attributes"], dict):
|
|
2208
|
+
span_dict["attributes"] = json.dumps(span_dict["attributes"])
|
|
2209
|
+
|
|
2210
|
+
collection_ref.add(span_dict)
|
|
2211
|
+
|
|
2212
|
+
# Increment total_spans and error_count on trace
|
|
2213
|
+
traces_collection = self._get_collection(table_type="traces")
|
|
2214
|
+
if traces_collection:
|
|
2215
|
+
try:
|
|
2216
|
+
docs = (
|
|
2217
|
+
traces_collection.where(filter=FieldFilter("trace_id", "==", span.trace_id)).limit(1).stream()
|
|
2218
|
+
)
|
|
2219
|
+
for doc in docs:
|
|
2220
|
+
trace_data = doc.to_dict()
|
|
2221
|
+
current_total = trace_data.get("total_spans", 0)
|
|
2222
|
+
current_errors = trace_data.get("error_count", 0)
|
|
2223
|
+
|
|
2224
|
+
update_values = {"total_spans": current_total + 1}
|
|
2225
|
+
if span.status_code == "ERROR":
|
|
2226
|
+
update_values["error_count"] = current_errors + 1
|
|
2227
|
+
|
|
2228
|
+
doc.reference.update(update_values)
|
|
2229
|
+
break
|
|
2230
|
+
except Exception as update_error:
|
|
2231
|
+
log_debug(f"Could not update trace span counts: {update_error}")
|
|
2232
|
+
|
|
2233
|
+
except Exception as e:
|
|
2234
|
+
log_error(f"Error creating span: {e}")
|
|
2235
|
+
|
|
2236
|
+
def create_spans(self, spans: List) -> None:
|
|
2237
|
+
"""Create multiple spans in the database as a batch.
|
|
2238
|
+
|
|
2239
|
+
Args:
|
|
2240
|
+
spans: List of Span objects to store.
|
|
2241
|
+
"""
|
|
2242
|
+
if not spans:
|
|
2243
|
+
return
|
|
2244
|
+
|
|
2245
|
+
try:
|
|
2246
|
+
collection_ref = self._get_collection(table_type="spans", create_collection_if_not_found=True)
|
|
2247
|
+
if collection_ref is None:
|
|
2248
|
+
return
|
|
2249
|
+
|
|
2250
|
+
# Firestore batch has a limit of 500 operations
|
|
2251
|
+
batch = self.db_client.batch()
|
|
2252
|
+
batch_count = 0
|
|
2253
|
+
|
|
2254
|
+
for span in spans:
|
|
2255
|
+
span_dict = span.to_dict()
|
|
2256
|
+
# Serialize attributes as JSON string
|
|
2257
|
+
if "attributes" in span_dict and isinstance(span_dict["attributes"], dict):
|
|
2258
|
+
span_dict["attributes"] = json.dumps(span_dict["attributes"])
|
|
2259
|
+
|
|
2260
|
+
doc_ref = collection_ref.document()
|
|
2261
|
+
batch.set(doc_ref, span_dict)
|
|
2262
|
+
batch_count += 1
|
|
2263
|
+
|
|
2264
|
+
# Commit batch if reaching limit
|
|
2265
|
+
if batch_count >= 500:
|
|
2266
|
+
batch.commit()
|
|
2267
|
+
batch = self.db_client.batch()
|
|
2268
|
+
batch_count = 0
|
|
2269
|
+
|
|
2270
|
+
# Commit remaining operations
|
|
2271
|
+
if batch_count > 0:
|
|
2272
|
+
batch.commit()
|
|
2273
|
+
|
|
2274
|
+
# Update trace with total_spans and error_count
|
|
2275
|
+
trace_id = spans[0].trace_id
|
|
2276
|
+
spans_count = len(spans)
|
|
2277
|
+
error_count = sum(1 for s in spans if s.status_code == "ERROR")
|
|
2278
|
+
|
|
2279
|
+
traces_collection = self._get_collection(table_type="traces")
|
|
2280
|
+
if traces_collection:
|
|
2281
|
+
try:
|
|
2282
|
+
docs = traces_collection.where(filter=FieldFilter("trace_id", "==", trace_id)).limit(1).stream()
|
|
2283
|
+
for doc in docs:
|
|
2284
|
+
trace_data = doc.to_dict()
|
|
2285
|
+
current_total = trace_data.get("total_spans", 0)
|
|
2286
|
+
current_errors = trace_data.get("error_count", 0)
|
|
2287
|
+
|
|
2288
|
+
doc.reference.update(
|
|
2289
|
+
{
|
|
2290
|
+
"total_spans": current_total + spans_count,
|
|
2291
|
+
"error_count": current_errors + error_count,
|
|
2292
|
+
}
|
|
2293
|
+
)
|
|
2294
|
+
break
|
|
2295
|
+
except Exception as update_error:
|
|
2296
|
+
log_debug(f"Could not update trace span counts: {update_error}")
|
|
2297
|
+
|
|
2298
|
+
except Exception as e:
|
|
2299
|
+
log_error(f"Error creating spans batch: {e}")
|
|
2300
|
+
|
|
2301
|
+
def get_span(self, span_id: str):
|
|
2302
|
+
"""Get a single span by its span_id.
|
|
2303
|
+
|
|
2304
|
+
Args:
|
|
2305
|
+
span_id: The unique span identifier.
|
|
2306
|
+
|
|
2307
|
+
Returns:
|
|
2308
|
+
Optional[Span]: The span if found, None otherwise.
|
|
2309
|
+
"""
|
|
2310
|
+
try:
|
|
2311
|
+
from agno.tracing.schemas import Span
|
|
2312
|
+
|
|
2313
|
+
collection_ref = self._get_collection(table_type="spans")
|
|
2314
|
+
if collection_ref is None:
|
|
2315
|
+
return None
|
|
2316
|
+
|
|
2317
|
+
docs = collection_ref.where(filter=FieldFilter("span_id", "==", span_id)).limit(1).stream()
|
|
2318
|
+
|
|
2319
|
+
for doc in docs:
|
|
2320
|
+
span_data = doc.to_dict()
|
|
2321
|
+
# Deserialize attributes from JSON string
|
|
2322
|
+
if "attributes" in span_data and isinstance(span_data["attributes"], str):
|
|
2323
|
+
span_data["attributes"] = json.loads(span_data["attributes"])
|
|
2324
|
+
return Span.from_dict(span_data)
|
|
2325
|
+
|
|
2326
|
+
return None
|
|
2327
|
+
|
|
2328
|
+
except Exception as e:
|
|
2329
|
+
log_error(f"Error getting span: {e}")
|
|
2330
|
+
return None
|
|
2331
|
+
|
|
2332
|
+
def get_spans(
|
|
2333
|
+
self,
|
|
2334
|
+
trace_id: Optional[str] = None,
|
|
2335
|
+
parent_span_id: Optional[str] = None,
|
|
2336
|
+
limit: Optional[int] = 1000,
|
|
2337
|
+
) -> List:
|
|
2338
|
+
"""Get spans matching the provided filters.
|
|
2339
|
+
|
|
2340
|
+
Args:
|
|
2341
|
+
trace_id: Filter by trace ID.
|
|
2342
|
+
parent_span_id: Filter by parent span ID.
|
|
2343
|
+
limit: Maximum number of spans to return.
|
|
2344
|
+
|
|
2345
|
+
Returns:
|
|
2346
|
+
List[Span]: List of matching spans.
|
|
2347
|
+
"""
|
|
2348
|
+
try:
|
|
2349
|
+
from agno.tracing.schemas import Span
|
|
2350
|
+
|
|
2351
|
+
collection_ref = self._get_collection(table_type="spans")
|
|
2352
|
+
if collection_ref is None:
|
|
2353
|
+
return []
|
|
2354
|
+
|
|
2355
|
+
query = collection_ref
|
|
2356
|
+
|
|
2357
|
+
if trace_id:
|
|
2358
|
+
query = query.where(filter=FieldFilter("trace_id", "==", trace_id))
|
|
2359
|
+
if parent_span_id:
|
|
2360
|
+
query = query.where(filter=FieldFilter("parent_span_id", "==", parent_span_id))
|
|
2361
|
+
|
|
2362
|
+
if limit:
|
|
2363
|
+
query = query.limit(limit)
|
|
2364
|
+
|
|
2365
|
+
docs = query.stream()
|
|
2366
|
+
|
|
2367
|
+
spans = []
|
|
2368
|
+
for doc in docs:
|
|
2369
|
+
span_data = doc.to_dict()
|
|
2370
|
+
# Deserialize attributes from JSON string
|
|
2371
|
+
if "attributes" in span_data and isinstance(span_data["attributes"], str):
|
|
2372
|
+
span_data["attributes"] = json.loads(span_data["attributes"])
|
|
2373
|
+
spans.append(Span.from_dict(span_data))
|
|
2374
|
+
|
|
2375
|
+
return spans
|
|
2376
|
+
|
|
2377
|
+
except Exception as e:
|
|
2378
|
+
log_error(f"Error getting spans: {e}")
|
|
2379
|
+
return []
|
agno/db/firestore/schemas.py
CHANGED
|
@@ -122,6 +122,44 @@ CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA = [
|
|
|
122
122
|
{"key": "updated_at"},
|
|
123
123
|
]
|
|
124
124
|
|
|
125
|
+
TRACE_COLLECTION_SCHEMA = [
|
|
126
|
+
{"key": "trace_id", "unique": True},
|
|
127
|
+
{"key": "name"},
|
|
128
|
+
{"key": "status"},
|
|
129
|
+
{"key": "run_id"},
|
|
130
|
+
{"key": "session_id"},
|
|
131
|
+
{"key": "user_id"},
|
|
132
|
+
{"key": "agent_id"},
|
|
133
|
+
{"key": "team_id"},
|
|
134
|
+
{"key": "workflow_id"},
|
|
135
|
+
{"key": "start_time"},
|
|
136
|
+
{"key": "end_time"},
|
|
137
|
+
{"key": "created_at"},
|
|
138
|
+
# Composite indexes for common query patterns
|
|
139
|
+
{"key": [("session_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
140
|
+
{"key": [("user_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
141
|
+
{"key": [("agent_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
142
|
+
{"key": [("team_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
143
|
+
{"key": [("workflow_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
144
|
+
{"key": [("run_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
145
|
+
{"key": [("status", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False},
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
SPAN_COLLECTION_SCHEMA = [
|
|
149
|
+
{"key": "span_id", "unique": True},
|
|
150
|
+
{"key": "trace_id"},
|
|
151
|
+
{"key": "parent_span_id"},
|
|
152
|
+
{"key": "name"},
|
|
153
|
+
{"key": "span_kind"},
|
|
154
|
+
{"key": "status_code"},
|
|
155
|
+
{"key": "start_time"},
|
|
156
|
+
{"key": "end_time"},
|
|
157
|
+
{"key": "created_at"},
|
|
158
|
+
# Composite indexes for common query patterns
|
|
159
|
+
{"key": [("trace_id", "ASCENDING"), ("start_time", "ASCENDING")], "collection_group": False},
|
|
160
|
+
{"key": [("parent_span_id", "ASCENDING"), ("start_time", "ASCENDING")], "collection_group": False},
|
|
161
|
+
]
|
|
162
|
+
|
|
125
163
|
|
|
126
164
|
def get_collection_indexes(collection_type: str) -> List[Dict[str, Any]]:
|
|
127
165
|
"""Get the index definitions for a specific collection type."""
|
|
@@ -132,6 +170,8 @@ def get_collection_indexes(collection_type: str) -> List[Dict[str, Any]]:
|
|
|
132
170
|
"evals": EVAL_COLLECTION_SCHEMA,
|
|
133
171
|
"knowledge": KNOWLEDGE_COLLECTION_SCHEMA,
|
|
134
172
|
"culture": CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA,
|
|
173
|
+
"traces": TRACE_COLLECTION_SCHEMA,
|
|
174
|
+
"spans": SPAN_COLLECTION_SCHEMA,
|
|
135
175
|
}
|
|
136
176
|
|
|
137
177
|
indexes = index_definitions.get(collection_type)
|