sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
agno-agi/agno:libs/agno/tests/integration/models/ollama/test_thinking.py
import json import os import tempfile import pytest from agno.agent import Agent from agno.db.json import JsonDb from agno.models.message import Message from agno.models.ollama import Ollama from agno.run.agent import RunOutput api_key = os.getenv("OLLAMA_API_KEY") def _get_thinking_agent(**kwargs): """Create an agent with thinking enabled using consistent settings.""" # Use Ollama cloud if API key is available, otherwise skip test if not api_key: pytest.skip("OLLAMA_API_KEY not set - skipping Ollama cloud tests") default_config = { "model": Ollama( id="gpt-oss:120b", api_key=api_key, ), "markdown": True, "telemetry": False, } default_config.update(kwargs) return Agent(**default_config) def test_thinking(): agent = _get_thinking_agent() response: RunOutput = agent.run( "Share a 2 sentence horror story. Think through your creative process using <think></think> tags before writing the story." ) assert response.content is not None assert response.reasoning_content is not None assert response.messages is not None assert len(response.messages) == 3 assert [m.role for m in response.messages] == ["system", "user", "assistant"] assert response.messages[2].reasoning_content is not None if response.messages is not None else False @pytest.mark.asyncio async def test_async_thinking(): agent = _get_thinking_agent() response: RunOutput = await agent.arun( "Share a 2 sentence horror story. Think through your creative process using <think></think> tags before writing the story." ) assert response.content is not None assert response.reasoning_content is not None assert response.messages is not None assert len(response.messages) == 3 assert [m.role for m in response.messages] == ["system", "user", "assistant"] assert response.messages[2].reasoning_content is not None if response.messages is not None else False def test_thinking_message_serialization(): """Test that thinking content is properly serialized in Message objects.""" message = Message( role="assistant", content="The answer is 42.", reasoning_content="I need to think about the meaning of life. After careful consideration, 42 seems right.", provider_data={"signature": "thinking_sig_xyz789"}, ) # Serialize to dict message_dict = message.to_dict() # Verify thinking content is in the serialized data assert "reasoning_content" in message_dict assert ( message_dict["reasoning_content"] == "I need to think about the meaning of life. After careful consideration, 42 seems right." ) # Verify provider data is preserved assert "provider_data" in message_dict assert message_dict["provider_data"]["signature"] == "thinking_sig_xyz789" @pytest.mark.asyncio async def test_thinking_with_storage(): """Test that thinking content is stored and retrievable.""" with tempfile.TemporaryDirectory() as storage_dir: if not api_key: pytest.skip("OLLAMA_API_KEY not set - skipping Ollama cloud tests") agent = Agent( model=Ollama(id="gpt-oss:120b", api_key=api_key), db=JsonDb(db_path=storage_dir, session_table="test_session"), user_id="test_user", session_id="test_session", telemetry=False, ) # Ask a question that should trigger thinking response = await agent.arun( "What is 25 * 47? Please think through the calculation step by step using <think></think> tags.", stream=False, ) # Verify response has thinking content assert response.reasoning_content is not None assert len(response.reasoning_content) > 0 # Read the storage files to verify thinking was persisted session_files = [f for f in os.listdir(storage_dir) if f.endswith(".json")] thinking_persisted = False for session_file in session_files: if session_file == "test_session.json": with open(os.path.join(storage_dir, session_file), "r") as f: session_data = json.load(f) # Check messages in this session if session_data and session_data[0] and session_data[0]["runs"]: for run in session_data[0]["runs"]: for message in run["messages"]: if message.get("role") == "assistant" and message.get("reasoning_content"): thinking_persisted = True break if thinking_persisted: break break assert thinking_persisted, "Thinking content should be persisted in storage"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/models/ollama/test_thinking.py", "license": "Apache License 2.0", "lines": 106, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/unit/tools/test_scrapegraph.py
"""Unit tests for ScrapeGraphTools class.""" import json import os from unittest.mock import Mock, patch import pytest from agno.tools.scrapegraph import ScrapeGraphTools @pytest.fixture def mock_scrapegraph_client(): """Create a mock ScrapeGraph client.""" mock_client = Mock() # Simple mock responses mock_client.scrape.return_value = { "html": "<html><body>Test content</body></html>", "request_id": "req_123", } mock_client.smartscraper.return_value = { "result": "extracted data", "request_id": "req_123", } mock_client.markdownify.return_value = { "result": "# Test Page\n\nTest content", } mock_client.searchscraper.return_value = {"result": [{"title": "Test Result", "url": "https://example.com"}]} mock_client.crawl.return_value = {"result": [{"page": "https://example.com", "data": {"title": "Test"}}]} mock_client.agenticscraper.return_value = { "result": {"content": "scraped content"}, "request_id": "req_123", } return mock_client @pytest.fixture def scrapegraph_tools(): """Create ScrapeGraphTools instance with mocked client.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client # Mock responses mock_client.scrape.return_value = {"html": "test html", "request_id": "123"} mock_client.smartscraper.return_value = {"result": "test data", "request_id": "123"} tools = ScrapeGraphTools(enable_scrape=True) return tools def test_init_with_api_key(): """Test initialization with API key.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client, patch("agno.tools.scrapegraph.sgai_logger"), ): tools = ScrapeGraphTools(api_key="test_key") assert tools.api_key == "test_key" mock_client.assert_called_once_with(api_key="test_key") def test_init_with_env_api_key(): """Test initialization with environment API key.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "env_key"}), ): tools = ScrapeGraphTools() assert tools.api_key == "env_key" mock_client.assert_called_once_with(api_key="env_key") def test_scrape_basic_functionality(): """Test basic scrape functionality.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client mock_client.scrape.return_value = { "html": "<html>test</html>", "request_id": "req_123", } tools = ScrapeGraphTools(enable_scrape=True) result = tools.scrape("https://example.com") result_data = json.loads(result) assert result_data["html"] == "<html>test</html>" assert result_data["request_id"] == "req_123" mock_client.scrape.assert_called_once_with( website_url="https://example.com", headers=None, render_heavy_js=False, ) def test_scrape_with_render_heavy_js(): """Test scrape with render_heavy_js enabled.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client mock_client.scrape.return_value = {"html": "js content", "request_id": "123"} tools = ScrapeGraphTools(enable_scrape=True, render_heavy_js=True) tools.scrape("https://spa-site.com") mock_client.scrape.assert_called_once_with( website_url="https://spa-site.com", headers=None, render_heavy_js=True, ) def test_scrape_error_handling(): """Test scrape error handling.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client mock_client.scrape.side_effect = Exception("API Error") tools = ScrapeGraphTools(enable_scrape=True) result = tools.scrape("https://example.com") assert result.startswith("Error:") assert "API Error" in result def test_smartscraper_basic(): """Test smartscraper basic functionality.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client mock_client.smartscraper.return_value = {"result": "extracted data"} tools = ScrapeGraphTools(enable_smartscraper=True) result = tools.smartscraper("https://example.com", "extract title") result_data = json.loads(result) assert result_data == "extracted data" mock_client.smartscraper.assert_called_once_with(website_url="https://example.com", user_prompt="extract title") def test_markdownify_basic(): """Test markdownify basic functionality.""" with ( patch("agno.tools.scrapegraph.Client") as mock_client_class, patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): mock_client = Mock() mock_client_class.return_value = mock_client mock_client.markdownify.return_value = {"result": "# Title\n\nContent"} tools = ScrapeGraphTools(enable_markdownify=True) result = tools.markdownify("https://example.com") assert result == "# Title\n\nContent" mock_client.markdownify.assert_called_once_with(website_url="https://example.com") def test_tool_selection(): """Test that only selected tools are enabled.""" with ( patch("agno.tools.scrapegraph.Client"), patch("agno.tools.scrapegraph.sgai_logger"), patch.dict(os.environ, {"SGAI_API_KEY": "test_key"}), ): # Test specific tool selection tools = ScrapeGraphTools(enable_scrape=True, enable_smartscraper=True, enable_markdownify=False) tool_names = [func.__name__ for func in tools.tools] assert "scrape" in tool_names assert "smartscraper" in tool_names # When smartscraper=False, markdownify is auto-enabled, so we test with both enabled
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/tools/test_scrapegraph.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/tools/mcp_toolbox.py
from typing import Any, Callable, Dict, List, Literal, Optional, Union from warnings import warn from agno.tools.function import Function from agno.tools.mcp import MCPTools from agno.utils.log import logger try: from toolbox_core import ToolboxClient # type: ignore except ImportError: raise ImportError("`toolbox_core` not installed. Please install using `pip install -U toolbox-core`.") class MCPToolsMeta(type): """Metaclass for MCPTools to ensure proper initialization with AgentOS""" @property def __name__(cls): return "MCPTools" class MCPToolbox(MCPTools, metaclass=MCPToolsMeta): """ A toolkit that combines MCPTools server connectivity with MCP Toolbox for Databases client (toolbox-core). MCPToolbox connects to an MCP Toolbox server and registers all available tools, then uses toolbox-core to filter those tools by toolset or tool name. This enables agents to receive only the specific tools they need while maintaining full MCP execution capabilities. """ def __init__( self, url: str, toolsets: Optional[List[str]] = None, tool_name: Optional[str] = None, headers: Optional[Dict[str, Any]] = None, transport: Literal["stdio", "sse", "streamable-http"] = "streamable-http", append_mcp_to_url: bool = True, **kwargs, ): """Initialize MCPToolbox with filtering capabilities. Args: url (str): Base URL for the toolbox service. toolsets (Optional[List[str]], optional): List of toolset names to filter tools by. Defaults to None. tool_name (Optional[str], optional): Single tool name to load. Defaults to None. headers (Optional[Dict[str, Any]], optional): Headers for toolbox-core client requests. Defaults to None. transport (Literal["stdio", "sse", "streamable-http"], optional): MCP transport protocol. Defaults to "streamable-http". append_mcp_to_url (bool, optional): Whether to append "/mcp" to the URL if it doesn't end with it. Defaults to True. """ if append_mcp_to_url and not url.endswith("/mcp"): url = url + "/mcp" super().__init__(url=url, transport=transport, **kwargs) self.name = "toolbox_client" self.toolbox_url = url self.toolsets = toolsets self.tool_name = tool_name self.headers = headers self._core_client_initialized = False # Validate that only one of toolsets or tool_name is provided filter_params = [toolsets, tool_name] non_none_params = [p for p in filter_params if p is not None] if len(non_none_params) > 1: raise ValueError("Only one of toolsets or tool_name can be specified") async def connect(self): """Initialize MCPToolbox instance and connect to the MCP server.""" # First, connect to MCP server and load all available tools await super().connect() if self._core_client_initialized: return # Then, connect to the ToolboxClient and filter tools based on toolsets or tool_name await self._connect_toolbox_client() async def _connect_toolbox_client(self): try: if self.toolsets is not None or self.tool_name is not None: self.__core_client = ToolboxClient( url=self.toolbox_url, client_headers=self.headers, ) self._core_client_initialized = True if self.toolsets is not None: # Load multiple toolsets all_functions = await self.load_multiple_toolsets(toolset_names=self.toolsets) # Replace functions dict with filtered subset filtered_functions = {func.name: func for func in all_functions} self.functions = filtered_functions elif self.tool_name is not None: tool = await self.load_tool(tool_name=self.tool_name) # Replace functions dict with just this single tool self.functions = {tool.name: tool} except Exception as e: raise RuntimeError(f"Failed to connect to ToolboxClient: {e}") from e def _handle_auth_params( self, auth_token_getters: dict[str, Callable[[], str]] = {}, auth_tokens: Optional[dict[str, Callable[[], str]]] = None, auth_headers: Optional[dict[str, Callable[[], str]]] = None, ): """handle authentication parameters for toolbox-core client""" if auth_tokens: if auth_token_getters: warn( "Both `auth_token_getters` and `auth_tokens` are provided. `auth_tokens` is deprecated, and `auth_token_getters` will be used.", DeprecationWarning, ) else: warn( "Argument `auth_tokens` is deprecated. Use `auth_token_getters` instead.", DeprecationWarning, ) auth_token_getters = auth_tokens if auth_headers: if auth_token_getters: warn( "Both `auth_token_getters` and `auth_headers` are provided. `auth_headers` is deprecated, and `auth_token_getters` will be used.", DeprecationWarning, ) else: warn( "Argument `auth_headers` is deprecated. Use `auth_token_getters` instead.", DeprecationWarning, ) auth_token_getters = auth_headers return auth_token_getters async def load_tool( self, tool_name: str, auth_token_getters: dict[str, Callable[[], str]] = {}, auth_tokens: Optional[dict[str, Callable[[], str]]] = None, auth_headers: Optional[dict[str, Callable[[], str]]] = None, bound_params: dict[str, Union[Any, Callable[[], Any]]] = {}, ) -> Function: """Loads the tool with the given tool name from the Toolbox service. Args: tool_name (str): The name of the tool to load. auth_token_getters (dict[str, Callable[[], str]], optional): A mapping of authentication source names to functions that retrieve ID tokens. Defaults to {}. auth_tokens (Optional[dict[str, Callable[[], str]]], optional): Deprecated. Use `auth_token_getters` instead. auth_headers (Optional[dict[str, Callable[[], str]]], optional): Deprecated. Use `auth_token_getters` instead. bound_params (dict[str, Union[Any, Callable[[], Any]]], optional): A mapping of parameter names to their bound values. Defaults to {}. Raises: RuntimeError: If the tool is not found in the MCP functions registry. Returns: Function: The loaded tool function. """ auth_token_getters = self._handle_auth_params( auth_token_getters=auth_token_getters, auth_tokens=auth_tokens, auth_headers=auth_headers, ) core_sync_tool = await self.__core_client.load_tool( name=tool_name, auth_token_getters=auth_token_getters, bound_params=bound_params, ) # Return the Function object from our MCP functions registry if core_sync_tool._name in self.functions: return self.functions[core_sync_tool._name] else: raise RuntimeError(f"Tool '{tool_name}' was not found in MCP functions registry") async def load_toolset( self, toolset_name: Optional[str] = None, auth_token_getters: dict[str, Callable[[], str]] = {}, auth_tokens: Optional[dict[str, Callable[[], str]]] = None, auth_headers: Optional[dict[str, Callable[[], str]]] = None, bound_params: dict[str, Union[Any, Callable[[], Any]]] = {}, strict: bool = False, ) -> List[Function]: """Loads tools from the configured toolset. Args: toolset_name (Optional[str], optional): The name of the toolset to load. Defaults to None. auth_token_getters (dict[str, Callable[[], str]], optional): A mapping of authentication source names to functions that retrieve ID tokens. Defaults to {}. auth_tokens (Optional[dict[str, Callable[[], str]]], optional): Deprecated. Use `auth_token_getters` instead. auth_headers (Optional[dict[str, Callable[[], str]]], optional): Deprecated. Use `auth_token_getters` instead. bound_params (dict[str, Union[Any, Callable[[], Any]]], optional): A mapping of parameter names to their bound values. Defaults to {}. strict (bool, optional): If True, raises an error if *any* loaded tool instance fails to utilize all of the given parameters or auth tokens. (if any provided). If False (default), raises an error only if a user-provided parameter or auth token cannot be applied to *any* loaded tool across the set. Returns: List[Function]: A list of all tools loaded from the Toolbox. """ auth_token_getters = self._handle_auth_params( auth_token_getters=auth_token_getters, auth_tokens=auth_tokens, auth_headers=auth_headers, ) core_sync_tools = await self.__core_client.load_toolset( name=toolset_name, auth_token_getters=auth_token_getters, bound_params=bound_params, strict=strict, ) tools = [] for core_sync_tool in core_sync_tools: if core_sync_tool._name in self.functions: tools.append(self.functions[core_sync_tool._name]) else: logger.debug(f"Tool '{core_sync_tool._name}' from toolset '{toolset_name}' not available in MCP server") return tools async def load_multiple_toolsets( self, toolset_names: List[str], auth_token_getters: dict[str, Callable[[], str]] = {}, bound_params: dict[str, Union[Any, Callable[[], Any]]] = {}, strict: bool = False, ) -> List[Function]: """Load tools from multiple toolsets. Args: toolset_names (List[str]): A list of toolset names to load. auth_token_getters (dict[str, Callable[[], str]], optional): A mapping of authentication source names to functions that retrieve ID tokens. Defaults to {}. bound_params (dict[str, Union[Any, Callable[[], Any]]], optional): A mapping of parameter names to their bound values. Defaults to {}. strict (bool, optional): If True, raises an error if *any* loaded tool instance fails to utilize all of the given parameters or auth tokens. Defaults to False. Returns: List[Function]: A list of all tools loaded from the specified toolsets. """ all_tools = [] for toolset_name in toolset_names: tools = await self.load_toolset( toolset_name=toolset_name, auth_token_getters=auth_token_getters, bound_params=bound_params, strict=strict, ) all_tools.extend(tools) return all_tools async def close(self): """Close the underlying asynchronous client.""" if self._core_client_initialized and hasattr(self, "_MCPToolbox__core_client"): await self.__core_client.close() await super().close() async def load_toolset_safe(self, toolset_name: str) -> List[str]: """Safely load a toolset and return tool names.""" try: tools = await self.load_toolset(toolset_name) return [tool.name for tool in tools] except Exception as e: raise RuntimeError(f"Failed to load toolset '{toolset_name}': {e}") from e def get_client(self) -> ToolboxClient: """Get the underlying ToolboxClient.""" if not self._core_client_initialized: raise RuntimeError("ToolboxClient not initialized. Call connect() first.") return self.__core_client async def __aenter__(self): """Initialize the direct toolbox client.""" await super().__aenter__() await self.connect() return self async def __aexit__(self, exc_type, exc_val, exc_tb): """Clean up the toolbox client.""" # Close ToolboxClient first, then MCP client if self._core_client_initialized and hasattr(self, "_MCPToolbox__core_client"): await self.__core_client.close() await super().__aexit__(exc_type, exc_val, exc_tb)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/tools/mcp_toolbox.py", "license": "Apache License 2.0", "lines": 245, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/tests/integration/teams/test_reasoning_content_default_COT.py
"""Test for reasoning_content generation in different Agent configurations. This test verifies that reasoning_content is properly populated in the RunOutput for various Agent configurations, including: - reasoning=True (with default model) - reasoning_model=specified model - streaming and non-streaming modes """ from textwrap import dedent import pytest from agno.models.openai import OpenAIChat from agno.team.team import Team @pytest.fixture(autouse=True) def _show_output(capfd): """Force pytest to show print output for all tests in this module.""" yield # Print captured output after test completes captured = capfd.readouterr() if captured.out: print(captured.out) if captured.err: print(captured.err) @pytest.mark.integration def test_reasoning_true_non_streaming(): """Test that reasoning_content is populated with reasoning=True in non-streaming mode.""" # Create an agent with reasoning=True team = Team( model=OpenAIChat(id="gpt-4o"), reasoning=True, members=[], instructions=dedent("""\ You are an expert problem-solving assistant with strong analytical skills! 🧠 Use step-by-step reasoning to solve the problem. \ """), ) # Run the agent in non-streaming mode response = team.run("What is the sum of the first 10 natural numbers?", stream=False) # Print the reasoning_content when received if hasattr(response, "reasoning_content") and response.reasoning_content: print("\n=== Default reasoning model (non-streaming) reasoning_content ===") print(response.reasoning_content) print("=========================================================\n") # Assert that reasoning_content exists and is populated assert hasattr(response, "reasoning_content"), "Response should have reasoning_content attribute" assert response.reasoning_content is not None, "reasoning_content should not be None" assert len(response.reasoning_content) > 0, "reasoning_content should not be empty" @pytest.mark.integration def test_reasoning_true_streaming(shared_db): """Test that reasoning_content is populated with reasoning=True in streaming mode.""" # Create an agent with reasoning=True team = Team( model=OpenAIChat(id="gpt-4o"), members=[], reasoning=True, db=shared_db, instructions=dedent("""\ You are an expert problem-solving assistant with strong analytical skills! 🧠 Use step-by-step reasoning to solve the problem. \ """), ) # Consume all streaming responses reasoning_content_found = False for event in team.run("What is the value of 5! (factorial)?", stream=True, stream_events=True): if hasattr(event, "reasoning_content"): reasoning_content_found = True assert reasoning_content_found, "reasoning_content should be found in the streaming responses" run_response = team.get_last_run_output() # Print the reasoning_content when received if run_response and hasattr(run_response, "reasoning_content") and run_response.reasoning_content: print("\n=== Default reasoning model (streaming) reasoning_content ===") print(run_response.reasoning_content) print("====================================================\n") # Check the agent's run_response directly after streaming is complete assert run_response is not None, "run_response should not be None" assert hasattr(run_response, "reasoning_content"), "Response should have reasoning_content attribute" assert run_response.reasoning_content is not None, "reasoning_content should not be None" assert len(run_response.reasoning_content) > 0, "reasoning_content should not be empty" @pytest.mark.integration def test_reasoning_model_non_streaming(): """Test that reasoning_content is populated with a specified reasoning_model in non-streaming mode.""" # Create an agent with a specified reasoning_model team = Team( model=OpenAIChat(id="gpt-4o"), reasoning_model=OpenAIChat(id="gpt-4o"), members=[], instructions=dedent("""\ You are an expert problem-solving assistant with strong analytical skills! 🧠 Use step-by-step reasoning to solve the problem. \ """), ) # Run the agent in non-streaming mode response = team.run("What is the sum of the first 10 natural numbers?", stream=False) # Print the reasoning_content when received if hasattr(response, "reasoning_content") and response.reasoning_content: print("\n=== Custom reasoning model (non-streaming) reasoning_content ===") print(response.reasoning_content) print("==========================================================\n") # Assert that reasoning_content exists and is populated assert hasattr(response, "reasoning_content"), "Response should have reasoning_content attribute" assert response.reasoning_content is not None, "reasoning_content should not be None" assert len(response.reasoning_content) > 0, "reasoning_content should not be empty" @pytest.mark.integration def test_reasoning_model_streaming(shared_db): """Test that reasoning_content is populated with a specified reasoning_model in streaming mode.""" # Create an agent with a specified reasoning_model team = Team( model=OpenAIChat(id="gpt-4o"), reasoning_model=OpenAIChat(id="gpt-4o"), db=shared_db, members=[], instructions=dedent("""\ You are an expert problem-solving assistant with strong analytical skills! 🧠 Use step-by-step reasoning to solve the problem. \ """), ) # Consume all streaming responses _ = list(team.run("What is the value of 5! (factorial)?", stream=True, stream_events=True)) run_response = team.get_last_run_output() # Print the reasoning_content when received if run_response and hasattr(run_response, "reasoning_content") and run_response.reasoning_content: print("\n=== Custom reasoning model (streaming) reasoning_content ===") print(run_response.reasoning_content) print("=====================================================\n") # Check the agent's run_response directly after streaming is complete assert run_response is not None, "Agent's run_response should not be None" assert hasattr(run_response, "reasoning_content"), "Response should have reasoning_content attribute" assert run_response.reasoning_content is not None, "reasoning_content should not be None" assert len(run_response.reasoning_content) > 0, "reasoning_content should not be empty"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/teams/test_reasoning_content_default_COT.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/unit/db/test_sessions.py
from agno.session.agent import AgentSession from agno.session.team import TeamSession def test_agent_session_serialization_empty_runs(): sess1 = AgentSession(session_id="s3", runs=[]) dump = sess1.to_dict() sess2 = AgentSession.from_dict(dump) assert sess1 == sess2 def test_team_session_serialization_empty_runs(): sess1 = TeamSession(session_id="s3", runs=[]) dump = sess1.to_dict() sess2 = TeamSession.from_dict(dump) assert sess1 == sess2
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/db/test_sessions.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/models/cometapi/cometapi.py
from dataclasses import dataclass, field from os import getenv from typing import Any, Dict, List, Optional import httpx from agno.exceptions import ModelAuthenticationError from agno.models.openai.like import OpenAILike from agno.utils.log import log_debug @dataclass class CometAPI(OpenAILike): """ The CometAPI class provides access to multiple AI model providers (GPT, Claude, Gemini, DeepSeek, etc.) through OpenAI-compatible endpoints. Args: id (str): The id of the CometAPI model to use. Default is "gpt-5-mini". name (str): The name for this model. Defaults to "CometAPI". api_key (str): The API key for CometAPI. Defaults to COMETAPI_KEY environment variable. base_url (str): The base URL for CometAPI. Defaults to "https://api.cometapi.com/v1". """ name: str = "CometAPI" id: str = "gpt-5-mini" api_key: Optional[str] = field(default_factory=lambda: getenv("COMETAPI_KEY")) base_url: str = "https://api.cometapi.com/v1" def _get_client_params(self) -> Dict[str, Any]: """ Returns client parameters for API requests, checking for COMETAPI_KEY. Returns: Dict[str, Any]: A dictionary of client parameters for API requests. """ if not self.api_key: self.api_key = getenv("COMETAPI_KEY") if not self.api_key: raise ModelAuthenticationError( message="COMETAPI_KEY not set. Please set the COMETAPI_KEY environment variable.", model_name=self.name, ) return super()._get_client_params() def get_available_models(self) -> List[str]: """ Fetch available chat models from CometAPI, filtering out non-chat models. Returns: List of available chat model IDs """ if not self.api_key: log_debug("No API key provided, returning empty model list") return [] try: with httpx.Client() as client: response = client.get( f"{self.base_url}/models", headers={"Authorization": f"Bearer {self.api_key}", "Accept": "application/json"}, timeout=30.0, ) response.raise_for_status() data = response.json() all_models = data.get("data", []) log_debug(f"Found {len(all_models)} total models") return sorted(all_models) except Exception as e: log_debug(f"Error fetching models from CometAPI: {e}") return []
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/models/cometapi/cometapi.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/tests/integration/models/cometapi/test_basic.py
"""Integration tests for CometAPI model provider.""" import pytest from pydantic import BaseModel, Field from agno.agent import Agent, RunOutput from agno.db.sqlite import SqliteDb from agno.models.cometapi import CometAPI def _assert_metrics(response: RunOutput): """Helper function to assert response metrics are valid.""" assert response.metrics is not None input_tokens = response.metrics.input_tokens output_tokens = response.metrics.output_tokens total_tokens = response.metrics.total_tokens assert input_tokens > 0 assert output_tokens > 0 assert total_tokens > 0 assert total_tokens == input_tokens + output_tokens def test_basic(): """Test basic chat functionality with CometAPI.""" agent = Agent(model=CometAPI(id="gpt-5-mini"), markdown=True, telemetry=False) # Test basic response generation response: RunOutput = agent.run("Share a 2 sentence horror story") assert response.content is not None assert response.messages is not None assert len(response.messages) == 3 assert [m.role for m in response.messages] == ["system", "user", "assistant"] _assert_metrics(response) def test_basic_stream(): """Test streaming response with CometAPI.""" agent = Agent(model=CometAPI(id="gpt-5-mini"), markdown=True, telemetry=False) response_stream = agent.run("Share a 2 sentence horror story", stream=True) # Verify it's an iterator assert hasattr(response_stream, "__iter__") responses = list(response_stream) assert len(responses) > 0 for response in responses: assert response.content is not None @pytest.mark.asyncio async def test_basic_async(): """Test async chat functionality with CometAPI.""" agent = Agent(model=CometAPI(id="gpt-5-mini"), markdown=True, telemetry=False) # Test async response generation response: RunOutput = await agent.arun("Share a 2 sentence horror story") assert response.content is not None assert response.messages is not None assert len(response.messages) == 3 assert [m.role for m in response.messages] == ["system", "user", "assistant"] _assert_metrics(response) @pytest.mark.asyncio async def test_basic_async_stream(): """Test async streaming response with CometAPI.""" agent = Agent(model=CometAPI(id="gpt-5-mini"), markdown=True, telemetry=False) response_stream = agent.arun("Share a 2 sentence horror story", stream=True) # Verify it's an async iterator assert hasattr(response_stream, "__aiter__") responses = [] async for response in response_stream: responses.append(response) assert response.content is not None assert len(responses) > 0 def test_structured_output(): """Test structured output with Pydantic models.""" class StoryElements(BaseModel): title: str = Field(..., description="Story title") genre: str = Field(..., description="Story genre") main_character: str = Field(..., description="Main character name") plot: str = Field(..., description="Brief plot summary") agent = Agent(model=CometAPI(id="gpt-5-mini"), output_schema=StoryElements, markdown=True, telemetry=False) response: RunOutput = agent.run("Create a short story about time travel") # Verify structured output assert isinstance(response.content, StoryElements) assert response.content.title is not None assert response.content.genre is not None assert response.content.main_character is not None assert response.content.plot is not None def test_with_memory(): """Test agent with memory storage.""" from agno.db.sqlite import SqliteDb db = SqliteDb(db_file="tmp/cometapi_agent_sessions.db") agent = Agent( model=CometAPI(id="gpt-5-mini"), db=db, session_id="test_session_123", add_history_to_context=True, telemetry=False, ) response: RunOutput = agent.run("Remember, my name is Alice.") assert response.content is not None # Test if agent can access session history response2: RunOutput = agent.run("What did I just tell you about my name?") assert response2.content is not None # The response should reference the previous conversation assert len(response2.messages) > 2 # Should have multiple messages in history def test_tool_usage(): """Test agent with Calculator tools.""" from agno.tools.calculator import CalculatorTools agent = Agent( model=CometAPI(id="gpt-5-mini"), tools=[CalculatorTools()], instructions="You are a helpful assistant. Always use the calculator tool for mathematical calculations.", telemetry=False, ) response: RunOutput = agent.run("Use the calculator to compute 15 + 27") assert response.content is not None assert "42" in response.content def test_different_models(): """Test CometAPI with different model IDs.""" model_ids = ["gpt-5-mini", "claude-sonnet-4-20250514", "gemini-2.5-flash-lite"] for model_id in model_ids: agent = Agent(model=CometAPI(id=model_id), telemetry=False) try: response: RunOutput = agent.run("Say hello in one sentence") assert response.content is not None assert len(response.content) > 0 except Exception as e: # Some models might not be available, that's ok for this test pytest.skip(f"Model {model_id} not available: {e}") def test_custom_base_url(): """Test CometAPI with custom base URL.""" agent = Agent( model=CometAPI( id="gpt-5-mini", base_url="https://api.cometapi.com/v1", # explicit base URL ), telemetry=False, ) response: RunOutput = agent.run("Hello, world!") assert response.content is not None _assert_metrics(response) def test_tool_usage_stream(): """Test agent with Calculator tools in streaming mode.""" from agno.tools.calculator import CalculatorTools agent = Agent( model=CometAPI(id="gpt-5-mini"), tools=[CalculatorTools()], instructions="You are a helpful assistant. Always use the calculator tool for mathematical calculations.", telemetry=False, ) response_stream = agent.run("Use the calculator to compute 25 * 4", stream=True) responses = list(response_stream) final_response = responses[-1] assert final_response.content is not None # Check if the calculation result is in the response full_content = "".join([r.content for r in responses if r.content]) assert "100" in full_content @pytest.mark.asyncio async def test_async_tool_usage(): """Test CometAPI with async tool usage.""" from agno.tools.calculator import CalculatorTools agent = Agent( model=CometAPI(id="gpt-5-mini"), tools=[CalculatorTools()], instructions="You are a helpful assistant. Always use the calculator tool for mathematical calculations.", telemetry=False, ) response: RunOutput = await agent.arun("Use the calculator to compute 12 * 8") assert response.content is not None assert response.messages is not None # Check if the calculation result is in the response assert "96" in response.content _assert_metrics(response) @pytest.mark.asyncio async def test_async_tool_usage_stream(): """Test CometAPI with async tool usage and streaming.""" from agno.tools.calculator import CalculatorTools agent = Agent( model=CometAPI(id="gpt-5-mini"), tools=[CalculatorTools()], instructions="You are a helpful assistant. Always use the calculator tool for mathematical calculations.", telemetry=False, ) response_stream = agent.arun("Use the calculator to compute 9 * 7", stream=True) # Verify it's an async iterator assert hasattr(response_stream, "__aiter__") responses = [] final_content = "" async for response in response_stream: responses.append(response) # Only check content if it exists (streaming events may not have content) if hasattr(response, "content") and response.content: final_content += response.content assert len(responses) > 0 # Check if the calculation result is in the final response assert "63" in final_content def test_image_analysis(): """Test CometAPI with image analysis capability.""" from agno.media import Image # Use a vision-capable model from CometAPI agent = Agent( model=CometAPI(id="gpt-4o"), # GPT-4o has vision capabilities markdown=True, telemetry=False, ) try: response: RunOutput = agent.run( "Describe what you see in this image briefly", images=[ Image( url="https://httpbin.org/image/png" # Use a reliable test image ) ], ) assert response.content is not None assert len(response.content) > 0 # Should mention it's an image or describe visual content assert any(keyword in response.content.lower() for keyword in ["image", "picture", "pig", "cartoon", "pink"]) _assert_metrics(response) except Exception as e: # Vision models might not be available, that's ok for this test pytest.skip(f"Vision model not available: {e}") def test_image_analysis_with_memory(): """Test CometAPI image analysis with memory storage.""" from agno.media import Image # Create a temporary database for testing db = SqliteDb(db_file="test_cometapi_image.db") agent = Agent( model=CometAPI(id="gpt-4o"), # GPT-4o has vision capabilities db=db, session_id="test_image_session_456", add_history_to_context=True, telemetry=False, ) try: # First interaction with an image response1: RunOutput = agent.run( "Look at this image and remember what you see", images=[ Image( url="https://httpbin.org/image/png" # Use a reliable test image ) ], ) assert response1.content is not None # Second interaction - should remember the image content response2: RunOutput = agent.run("What did you see in the image I showed you?") assert response2.content is not None # Should reference the previous image content assert any(keyword in response2.content.lower() for keyword in ["pig", "cartoon", "pink", "image", "showed"]) # Clean up try: import os if os.path.exists("test_cometapi_image.db"): os.remove("test_cometapi_image.db") except OSError: pass # Ignore cleanup errors except Exception as e: # Vision models might not be available, that's ok for this test pytest.skip(f"Vision model not available: {e}")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/models/cometapi/test_basic.py", "license": "Apache License 2.0", "lines": 247, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/integration/knowledge/filters/test_agentic_filtering.py
import tempfile from pathlib import Path import pytest from pydantic import BaseModel from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.knowledge.reader.csv_reader import CSVReader from agno.models.anthropic.claude import Claude from agno.models.google.gemini import Gemini from agno.models.openai.chat import OpenAIChat from agno.vectordb.lancedb import LanceDb # Sample CSV data to use in tests EMPLOYEE_CSV_DATA = """id,name,department,salary,years_experience 1,John Smith,Engineering,75000,5 2,Sarah Johnson,Marketing,65000,3 3,Michael Brown,Finance,85000,8 4,Jessica Lee,Engineering,80000,6 5,David Wilson,HR,55000,2 6,Emily Chen,Product,70000,4 7,Robert Miller,Engineering,90000,10 8,Amanda White,Marketing,60000,3 9,Thomas Garcia,Finance,82000,7 10,Lisa Thompson,Engineering,78000,5 """ # Updated CSV data to match the test expectations better SALES_CSV_DATA = """quarter,region,product,revenue,units_sold,data_type Q1,north_america,Laptop,128500,85,sales Q1,south_america,Laptop,95000,65,sales Q1,europe,Laptop,110200,75,sales Q1,asia,Laptop,142300,95,sales Q2,north_america,Laptop,138600,90,sales Q2,south_america,Laptop,105800,70,sales Q2,europe,Laptop,115000,78,sales Q2,asia,Laptop,155000,100,sales """ class CSVDataOutput(BaseModel): """Output schema for CSV data analysis.""" data_type: str region: str summary: str # More flexible field instead of specific quarter/year/currency @pytest.fixture def setup_csv_files(): """Create temporary CSV files for testing.""" with tempfile.TemporaryDirectory() as temp_dir: # Create the directory for CSV files data_dir = Path(temp_dir) / "csvs" data_dir.mkdir(parents=True, exist_ok=True) # Create employees.csv employee_path = data_dir / "employees.csv" with open(employee_path, "w") as f: f.write(EMPLOYEE_CSV_DATA) # Create sales.csv sales_path = data_dir / "sales.csv" with open(sales_path, "w") as f: f.write(SALES_CSV_DATA) yield temp_dir @pytest.fixture async def knowledge_base(setup_csv_files): # Use LanceDB instead of ChromaDB to avoid multiple filter issues vector_db = LanceDb(table_name="test_vectors", uri="tmp/lancedb") # Use the temporary directory with CSV files csv_dir = Path(setup_csv_files) / "csvs" print(f"Testing with CSV directory: {csv_dir}") # Create a knowledge base with the test CSV files knowledge = Knowledge( vector_db=vector_db, ) reader = CSVReader( chunk=False, ) await knowledge.ainsert( path=str(csv_dir), reader=reader, metadata={"data_type": "sales", "region": "north_america", "currency": "USD"}, ) return knowledge async def test_agentic_filtering_openai(knowledge_base): agent = Agent(model=OpenAIChat("gpt-4o-mini"), knowledge=knowledge_base, enable_agentic_knowledge_filters=True) response = await agent.arun( "Tell me about revenue performance and top selling products in the region north_america and data_type sales", markdown=True, ) found_tool = False assert response.tools is not None, "Response tools should not be None" for tool in response.tools: # Tool name may be search_knowledge_base or search_knowledge_base_with_filters if "search_knowledge_base" in tool.tool_name: # Filters may be passed as "filters" key or model may pass them differently if "filters" in tool.tool_args: filters = tool.tool_args["filters"] # Extract filter values for validation filter_dict = {} for f in filters: if isinstance(f, dict) and "key" in f and "value" in f: filter_dict[f["key"]] = f["value"] elif isinstance(f, dict): filter_dict.update(f) assert filter_dict.get("region") == "north_america" assert filter_dict.get("data_type") == "sales" found_tool = True break assert found_tool, "search_knowledge_base tool was not called" async def test_agentic_filtering_openai_with_output_schema(knowledge_base): """Test agentic filtering with structured output schema - this was the original issue.""" agent = Agent( model=OpenAIChat("gpt-4o-mini"), knowledge=knowledge_base, enable_agentic_knowledge_filters=True, output_schema=CSVDataOutput, ) response = await agent.arun( "Tell me about revenue performance and top selling products in the region north_america and data_type sales", markdown=True, ) found_tool = False assert response.tools is not None, "Response tools should not be None" for tool in response.tools: # Tool name may be search_knowledge_base or search_knowledge_base_with_filters if "search_knowledge_base" in tool.tool_name: # Filters may be passed as "filters" key or model may pass them differently if "filters" in tool.tool_args: filters = tool.tool_args["filters"] # Extract filter values for validation filter_dict = {} for f in filters: if isinstance(f, dict) and "key" in f and "value" in f: filter_dict[f["key"]] = f["value"] elif isinstance(f, dict): filter_dict.update(f) assert filter_dict.get("region") == "north_america" assert filter_dict.get("data_type") == "sales" found_tool = True break assert found_tool, "search_knowledge_base tool was not called" assert response.content is not None, "Response content should not be None" assert isinstance(response.content, CSVDataOutput), f"Expected CSVDataOutput, got {type(response.content)}" assert response.content.data_type == "sales" assert "north" in response.content.region.lower() or "america" in response.content.region.lower() assert response.content.summary is not None async def test_agentic_filtering_gemini(knowledge_base): agent = Agent(model=Gemini("gemini-2.0-flash-001"), knowledge=knowledge_base, enable_agentic_knowledge_filters=True) response = await agent.arun( "Tell me about revenue performance and top selling products in the region north_america and data_type sales", markdown=True, ) found_tool = False assert response.tools is not None, "Response tools should not be None" for tool in response.tools: # Tool name may be search_knowledge_base or search_knowledge_base_with_filters if "search_knowledge_base" in tool.tool_name: # Filters may be passed as "filters" key or model may pass them differently if "filters" in tool.tool_args: filters = tool.tool_args["filters"] # Extract filter values for validation filter_dict = {} for f in filters: if isinstance(f, dict) and "key" in f and "value" in f: filter_dict[f["key"]] = f["value"] elif isinstance(f, dict): filter_dict.update(f) assert filter_dict.get("region") == "north_america" assert filter_dict.get("data_type") == "sales" found_tool = True break assert found_tool, "search_knowledge_base tool was not called" async def test_agentic_filtering_claude(knowledge_base): agent = Agent(model=Claude("claude-sonnet-4-0"), knowledge=knowledge_base, enable_agentic_knowledge_filters=True) response = await agent.arun( "Tell me about revenue performance and top selling products in the region north_america and data_type sales", markdown=True, ) found_tool = False assert response.tools is not None, "Response tools should not be None" for tool in response.tools: # Tool name may be search_knowledge_base or search_knowledge_base_with_filters if "search_knowledge_base" in tool.tool_name: # Filters may be passed as "filters" key or model may pass them differently if "filters" in tool.tool_args: filters = tool.tool_args["filters"] # Extract filter values for validation filter_dict = {} for f in filters: if isinstance(f, dict) and "key" in f and "value" in f: filter_dict[f["key"]] = f["value"] elif isinstance(f, dict): filter_dict.update(f) assert filter_dict.get("region") == "north_america" assert filter_dict.get("data_type") == "sales" found_tool = True break assert found_tool, "search_knowledge_base tool was not called"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/knowledge/filters/test_agentic_filtering.py", "license": "Apache License 2.0", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/models/llama_cpp/llama_cpp.py
from dataclasses import dataclass from agno.models.openai.like import OpenAILike @dataclass class LlamaCpp(OpenAILike): """ A class for interacting with LLMs using Llama CPP. Attributes: id (str): The id of the Llama CPP model. Default is "ggml-org/gpt-oss-20b-GGUF". name (str): The name of this chat model instance. Default is "LlamaCpp". provider (str): The provider of the model. Default is "LlamaCpp". base_url (str): The base url to which the requests are sent. """ id: str = "ggml-org/gpt-oss-20b-GGUF" name: str = "LlamaCpp" provider: str = "LlamaCpp" base_url: str = "http://127.0.0.1:8080/v1"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/models/llama_cpp/llama_cpp.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:libs/agno/tests/integration/os/test_custom_fastapi_app.py
"""Integration tests for custom FastAPI app scenarios with AgentOS.""" from contextlib import asynccontextmanager from unittest.mock import Mock, patch import pytest from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient from starlette.middleware.cors import CORSMiddleware from agno.agent.agent import Agent from agno.db.in_memory import InMemoryDb from agno.os import AgentOS from agno.team.team import Team from agno.tools.mcp import MCPTools from agno.workflow.workflow import Workflow @pytest.fixture def test_agent(): """Create a test agent.""" return Agent(name="test-agent", db=InMemoryDb()) @pytest.fixture def test_team(test_agent: Agent): """Create a test team.""" return Team(name="test-team", members=[test_agent]) @pytest.fixture def test_workflow(): """Create a test workflow.""" return Workflow(name="test-workflow") def test_custom_app_with_cors_middleware(test_agent: Agent): """Test that custom CORS middleware is properly handled by AgentOS.""" # Create custom FastAPI app with CORS middleware custom_app = FastAPI(title="Custom App") custom_app.add_middleware( CORSMiddleware, allow_origins=["https://custom.example.com", "http://localhost:3000"], allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["X-Custom-Header"], ) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Ensure the app is running response = client.get( "/health", headers={"Origin": "https://custom.example.com", "Access-Control-Request-Method": "GET"} ) assert response.status_code == 200 # Check that CORS headers are present in response # Note: header names can be case-insensitive, so check both variants cors_headers = {k.lower(): v for k, v in response.headers.items()} assert "access-control-allow-origin" in cors_headers # Verify CORS middleware exists (AgentOS replaces custom CORS middleware) cors_middleware = None for middleware in app.user_middleware: if middleware.cls == CORSMiddleware: cors_middleware = middleware break assert cors_middleware is not None # AgentOS update_cors_middleware merges origins from custom middleware origins = cors_middleware.kwargs.get("allow_origins", []) assert len(origins) > 0 # Should include the custom origin that was merged assert any("custom.example.com" in origin for origin in origins) def test_cors_middleware_configuration_only(test_agent: Agent): """Test CORS middleware configuration without relying on OPTIONS requests.""" # Create custom FastAPI app with CORS middleware custom_app = FastAPI(title="Custom App") custom_app.add_middleware( CORSMiddleware, allow_origins=["https://custom.example.com"], allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["X-Custom-Header"], ) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() # Verify CORS middleware configuration after AgentOS processing cors_middleware = None for middleware in app.user_middleware: if middleware.cls == CORSMiddleware: cors_middleware = middleware break assert cors_middleware is not None # AgentOS update_cors_middleware should have changed the configuration kwargs = cors_middleware.kwargs assert "allow_origins" in kwargs assert "allow_methods" in kwargs assert "allow_headers" in kwargs # AgentOS sets allow_methods to ["*"] which includes OPTIONS methods = kwargs.get("allow_methods", []) assert methods == ["*"] or "OPTIONS" in methods # Origins should be preserved or merged origins = kwargs.get("allow_origins", []) assert any("custom.example.com" in origin for origin in origins) def test_options_request_with_explicit_handler(test_agent: Agent): """Test OPTIONS requests with an explicit handler - explains why basic OPTIONS fail.""" # Create custom FastAPI app with explicit OPTIONS handler custom_app = FastAPI(title="Custom App") # Add explicit OPTIONS handler for testing @custom_app.options("/test-endpoint") async def options_handler(): return {"message": "options ok"} @custom_app.get("/test-endpoint") async def test_endpoint(): return {"message": "get ok"} custom_app.add_middleware( CORSMiddleware, allow_origins=["https://custom.example.com"], allow_credentials=True, allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"], ) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # This should work because we have an explicit OPTIONS handler response = client.options("/test-endpoint") assert response.status_code == 200 # Regular request should also work response = client.get("/test-endpoint") assert response.status_code == 200 # OPTIONS on /health will still fail because AgentOS health endpoint # doesn't define an OPTIONS handler, and CORS middleware alone # doesn't automatically add OPTIONS support to all endpoints def test_custom_app_endpoints_preserved(test_agent: Agent): """Test that custom endpoints are preserved alongside AgentOS endpoints.""" # Create custom FastAPI app with custom routes custom_app = FastAPI(title="Custom App") @custom_app.get("/custom") async def custom_endpoint(): return {"message": "custom endpoint"} @custom_app.post("/customers") async def get_customers(): return [ {"id": 1, "name": "John Doe", "email": "john@example.com"}, {"id": 2, "name": "Jane Doe", "email": "jane@example.com"}, ] # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Test custom endpoints work response = client.get("/custom") assert response.status_code == 200 assert response.json() == {"message": "custom endpoint"} response = client.post("/customers") assert response.status_code == 200 data = response.json() assert len(data) == 2 assert data[0]["name"] == "John Doe" # Test AgentOS endpoints still work response = client.get("/health") assert response.status_code == 200 assert response.json()["status"] == "ok" response = client.get("/") assert response.status_code == 200 data = response.json() assert "name" in data assert "AgentOS API" in data["name"] def test_custom_lifespan_integration(test_agent: Agent): """Test custom lifespan context manager integration.""" startup_called = False shutdown_called = False @asynccontextmanager async def custom_lifespan(app): nonlocal startup_called, shutdown_called startup_called = True yield shutdown_called = True # Create AgentOS with custom lifespan agent_os = AgentOS( agents=[test_agent], lifespan=custom_lifespan, ) app = agent_os.get_app() # Test that the lifespan is properly configured assert app.router.lifespan_context is not None # Create test client to trigger lifespan events with TestClient(app) as client: # Basic test to ensure app is working response = client.get("/health") assert response.status_code == 200 # Note: TestClient automatically calls lifespan events assert startup_called is True assert shutdown_called is True def test_custom_app_middleware_preservation(test_agent: Agent): """Test that custom middleware is preserved when using custom FastAPI app.""" custom_middleware_called = False async def custom_middleware(request, call_next): nonlocal custom_middleware_called custom_middleware_called = True response = await call_next(request) response.headers["X-Custom-Header"] = "present" return response # Create custom FastAPI app with middleware custom_app = FastAPI(title="Custom App") custom_app.middleware("http")(custom_middleware) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Test that custom middleware is called response = client.get("/health") assert response.status_code == 200 assert custom_middleware_called is True assert response.headers["X-Custom-Header"] == "present" def test_available_endpoints_with_custom_app(test_agent: Agent, test_team: Team, test_workflow: Workflow): """Test that all expected AgentOS endpoints are available with custom app.""" # Create custom FastAPI app custom_app = FastAPI(title="Custom App") @custom_app.get("/custom") async def custom_endpoint(): return {"message": "custom"} # Setup AgentOS with custom app agent_os = AgentOS( agents=[test_agent], teams=[test_team], workflows=[test_workflow], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Test core endpoints response = client.get("/health") assert response.status_code == 200 response = client.get("/") assert response.status_code == 200 # Test custom endpoint still works response = client.get("/custom") assert response.status_code == 200 assert response.json()["message"] == "custom" # Test sessions endpoint (should be available) response = client.get("/sessions") assert response.status_code != 404 def test_route_listing_with_custom_app(test_agent: Agent): """Test that get_routes() returns all routes including custom ones.""" # Create custom FastAPI app custom_app = FastAPI(title="Custom App") @custom_app.get("/custom") async def custom_endpoint(): return {"message": "custom"} @custom_app.post("/custom-post") async def custom_post(): return {"result": "posted"} # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) routes = agent_os.get_routes() # Convert routes to paths for easier testing route_paths = [] route_methods = [] for route in routes: if hasattr(route, "path"): route_paths.append(route.path) if hasattr(route, "methods"): route_methods.extend(list(route.methods)) # Check that both custom and AgentOS routes are present assert "/custom" in route_paths assert "/custom-post" in route_paths assert "/health" in route_paths assert "/" in route_paths # Check methods assert "GET" in route_methods assert "POST" in route_methods def test_cors_origin_merging(test_agent: Agent): """Test CORS origin merging between custom app and AgentOS settings.""" # Create custom FastAPI app with CORS custom_app = FastAPI() custom_app.add_middleware( CORSMiddleware, allow_origins=["https://custom.com"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Mock AgentOS settings with different origins with patch("agno.os.app.AgnoAPISettings") as mock_settings_class: mock_settings = Mock() mock_settings.docs_enabled = True mock_settings.cors_origin_list = ["https://agno.com", "http://localhost:3000"] mock_settings_class.return_value = mock_settings # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, settings=mock_settings, ) app = agent_os.get_app() # Check that CORS middleware exists and has merged origins cors_middleware = None for middleware in app.user_middleware: if middleware.cls == CORSMiddleware: cors_middleware = middleware break assert cors_middleware is not None origins = cors_middleware.kwargs.get("allow_origins", []) # Should contain origins from both custom app and settings # Exact merging behavior depends on implementation assert set(origins) == set(["https://agno.com", "http://localhost:3000", "https://custom.com"]) def test_exception_handling_with_custom_app(test_agent: Agent): """Test that exception handling works properly with custom FastAPI app.""" # Create custom FastAPI app custom_app = FastAPI() @custom_app.get("/error") async def error_endpoint(): raise HTTPException(status_code=400, detail="Custom error") # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Test custom error endpoint response = client.get("/error") assert response.status_code == 400 assert "Custom error" in response.json()["detail"] # Test AgentOS endpoints still handle errors properly response = client.get("/nonexistent") assert response.status_code == 404 def test_custom_app_docs_configuration(test_agent: Agent): """Test that API docs configuration is preserved with custom FastAPI app.""" # Create custom FastAPI app with custom docs settings custom_app = FastAPI( title="Custom API", version="2.0.0", description="Custom API Description", docs_url="/custom-docs", redoc_url="/custom-redoc", ) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Test custom docs endpoints response = client.get("/custom-docs") assert response.status_code == 200 response = client.get("/custom-redoc") assert response.status_code == 200 # Check that app metadata is preserved assert app.title == "Custom API" assert app.version == "2.0.0" assert app.description == "Custom API Description" def test_multiple_middleware_interaction(test_agent: Agent): """Test interaction between custom middleware and AgentOS middleware.""" middleware_call_order = [] async def first_middleware(request, call_next): middleware_call_order.append("first") response = await call_next(request) response.headers["X-First"] = "first" return response async def second_middleware(request, call_next): middleware_call_order.append("second") response = await call_next(request) response.headers["X-Second"] = "second" return response # Create custom FastAPI app with multiple middleware custom_app = FastAPI() custom_app.middleware("http")(first_middleware) custom_app.middleware("http")(second_middleware) # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, ) app = agent_os.get_app() client = TestClient(app) # Clear call order for test middleware_call_order.clear() # Test request response = client.get("/health") assert response.status_code == 200 # Check middleware was called assert len(middleware_call_order) > 0 # Check headers from middleware assert "X-First" in response.headers assert "X-Second" in response.headers # Additional Route Conflict Tests def test_multiple_conflicting_routes_preserve_agentos(test_agent: Agent): """Test multiple conflicting routes when on_route_conflict="preserve_agentos".""" # Create custom FastAPI app with multiple conflicting routes custom_app = FastAPI(title="Custom App") @custom_app.get("/") async def custom_home(): return {"message": "custom home"} @custom_app.get("/health") async def custom_health(): return {"status": "custom_ok"} @custom_app.get("/sessions") async def custom_sessions(): return {"sessions": ["custom_session1", "custom_session2"]} # Create AgentOS with custom app (on_route_conflict="preserve_agentos" by default) agent_os = AgentOS( agents=[test_agent], base_app=custom_app, on_route_conflict="preserve_agentos", ) app = agent_os.get_app() client = TestClient(app) # All AgentOS routes should override custom routes response = client.get("/health") assert response.status_code == 200 assert response.json()["status"] == "ok" # AgentOS health endpoint response = client.get("/") assert response.status_code == 200 data = response.json() assert "name" in data # AgentOS home endpoint assert "AgentOS API" in data["name"] response = client.get("/sessions") assert response.status_code == 200 # Should be AgentOS sessions endpoint, not custom def test_multiple_conflicting_routes_preserve_base_app(test_agent: Agent): """Test multiple conflicting routes when on_route_conflict="preserve_base_app".""" # Create custom FastAPI app with multiple conflicting routes custom_app = FastAPI(title="Custom App") @custom_app.get("/") async def custom_home(): return {"message": "custom home"} @custom_app.get("/health") async def custom_health(): return {"status": "custom_ok"} @custom_app.get("/sessions") async def custom_sessions(): return {"sessions": ["custom_session1", "custom_session2"]} # Create AgentOS with custom app and on_route_conflict="preserve_base_app" agent_os = AgentOS( agents=[test_agent], base_app=custom_app, on_route_conflict="preserve_base_app", ) app = agent_os.get_app() client = TestClient(app) # All custom routes should be preserved response = client.get("/health") assert response.status_code == 200 assert response.json()["status"] == "custom_ok" # Custom health endpoint response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "custom home"} # Custom home endpoint response = client.get("/sessions") assert response.status_code == 200 sessions = response.json()["sessions"] assert "custom_session1" in sessions # Custom sessions endpoint def test_http_method_conflicts(test_agent: Agent): """Test conflicts with different HTTP methods on same path.""" # Create custom FastAPI app with different methods on conflicting paths custom_app = FastAPI(title="Custom App") @custom_app.get("/health") async def custom_health_get(): return {"status": "custom_get"} @custom_app.post("/health") async def custom_health_post(): return {"status": "custom_post"} @custom_app.put("/health") async def custom_health_put(): return {"status": "custom_put"} # Create AgentOS with custom app agent_os = AgentOS( agents=[test_agent], base_app=custom_app, on_route_conflict="preserve_agentos", ) app = agent_os.get_app() client = TestClient(app) # GET should be replaced by AgentOS response = client.get("/health") assert response.status_code == 200 assert response.json()["status"] == "ok" # AgentOS health endpoint # POST and PUT should remain custom since AgentOS health is only GET response = client.post("/health") assert response.status_code == 200 assert response.json()["status"] == "custom_post" response = client.put("/health") assert response.status_code == 200 assert response.json()["status"] == "custom_put" def test_complex_route_conflict_scenario(test_agent: Agent, test_team: Team, test_workflow: Workflow): """Test complex scenario with multiple types of route conflicts.""" # Create custom FastAPI app with various conflicting routes custom_app = FastAPI(title="Complex Custom App") # Root level conflicts @custom_app.get("/") async def custom_root(): return {"app": "custom", "version": "1.0"} @custom_app.get("/health") async def custom_health(): return {"status": "custom_healthy"} # Agent conflicts with different methods @custom_app.get("/agents") async def custom_agents_list(): return {"agents": ["custom1", "custom2"]} @custom_app.post("/agents") async def custom_agents_create(): return {"created": "custom_agent"} # Team conflicts @custom_app.get("/teams") async def custom_teams(): return {"teams": ["custom_team"]} # Workflow conflicts @custom_app.get("/workflows") async def custom_workflows(): return {"workflows": ["custom_workflow"]} # Mixed parameterized conflicts @custom_app.get("/agents/{agent_name}/status") async def custom_agent_status(agent_name: str): return {"agent": agent_name, "status": "custom_active"} # Non-conflicting routes @custom_app.get("/custom-only") async def custom_only(): return {"message": "this should always work"} # Test with on_route_conflict=True agent_os = AgentOS( agents=[test_agent], teams=[test_team], workflows=[test_workflow], base_app=custom_app, on_route_conflict="preserve_agentos", ) app = agent_os.get_app() client = TestClient(app) # AgentOS should override conflicting GET routes response = client.get("/") assert response.status_code == 200 data = response.json() assert "AgentOS" in str(data) or "name" in data # AgentOS format response = client.get("/health") assert response.status_code == 200 assert response.json()["status"] == "ok" # AgentOS health # Non-conflicting custom routes should work response = client.get("/custom-only") assert response.status_code == 200 assert response.json()["message"] == "this should always work" # Test POST agents (might not conflict if AgentOS doesn't have POST /agents) response = client.post("/agents") # Should either work (custom) or have specific AgentOS behavior assert response.status_code != 404 def test_custom_app_with_mcp_tools_lifespan(test_agent: Agent): """Test that MCP tools work correctly with a custom base_app.""" base_app_startup_called = False base_app_shutdown_called = False mcp_connect_called = False mcp_close_called = False @asynccontextmanager async def base_app_lifespan(app): nonlocal base_app_startup_called, base_app_shutdown_called base_app_startup_called = True yield base_app_shutdown_called = True # Setup custom FastAPI app with custom lifespan custom_app = FastAPI(title="Custom App", lifespan=base_app_lifespan) # Setup MCP tools with mocked connect/close methods mcp_tools = MCPTools("npm fake-command") async def mock_connect(): nonlocal mcp_connect_called mcp_connect_called = True async def mock_close(): nonlocal mcp_close_called mcp_close_called = True mcp_tools.connect = mock_connect mcp_tools.close = mock_close # Setup agent with MCP tools agent = Agent(name="mcp-test-agent", tools=[mcp_tools], db=InMemoryDb()) # Setup AgentOS with custom base_app agent_os = AgentOS( agents=[agent], base_app=custom_app, ) # Verify MCP tools were registered assert len(agent_os.mcp_tools) == 1 assert agent_os.mcp_tools[0] is mcp_tools app = agent_os.get_app() # Verify lifespans were properly combined assert app.router.lifespan_context is not None # Ensure the app is running and lifespans are called with TestClient(app) as client: response = client.get("/health") assert response.status_code == 200 # Verify the agent has access to MCP tools through the API # Get the agent from the OS to check its tools os_agent = agent_os.agents[0] assert os_agent.tools is not None assert len(os_agent.tools) == 1 assert os_agent.tools[0] is mcp_tools # Verify agent endpoint is accessible and shows agent with tools response = client.get(f"/agents/{os_agent.id}") assert response.status_code == 200 agent_data = response.json() assert agent_data["name"] == "mcp-test-agent" # Agent should have tools configured (tools field should be present and non-empty) assert "tools" in agent_data assert agent_data["tools"] is not None assert base_app_startup_called is True assert base_app_shutdown_called is True assert mcp_connect_called is True assert mcp_close_called is True def test_custom_app_with_enable_mcp_server(): """Test that enable_mcp_server=True works with a custom base_app. Note: This test requires a compatible version of fastmcp that exports fastmcp.server.http.StarletteWithLifespan. If this import fails, it indicates a version mismatch that needs to be resolved in agno/os/mcp.py. """ # Setup lifespan events base_app_startup_called = False base_app_shutdown_called = False @asynccontextmanager async def base_app_lifespan(app): nonlocal base_app_startup_called, base_app_shutdown_called base_app_startup_called = True yield base_app_shutdown_called = True # Setup custom FastAPI app with custom lifespan custom_app = FastAPI(title="Custom App with MCP Server", lifespan=base_app_lifespan) # Setup a simple agent agent = Agent(name="test-agent", db=InMemoryDb()) # Setup AgentOS with enable_mcp_server=True and custom base_app agent_os = AgentOS( agents=[agent], base_app=custom_app, enable_mcp_server=True, ) app = agent_os.get_app() # Verify MCP server was initialized and lifespans were combined assert agent_os._mcp_app is not None assert app.router.lifespan_context is not None # Verify MCP server is mounted by checking the app's routes mcp_mounted = False for route in app.routes: if hasattr(route, "app") and route.app == agent_os._mcp_app: # type: ignore mcp_mounted = True break assert mcp_mounted, "MCP server should be mounted to the base_app" # Ensure the app is running and lifespans were called with TestClient(app) as client: response = client.get("/health") assert response.status_code == 200 assert base_app_startup_called is True assert base_app_shutdown_called is True def test_custom_health_endpoint(): """Test that the custom health endpoint works.""" from fastapi import FastAPI from fastapi.testclient import TestClient from agno.agent import Agent from agno.os.routers.health import get_health_router app = FastAPI(title="Custom App") health_router = get_health_router(health_endpoint="/health-check") app.include_router(health_router) agent_os = AgentOS(agents=[Agent()], base_app=app) app = agent_os.get_app() client = TestClient(app) response = client.get("/health-check") assert response.status_code == 200 assert response.json()["status"] == "ok"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/os/test_custom_fastapi_app.py", "license": "Apache License 2.0", "lines": 671, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/unit/knowledge/chunking/test_semantic_chunking.py
"""Tests for SemanticChunking wrapper that adapts Agno embedders to chonkie.""" from dataclasses import dataclass from types import SimpleNamespace from typing import List from unittest.mock import patch import pytest from agno.knowledge.chunking.semantic import SemanticChunking from agno.knowledge.document.base import Document from agno.knowledge.embedder.base import Embedder @dataclass class DummyEmbedder(Embedder): """Minimal embedder stub for testing.""" id: str = "azure-embedding-deployment" dimensions: int = 1024 def get_embedding(self, text: str) -> List[float]: return [0.0] * self.dimensions @pytest.fixture def fake_chonkie_capturing(): """Fixture that patches SemanticChunker and captures init kwargs.""" captured = {} class FakeSemanticChunker: def __init__(self, **kwargs): captured.update(kwargs) def chunk(self, text: str): return [SimpleNamespace(text=text)] with patch("agno.knowledge.chunking.semantic.SemanticChunker", FakeSemanticChunker): yield captured def test_semantic_chunking_wraps_embedder(fake_chonkie_capturing): """Test that SemanticChunking wraps embedder and passes to chonkie.""" embedder = DummyEmbedder(id="azure-deploy", dimensions=1536) sc = SemanticChunking(embedder=embedder, chunk_size=123, similarity_threshold=0.7) _ = sc.chunk(Document(content="Hello world")) wrapper = fake_chonkie_capturing["embedding_model"] assert wrapper is not None assert hasattr(wrapper, "_embedder") assert wrapper._embedder is embedder assert fake_chonkie_capturing["chunk_size"] == 123 assert abs(fake_chonkie_capturing["threshold"] - 0.7) < 1e-9 def test_semantic_chunking_wrapper_calls_embedder(fake_chonkie_capturing): """Test that wrapper's embed method calls the Agno embedder.""" call_log: List[str] = [] @dataclass class TrackingEmbedder(Embedder): dimensions: int = 1536 def get_embedding(self, text: str) -> List[float]: call_log.append(text) return [0.1] * self.dimensions embedder = TrackingEmbedder() sc = SemanticChunking(embedder=embedder, chunk_size=500) _ = sc.chunk(Document(content="Test content")) wrapper = fake_chonkie_capturing["embedding_model"] result = wrapper.embed("test text") assert "test text" in call_log assert len(result) == 1536 def test_semantic_chunking_wrapper_dimension(fake_chonkie_capturing): """Test that wrapper exposes correct dimension from embedder.""" embedder = DummyEmbedder(id="test", dimensions=768) sc = SemanticChunking(embedder=embedder) _ = sc.chunk(Document(content="Test")) wrapper = fake_chonkie_capturing["embedding_model"] assert wrapper.dimension == 768 def test_semantic_chunking_passes_all_parameters(fake_chonkie_capturing): """Test that all SemanticChunking params are passed to chonkie.""" embedder = DummyEmbedder() sc = SemanticChunking( embedder=embedder, chunk_size=500, similarity_threshold=0.6, similarity_window=5, min_sentences_per_chunk=2, min_characters_per_sentence=30, delimiters=[". ", "! "], include_delimiters="next", skip_window=1, filter_window=7, filter_polyorder=2, filter_tolerance=0.3, ) _ = sc.chunk(Document(content="Test")) assert fake_chonkie_capturing["chunk_size"] == 500 assert abs(fake_chonkie_capturing["threshold"] - 0.6) < 1e-9 assert fake_chonkie_capturing["similarity_window"] == 5 assert fake_chonkie_capturing["min_sentences_per_chunk"] == 2 assert fake_chonkie_capturing["min_characters_per_sentence"] == 30 assert fake_chonkie_capturing["delim"] == [". ", "! "] assert fake_chonkie_capturing["include_delim"] == "next" assert fake_chonkie_capturing["skip_window"] == 1 assert fake_chonkie_capturing["filter_window"] == 7 assert fake_chonkie_capturing["filter_polyorder"] == 2 assert abs(fake_chonkie_capturing["filter_tolerance"] - 0.3) < 1e-9 def test_semantic_chunking_default_embedder(): """Test that OpenAIEmbedder is used when no embedder provided.""" sc = SemanticChunking(chunk_size=100) assert sc.embedder is not None assert "OpenAIEmbedder" in type(sc.embedder).__name__ def test_semantic_chunking_chunker_params(fake_chonkie_capturing): """Test that chunker_params are passed through to chonkie.""" embedder = DummyEmbedder() sc = SemanticChunking( embedder=embedder, chunk_size=500, chunker_params={"future_param": "value", "another_param": 42}, ) _ = sc.chunk(Document(content="Test")) assert fake_chonkie_capturing["chunk_size"] == 500 assert fake_chonkie_capturing["future_param"] == "value" assert fake_chonkie_capturing["another_param"] == 42 def test_semantic_chunking_chunker_params_override(fake_chonkie_capturing): """Test that chunker_params can override default params.""" embedder = DummyEmbedder() sc = SemanticChunking( embedder=embedder, chunk_size=500, similarity_window=3, # default chunker_params={"similarity_window": 10}, # override ) _ = sc.chunk(Document(content="Test")) assert fake_chonkie_capturing["similarity_window"] == 10 def test_semantic_chunking_string_embedder_passed_directly(fake_chonkie_capturing): """Test that string embedder is passed directly to chonkie without wrapping.""" sc = SemanticChunking(embedder="text-embedding-3-small", chunk_size=100) _ = sc.chunk(Document(content="Test")) assert fake_chonkie_capturing["embedding_model"] == "text-embedding-3-small" assert isinstance(fake_chonkie_capturing["embedding_model"], str) def test_semantic_chunking_base_embeddings_not_wrapped(fake_chonkie_capturing): """Test that BaseEmbeddings subclass is passed directly without wrapping.""" import numpy as np from chonkie.embeddings.base import BaseEmbeddings class CustomChonkieEmbedder(BaseEmbeddings): def embed(self, text: str): return np.zeros(768, dtype=np.float32) @property def dimension(self): return 768 def get_tokenizer(self): return lambda x: len(x.split()) custom_embedder = CustomChonkieEmbedder() sc = SemanticChunking(embedder=custom_embedder, chunk_size=100) _ = sc.chunk(Document(content="Test")) # Should be the same object, not wrapped assert fake_chonkie_capturing["embedding_model"] is custom_embedder assert not hasattr(fake_chonkie_capturing["embedding_model"], "_embedder") def test_semantic_chunking_wrapper_dtype_float32(fake_chonkie_capturing): """Test that wrapper.embed() returns numpy array with float32 dtype.""" import numpy as np embedder = DummyEmbedder(dimensions=1536) sc = SemanticChunking(embedder=embedder, chunk_size=100) _ = sc.chunk(Document(content="Test")) wrapper = fake_chonkie_capturing["embedding_model"] result = wrapper.embed("test text") assert isinstance(result, np.ndarray) assert result.dtype == np.float32
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/knowledge/chunking/test_semantic_chunking.py", "license": "Apache License 2.0", "lines": 152, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/models/nexus/nexus.py
from dataclasses import dataclass from agno.models.openai.like import OpenAILike @dataclass class Nexus(OpenAILike): """ A class for interacting with LLMs using Nexus. Attributes: id (str): The id of the Nexus model to use. Default is "openai/gpt-4". name (str): The name of this chat model instance. Default is "Nexus" provider (str): The provider of the model. Default is "Nexus". base_url (str): The base url to which the requests are sent. """ id: str = "openai/gpt-4" name: str = "Nexus" provider: str = "Nexus" base_url: str = "http://localhost:8000/llm/v1/"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/models/nexus/nexus.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:libs/agno/agno/tools/file_generation.py
import csv import io import json from pathlib import Path from typing import Any, Dict, List, Optional, Union from uuid import uuid4 from agno.media import File from agno.tools import Toolkit from agno.tools.function import ToolResult from agno.utils.log import log_debug, logger try: from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer PDF_AVAILABLE = True except ImportError: PDF_AVAILABLE = False logger.warning("reportlab not installed. PDF generation will not be available. Install with: pip install reportlab") class FileGenerationTools(Toolkit): def __init__( self, enable_json_generation: bool = True, enable_csv_generation: bool = True, enable_pdf_generation: bool = True, enable_txt_generation: bool = True, output_directory: Optional[str] = None, all: bool = False, **kwargs, ): self.enable_json_generation = enable_json_generation self.enable_csv_generation = enable_csv_generation self.enable_pdf_generation = enable_pdf_generation and PDF_AVAILABLE self.enable_txt_generation = enable_txt_generation self.output_directory = Path(output_directory) if output_directory else None # Create output directory if specified if self.output_directory: self.output_directory.mkdir(parents=True, exist_ok=True) log_debug(f"Files will be saved to: {self.output_directory}") if enable_pdf_generation and not PDF_AVAILABLE: logger.warning("PDF generation requested but reportlab is not installed. Disabling PDF generation.") self.enable_pdf_generation = False tools: List[Any] = [] if all or enable_json_generation: tools.append(self.generate_json_file) if all or enable_csv_generation: tools.append(self.generate_csv_file) if all or (enable_pdf_generation and PDF_AVAILABLE): tools.append(self.generate_pdf_file) if all or enable_txt_generation: tools.append(self.generate_text_file) super().__init__(name="file_generation", tools=tools, **kwargs) def _save_file_to_disk(self, content: Union[str, bytes], filename: str) -> Optional[str]: """Save file to disk if output_directory is set. Return file path or None.""" if not self.output_directory: return None file_path = self.output_directory / filename if isinstance(content, str): file_path.write_text(content, encoding="utf-8") else: file_path.write_bytes(content) log_debug(f"File saved to: {file_path}") return str(file_path) def generate_json_file(self, data: Union[Dict, List, str], filename: Optional[str] = None) -> ToolResult: """Generate a JSON file from the provided data. Args: data: The data to write to the JSON file. Can be a dictionary, list, or JSON string. filename: Optional filename for the generated file. If not provided, a UUID will be used. Returns: ToolResult: Result containing the generated JSON file as a FileArtifact. """ try: log_debug(f"Generating JSON file with data: {type(data)}") # Handle different input types if isinstance(data, str): try: json.loads(data) json_content = data # Use the original string if it's valid JSON except json.JSONDecodeError: # If it's not valid JSON, treat as plain text and wrap it json_content = json.dumps({"content": data}, indent=2) else: json_content = json.dumps(data, indent=2, ensure_ascii=False) # Generate filename if not provided if not filename: filename = f"generated_file_{str(uuid4())[:8]}.json" elif not filename.endswith(".json"): filename += ".json" # Save file to disk (if output_directory is set) file_path = self._save_file_to_disk(json_content, filename) content_bytes = json_content.encode("utf-8") # Create FileArtifact file_artifact = File( id=str(uuid4()), content=content_bytes, mime_type="application/json", file_type="json", filename=filename, size=len(content_bytes), filepath=file_path if file_path else None, ) log_debug("JSON file generated successfully") success_msg = f"JSON file '{filename}' has been generated successfully with {len(json_content)} characters." if file_path: success_msg += f" File saved to: {file_path}" else: success_msg += " File is available in response." return ToolResult(content=success_msg, files=[file_artifact]) except Exception as e: logger.error(f"Failed to generate JSON file: {e}") return ToolResult(content=f"Error generating JSON file: {e}") def generate_csv_file( self, data: Union[List[List], List[Dict], str], filename: Optional[str] = None, headers: Optional[List[str]] = None, ) -> ToolResult: """Generate a CSV file from the provided data. Args: data: The data to write to the CSV file. Can be a list of lists, list of dictionaries, or CSV string. filename: Optional filename for the generated file. If not provided, a UUID will be used. headers: Optional headers for the CSV. Used when data is a list of lists. Returns: ToolResult: Result containing the generated CSV file as a FileArtifact. """ try: log_debug(f"Generating CSV file with data: {type(data)}") # Create CSV content output = io.StringIO() if isinstance(data, str): # If it's already a CSV string, use it directly csv_content = data elif isinstance(data, list) and len(data) > 0: writer = csv.writer(output) if isinstance(data[0], dict): # List of dictionaries - use keys as headers if data: fieldnames = list(data[0].keys()) writer.writerow(fieldnames) for row in data: if isinstance(row, dict): writer.writerow([row.get(field, "") for field in fieldnames]) else: writer.writerow([str(row)] + [""] * (len(fieldnames) - 1)) elif isinstance(data[0], list): # List of lists if headers: writer.writerow(headers) writer.writerows(data) else: # List of other types if headers: writer.writerow(headers) for item in data: writer.writerow([str(item)]) csv_content = output.getvalue() else: csv_content = "" # Generate filename if not provided if not filename: filename = f"generated_file_{str(uuid4())[:8]}.csv" elif not filename.endswith(".csv"): filename += ".csv" # Save file to disk (if output_directory is set) file_path = self._save_file_to_disk(csv_content, filename) content_bytes = csv_content.encode("utf-8") # Create FileArtifact file_artifact = File( id=str(uuid4()), content=content_bytes, mime_type="text/csv", file_type="csv", filename=filename, size=len(content_bytes), filepath=file_path if file_path else None, ) log_debug("CSV file generated successfully") success_msg = f"CSV file '{filename}' has been generated successfully with {len(csv_content)} characters." if file_path: success_msg += f" File saved to: {file_path}" else: success_msg += " File is available in response." return ToolResult(content=success_msg, files=[file_artifact]) except Exception as e: logger.error(f"Failed to generate CSV file: {e}") return ToolResult(content=f"Error generating CSV file: {e}") def generate_pdf_file( self, content: str, filename: Optional[str] = None, title: Optional[str] = None ) -> ToolResult: """Generate a PDF file from the provided content. Args: content: The text content to write to the PDF file. filename: Optional filename for the generated file. If not provided, a UUID will be used. title: Optional title for the PDF document. Returns: ToolResult: Result containing the generated PDF file as a FileArtifact. """ if not PDF_AVAILABLE: return ToolResult( content="PDF generation is not available. Please install reportlab: pip install reportlab" ) try: log_debug(f"Generating PDF file with content length: {len(content)}") # Create PDF content in memory buffer = io.BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter, topMargin=1 * inch) # Get styles styles = getSampleStyleSheet() title_style = styles["Title"] normal_style = styles["Normal"] # Build story (content elements) story = [] if title: story.append(Paragraph(title, title_style)) story.append(Spacer(1, 20)) # Split content into paragraphs and add to story paragraphs = content.split("\n\n") for para in paragraphs: if para.strip(): # Clean the paragraph text for PDF clean_para = para.strip().replace("<", "&lt;").replace(">", "&gt;") story.append(Paragraph(clean_para, normal_style)) story.append(Spacer(1, 10)) # Build PDF doc.build(story) pdf_content = buffer.getvalue() buffer.close() # Generate filename if not provided if not filename: filename = f"generated_file_{str(uuid4())[:8]}.pdf" elif not filename.endswith(".pdf"): filename += ".pdf" # Save file to disk (if output_directory is set) file_path = self._save_file_to_disk(pdf_content, filename) # Create FileArtifact file_artifact = File( id=str(uuid4()), content=pdf_content, mime_type="application/pdf", file_type="pdf", filename=filename, size=len(pdf_content), filepath=file_path if file_path else None, ) log_debug("PDF file generated successfully") success_msg = f"PDF file '{filename}' has been generated successfully with {len(pdf_content)} bytes." if file_path: success_msg += f" File saved to: {file_path}" else: success_msg += " File is available in response." return ToolResult(content=success_msg, files=[file_artifact]) except Exception as e: logger.error(f"Failed to generate PDF file: {e}") return ToolResult(content=f"Error generating PDF file: {e}") def generate_text_file(self, content: str, filename: Optional[str] = None) -> ToolResult: """Generate a text file from the provided content. Args: content: The text content to write to the file. filename: Optional filename for the generated file. If not provided, a UUID will be used. Returns: ToolResult: Result containing the generated text file as a FileArtifact. """ try: log_debug(f"Generating text file with content length: {len(content)}") # Generate filename if not provided if not filename: filename = f"generated_file_{str(uuid4())[:8]}.txt" elif not filename.endswith(".txt"): filename += ".txt" # Save file to disk (if output_directory is set) file_path = self._save_file_to_disk(content, filename) content_bytes = content.encode("utf-8") # Create FileArtifact file_artifact = File( id=str(uuid4()), content=content_bytes, mime_type="text/plain", file_type="txt", filename=filename, size=len(content_bytes), filepath=file_path if file_path else None, ) log_debug("Text file generated successfully") success_msg = f"Text file '{filename}' has been generated successfully with {len(content)} characters." if file_path: success_msg += f" File saved to: {file_path}" else: success_msg += " File is available in response." return ToolResult(content=success_msg, files=[file_artifact]) except Exception as e: logger.error(f"Failed to generate text file: {e}") return ToolResult(content=f"Error generating text file: {e}")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/tools/file_generation.py", "license": "Apache License 2.0", "lines": 292, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/tests/integration/agent/test_tool_hooks.py
from typing import Any, Callable, Dict from unittest.mock import patch import pytest from agno.agent import Agent from agno.run.agent import RunOutput from agno.tools.decorator import tool from agno.utils.log import logger # --- Hooks Definition --- def logger_hook( function_name: str, function_call: Callable[..., Any], arguments: Dict[str, Any], ) -> Any: logger.info(f"HOOK PRE: Calling {function_name} with args {arguments}") result = function_call(**arguments) logger.info(f"HOOK POST: {function_name} returned {result}") return result def confirmation_hook( function_name: str, function_call: Callable[..., Any], arguments: Dict[str, Any], ) -> Any: if function_name == "add": logger.info("This tool is not allowed to be called") return logger.info("This tool is allowed to be called") return function_call(**arguments) # --- Tools Definition --- @tool() def add(a: int, b: int) -> int: return a + b @tool(tool_hooks=[logger_hook]) def sub(a: int, b: int) -> int: return a - b @tool(tool_hooks=[confirmation_hook]) def mul(a: int, b: int) -> int: return a * b # --- Test Cases --- def test_logger_hook_invocation_sub_tool(): agent = Agent(tools=[sub]) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: response: RunOutput = agent.run("Compute 6 - 5") assert response.tools is not None assert response.tools[0].tool_name == "sub" assert response.tools[0].result == "1" mock_info.assert_any_call("HOOK PRE: Calling sub with args {'a': 6, 'b': 5}") mock_info.assert_any_call("HOOK POST: sub returned 1") def test_confirmation_hook_blocks_add_tool(): agent = Agent(tools=[add], tool_hooks=[confirmation_hook]) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: agent.run("Compute 4 + 5") mock_info.assert_any_call("This tool is not allowed to be called") def test_confirmation_hook_allows_mul_tool(): agent = Agent(tools=[mul], tool_hooks=[confirmation_hook]) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: response: RunOutput = agent.run("Compute 4 * 5") mock_info.assert_any_call("This tool is allowed to be called") assert response.tools is not None assert response.tools[0].tool_name == "mul" assert response.tools[0].result == "20" def test_logger_hook_invocation_add_tool(): agent = Agent(tools=[add], tool_hooks=[logger_hook]) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: response: RunOutput = agent.run("Compute 4 + 5") assert response.tools is not None assert response.tools[0].tool_name == "add" assert response.tools[0].result == "9" mock_info.assert_any_call("HOOK PRE: Calling add with args {'a': 4, 'b': 5}") mock_info.assert_any_call("HOOK POST: add returned 9") def test_logger_hook_invocation_mul_tool(): agent = Agent(tools=[mul], tool_hooks=[logger_hook]) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: response: RunOutput = agent.run("Compute 3 * 3") assert response.tools is not None assert response.tools[0].tool_name == "mul" assert response.tools[0].result == "9" mock_info.assert_any_call("HOOK PRE: Calling mul with args {'a': 3, 'b': 3}") mock_info.assert_any_call("HOOK POST: mul returned 9") def test_logger_and_confirmation_hooks_combined(): agent = Agent( tools=[add, mul], tool_hooks=[logger_hook, confirmation_hook], # Logger outer, confirmation inner ) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: agent.run("Compute 2 + 3 and 4 * 5") # add tool should be blocked by confirmation_hook mock_info.assert_any_call("This tool is not allowed to be called") # mul tool should be allowed and logged mock_info.assert_any_call("This tool is allowed to be called") mock_info.assert_any_call("HOOK PRE: Calling mul with args {'a': 4, 'b': 5}") mock_info.assert_any_call("HOOK POST: mul returned 20") @pytest.mark.asyncio async def test_logger_and_confirmation_hooks_combined_async(): agent = Agent( tools=[add, mul], tool_hooks=[logger_hook, confirmation_hook], # Logger outer, confirmation inner ) with patch.object(type(logger), "info", wraps=logger.info) as mock_info: await agent.arun("Compute 2 + 3 and 4 * 5") # Check that add tool was blocked by confirmation_hook mock_info.assert_any_call("This tool is not allowed to be called") # Check that mul tool was allowed and logged mock_info.assert_any_call("This tool is allowed to be called") mock_info.assert_any_call("HOOK PRE: Calling mul with args {'a': 4, 'b': 5}") mock_info.assert_any_call("HOOK POST: mul returned 20")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/agent/test_tool_hooks.py", "license": "Apache License 2.0", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/os/routers/home.py
from typing import TYPE_CHECKING from fastapi import APIRouter if TYPE_CHECKING: from agno.os.app import AgentOS def get_home_router(os: "AgentOS") -> APIRouter: router = APIRouter(tags=["Home"]) @router.get( "/", operation_id="get_api_info", summary="API Information", description=( "Get basic information about this AgentOS API instance, including:\n\n" "- API metadata and version\n" "- Available capabilities overview\n" "- Links to key endpoints and documentation" ), responses={ 200: { "description": "API information retrieved successfully", "content": { "application/json": { "examples": { "home": { "summary": "Example home response", "value": { "name": "AgentOS API", "id": "demo-os", "version": "1.0.0", }, } } } }, } }, ) async def get_api_info(): """Get basic API information and available capabilities""" return { "name": "AgentOS API", "id": os.id or "agno-agentos", "version": os.version or "1.0.0", } return router
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/os/routers/home.py", "license": "Apache License 2.0", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/models/siliconflow/siliconflow.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, Optional from agno.exceptions import ModelAuthenticationError from agno.models.openai.like import OpenAILike @dataclass class Siliconflow(OpenAILike): """ A class for interacting with Siliconflow API. Attributes: id (str): The id of the Siliconflow model to use. Default is "Qwen/QwQ-32B". name (str): The name of this chat model instance. Default is "Siliconflow". provider (str): The provider of the model. Default is "Siliconflow". api_key (str): The api key to authorize request to Siliconflow. base_url (str): The base url to which the requests are sent. Defaults to "https://api.siliconflow.cn/v1". """ id: str = "Qwen/QwQ-32B" name: str = "Siliconflow" provider: str = "Siliconflow" api_key: Optional[str] = None base_url: str = "https://api.siliconflow.com/v1" def _get_client_params(self) -> Dict[str, Any]: """ Returns client parameters for API requests, checking for SILICONFLOW_API_KEY. Returns: Dict[str, Any]: A dictionary of client parameters for API requests. """ if not self.api_key: self.api_key = getenv("SILICONFLOW_API_KEY") if not self.api_key: raise ModelAuthenticationError( message="SILICONFLOW_API_KEY not set. Please set the SILICONFLOW_API_KEY environment variable.", model_name=self.name, ) return super()._get_client_params()
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/models/siliconflow/siliconflow.py", "license": "Apache License 2.0", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/tests/integration/agent/test_dependencies.py
import json from agno.agent import Agent, RunOutput from agno.db.in_memory import InMemoryDb from agno.models.openai.chat import OpenAIChat from agno.run.base import RunContext def test_dependencies(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Anna"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_function(): def get_robot_name(): return "Anna" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_async(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Anna"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_function_async(): async def get_robot_name(): return "Anna" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_on_run(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_on_run_async(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_mixed(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"} ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_mixed_async(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"} ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_mixed_async_stream(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), db=InMemoryDb(), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response = agent.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, stream=True, stream_events=True, ) async for _ in response: pass run_response = agent.get_last_run_output() # Check the system message assert ( "If you are asked to write a story about a robot, always name the robot Anna" in run_response.messages[0].content ) # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in run_response.messages[1].content def test_dependencies_resolve_in_context_false(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", resolve_in_context=False, ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert ( "If you are asked to write a story about a robot, always name the robot {robot_name}" in response.messages[0].content ) # Check the user message assert "Tell me a 5 second short story about a robot named {robot_name}" in response.messages[1].content def test_add_dependencies_to_context(): agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, add_dependencies_to_context=True, markdown=True, ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot and include their name in the story.") # Check the user message assert json.dumps({"robot_name": "Johnny"}, indent=2, default=str) in response.messages[1].content # Check the response assert "Johnny" in response.content def test_add_dependencies_to_context_function(): def get_robot_name(): return "Johnny" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, add_dependencies_to_context=True, markdown=True, ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot and include their name in the story.") # Check the user message assert json.dumps({"robot_name": "Johnny"}, indent=2, default=str) in response.messages[1].content # Check the response assert "Johnny" in response.content def test_dependencies_function_with_run_context(): def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run("Tell me a 5 second short story about a robot named {robot_name}") # Verify run_id was used (robot name should contain part of run_id) assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content async def test_dependencies_function_with_run_context_async(): async def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun("Tell me a 5 second short story about a robot named {robot_name}") # Verify run_id was used (robot name should contain part of run_id) assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content def test_dependencies_function_with_run_context_on_run(): def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = agent.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": get_robot_name}, ) # Verify run_id was used assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content async def test_dependencies_function_with_run_context_on_run_async(): async def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" agent = Agent( model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: RunOutput = await agent.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": get_robot_name}, ) # Verify run_id was used assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/agent/test_dependencies.py", "license": "Apache License 2.0", "lines": 265, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/integration/agent/test_storage.py
import uuid import pytest from agno.agent.agent import Agent from agno.models.openai.chat import OpenAIChat from agno.run.base import RunStatus @pytest.fixture def agent(shared_db): """Create an agent with db and memory for testing.""" return Agent( model=OpenAIChat(id="gpt-4o"), db=shared_db, markdown=True, ) @pytest.mark.asyncio async def test_run_history_persistence(agent): """Test that all runs within a session are persisted in db.""" user_id = "john@example.com" session_id = f"session_{uuid.uuid4()}" response = await agent.arun("Hello, how are you?", user_id=user_id, session_id=session_id) assert response.status == RunStatus.completed # Verify the stored session data after all turns agent_session = agent.get_session(session_id=session_id) assert agent_session is not None assert len(agent_session.runs) == 1 assert agent_session.runs[0].status == RunStatus.completed assert agent_session.runs[0].messages is not None assert len(agent_session.runs[0].messages) == 3 assert agent_session.runs[0].messages[1].content == "Hello, how are you?"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/agent/test_storage.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/integration/teams/test_dependencies.py
import json from agno.agent import Agent from agno.db.in_memory import InMemoryDb from agno.models.openai.chat import OpenAIChat from agno.run.base import RunContext from agno.team import Team, TeamRunOutput def test_dependencies(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Anna"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_function(): def get_robot_name(): return "Anna" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_async(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Anna"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_function_async(): async def get_robot_name(): return "Anna" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_on_run(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_on_run_async(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content def test_dependencies_mixed(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"} ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_mixed_async(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"} ) # Check the system message assert "If you are asked to write a story about a robot, always name the robot Anna" in response.messages[0].content # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in response.messages[1].content async def test_dependencies_mixed_async_stream(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), db=InMemoryDb(), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response = team.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": "Anna"}, stream=True, stream_events=True, ) async for _ in response: pass run_response = team.get_last_run_output() # Check the system message assert ( "If you are asked to write a story about a robot, always name the robot Anna" in run_response.messages[0].content ) # Check the user message assert "Tell me a 5 second short story about a robot named Anna" in run_response.messages[1].content def test_dependencies_resolve_in_context_false(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", resolve_in_context=False, ) # Run agent and return the response as a variable response: TeamRunOutput = team.run("Tell me a 5 second short story about a robot named {robot_name}") # Check the system message assert ( "If you are asked to write a story about a robot, always name the robot {robot_name}" in response.messages[0].content ) # Check the user message assert "Tell me a 5 second short story about a robot named {robot_name}" in response.messages[1].content def test_add_dependencies_to_context(): team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": "Johnny"}, add_dependencies_to_context=True, markdown=True, ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot and include their name in the story." ) # Check the user message assert json.dumps({"robot_name": "Johnny"}, indent=2, default=str) in response.messages[1].content # Check the response assert "Johnny" in response.content def test_add_dependencies_to_context_function(): def get_robot_name(): return "Johnny" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, add_dependencies_to_context=True, markdown=True, ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot and include their name in the story." ) # Check the user message assert json.dumps({"robot_name": "Johnny"}, indent=2, default=str) in response.messages[1].content # Check the response assert "Johnny" in response.content def test_dependencies_on_run_pass_to_team_members(): member = Agent( role="Story Writer", model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) team = Team( members=[member], model=OpenAIChat(id="gpt-4o-mini"), instructions="Always delegate the task to the member agent", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot", dependencies={"robot_name": "Anna"}, ) assert response.member_responses is not None assert len(response.member_responses) == 1 print(response.member_responses[0]) # Check the system message assert ( "If you are asked to write a story about a robot, always name the robot Anna" in response.member_responses[0].messages[0].content ) def test_dependencies_function_with_run_context(): def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run("Tell me a 5 second short story about a robot named {robot_name}") # Verify run_id was used (robot name should contain part of run_id) assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content async def test_dependencies_function_with_run_context_async(): async def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), dependencies={"robot_name": get_robot_name}, instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun("Tell me a 5 second short story about a robot named {robot_name}") # Verify run_id was used (robot name should contain part of run_id) assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content def test_dependencies_function_with_run_context_on_run(): def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = team.run( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": get_robot_name}, ) # Verify run_id was used assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content async def test_dependencies_function_with_run_context_on_run_async(): async def get_robot_name(run_context: RunContext): return f"Anna-{run_context.run_id[:8]}" team = Team( members=[], model=OpenAIChat(id="gpt-4o-mini"), instructions="If you are asked to write a story about a robot, always name the robot {robot_name}", ) # Run agent and return the response as a variable response: TeamRunOutput = await team.arun( "Tell me a 5 second short story about a robot named {robot_name}", dependencies={"robot_name": get_robot_name}, ) # Verify run_id was used assert response.run_id is not None robot_name_with_id = f"Anna-{response.run_id[:8]}" # Check the system message contains the resolved robot name assert ( f"If you are asked to write a story about a robot, always name the robot {robot_name_with_id}" in response.messages[0].content ) # Check the user message contains the resolved robot name assert f"Tell me a 5 second short story about a robot named {robot_name_with_id}" in response.messages[1].content
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/integration/teams/test_dependencies.py", "license": "Apache License 2.0", "lines": 310, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/tests/unit/agent/test_input_schema.py
from typing import List, Optional, TypedDict import pytest from pydantic import BaseModel, ConfigDict, Field from agno.agent import Agent from agno.models.openai import OpenAIChat from agno.utils.agent import validate_input # TypedDict schemas class ResearchTopicDict(TypedDict): topic: str focus_areas: List[str] target_audience: str sources_required: int class OptionalFieldsDict(TypedDict, total=False): topic: str focus_areas: List[str] priority: Optional[str] # Pydantic schemas class ResearchTopic(BaseModel): """Structured research topic with specific requirements""" topic: str focus_areas: List[str] = Field(description="Specific areas to focus on") target_audience: str = Field(description="Who this research is for") sources_required: int = Field(description="Number of sources needed", default=5) class OptionalResearchTopic(BaseModel): """Research topic with optional fields""" topic: str focus_areas: List[str] = Field(description="Specific areas to focus on") target_audience: Optional[str] = None sources_required: int = Field(default=3, description="Number of sources needed") priority: Optional[str] = Field(default=None, description="Priority level") class StrictResearchTopic(BaseModel): """Strict research topic with validation""" model_config = ConfigDict(extra="forbid") # Forbid extra fields topic: str = Field(min_length=1, max_length=100) focus_areas: List[str] = Field(min_items=1, max_items=5) target_audience: str = Field(min_length=1) sources_required: int = Field(gt=0, le=20) # Greater than 0, less than or equal to 20 # Fixtures @pytest.fixture def typed_dict_agent(): """Create an agent with TypedDict input schema for testing.""" return Agent( name="Test Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=ResearchTopicDict, ) @pytest.fixture def optional_fields_agent(): """Create an agent with optional fields TypedDict schema.""" return Agent( name="Optional Fields Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=OptionalFieldsDict, ) @pytest.fixture def pydantic_agent(): """Create an agent with Pydantic input schema for testing.""" return Agent( name="Pydantic Test Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=ResearchTopic, ) @pytest.fixture def optional_pydantic_agent(): """Create an agent with optional Pydantic fields.""" return Agent( name="Optional Pydantic Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=OptionalResearchTopic, ) @pytest.fixture def strict_pydantic_agent(): """Create an agent with strict Pydantic validation.""" return Agent( name="Strict Pydantic Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=StrictResearchTopic, ) # TypedDict tests def test_typed_dict_agent_validate_input_with_valid_data(typed_dict_agent): """Test agent input validation with valid TypedDict data.""" valid_input = { "topic": "AI Research", "focus_areas": ["Machine Learning", "NLP"], "target_audience": "Developers", "sources_required": 5, } result = validate_input(valid_input) assert result == valid_input def test_typed_dict_agent_validate_input_with_missing_required_field(typed_dict_agent): """Test agent input validation fails with missing required fields.""" invalid_input = { "topic": "AI Research", # Missing focus_areas, target_audience, sources_required } with pytest.raises(ValueError, match="Missing required fields"): validate_input(invalid_input, typed_dict_agent.input_schema) def test_typed_dict_agent_validate_input_with_unexpected_field(typed_dict_agent): """Test agent input validation fails with unexpected fields.""" invalid_input = { "topic": "AI Research", "focus_areas": ["Machine Learning"], "target_audience": "Developers", "sources_required": 5, "unexpected_field": "value", } with pytest.raises(ValueError, match="Unexpected fields"): validate_input(invalid_input, typed_dict_agent.input_schema) def test_typed_dict_agent_validate_input_with_wrong_type(typed_dict_agent): """Test agent input validation fails with wrong field types.""" invalid_input = { "topic": "AI Research", "focus_areas": "Not a list", # Should be List[str] "target_audience": "Developers", "sources_required": 5, } with pytest.raises(ValueError, match="expected type"): validate_input(invalid_input, typed_dict_agent.input_schema) def test_typed_dict_agent_validate_input_with_optional_fields(optional_fields_agent): """Test agent input validation with optional fields.""" # Minimal input (only required fields) minimal_input = {"topic": "Blockchain", "focus_areas": ["DeFi", "Smart Contracts"]} # Input with optional field full_input = {"topic": "Blockchain", "focus_areas": ["DeFi", "Smart Contracts"], "priority": "high"} # Both should validate successfully result1 = validate_input(minimal_input, optional_fields_agent.input_schema) result2 = validate_input(full_input, optional_fields_agent.input_schema) assert result1 == minimal_input assert result2 == full_input def test_agent_without_input_schema_handles_dict(): """Test that agent without input_schema handles dict input gracefully.""" agent = Agent( name="No Schema Agent", model=OpenAIChat(id="gpt-4o-mini"), # No input_schema ) dict_input = {"arbitrary": "data", "numbers": [1, 2, 3]} # Should not raise an exception and return input unchanged result = validate_input(dict_input, agent.input_schema) assert result == dict_input # Pydantic tests def test_pydantic_agent_validate_input_with_valid_dict(pydantic_agent): """Test agent input validation with valid dict that matches Pydantic schema.""" valid_input = { "topic": "AI Research", "focus_areas": ["Machine Learning", "NLP"], "target_audience": "Developers", "sources_required": 8, } result = validate_input(valid_input, pydantic_agent.input_schema) # Result should be a ResearchTopic instance assert isinstance(result, ResearchTopic) assert result.topic == "AI Research" assert result.focus_areas == ["Machine Learning", "NLP"] assert result.target_audience == "Developers" assert result.sources_required == 8 def test_pydantic_agent_validate_input_with_model_instance(pydantic_agent): """Test agent input validation with direct Pydantic model instance.""" model_instance = ResearchTopic( topic="Blockchain", focus_areas=["DeFi", "Smart Contracts"], target_audience="Crypto Developers", sources_required=6, ) result = validate_input(model_instance, pydantic_agent.input_schema) # Should return the same instance assert result is model_instance assert isinstance(result, ResearchTopic) def test_pydantic_agent_validate_input_with_default_values(pydantic_agent): """Test agent input validation uses Pydantic default values.""" input_without_sources = { "topic": "Machine Learning", "focus_areas": ["Neural Networks"], "target_audience": "Students", # sources_required omitted - should use default value of 5 } result = validate_input(input_without_sources, pydantic_agent.input_schema) assert isinstance(result, ResearchTopic) assert result.sources_required == 5 # Default value def test_pydantic_agent_validate_input_with_missing_required_field(pydantic_agent): """Test agent input validation fails with missing required fields.""" invalid_input = { "topic": "AI Research", # Missing focus_areas and target_audience (required fields) "sources_required": 5, } with pytest.raises(ValueError, match="Failed to parse dict into ResearchTopic"): validate_input(invalid_input, pydantic_agent.input_schema) def test_pydantic_agent_validate_input_with_wrong_type(pydantic_agent): """Test agent input validation fails with wrong field types.""" invalid_input = { "topic": "AI Research", "focus_areas": "Not a list", # Should be List[str] "target_audience": "Developers", "sources_required": 5, } with pytest.raises(ValueError, match="Failed to parse dict into ResearchTopic"): validate_input(invalid_input, pydantic_agent.input_schema) def test_pydantic_agent_validate_input_with_type_coercion(pydantic_agent): """Test that Pydantic performs type coercion when possible.""" input_with_coercion = { "topic": "AI Research", "focus_areas": ["Machine Learning"], "target_audience": "Developers", "sources_required": "5", # String that can be converted to int } result = validate_input(input_with_coercion, pydantic_agent.input_schema) assert isinstance(result, ResearchTopic) assert result.sources_required == 5 # Should be converted to int assert isinstance(result.sources_required, int) def test_pydantic_agent_validate_input_with_optional_fields(optional_pydantic_agent): """Test agent input validation with optional Pydantic fields.""" # Minimal input (only required fields) minimal_input = { "topic": "Blockchain", "focus_areas": ["DeFi"], # target_audience and sources_required are optional } result = validate_input(minimal_input, optional_pydantic_agent.input_schema) assert isinstance(result, OptionalResearchTopic) assert result.topic == "Blockchain" assert result.focus_areas == ["DeFi"] assert result.target_audience is None assert result.sources_required == 3 # Default value assert result.priority is None def test_pydantic_agent_validate_input_with_all_optional_fields(optional_pydantic_agent): """Test agent input validation with all optional fields provided.""" full_input = { "topic": "Blockchain", "focus_areas": ["DeFi", "Smart Contracts"], "target_audience": "Crypto Developers", "sources_required": 10, "priority": "high", } result = validate_input(full_input, optional_pydantic_agent.input_schema) assert isinstance(result, OptionalResearchTopic) assert result.priority == "high" assert result.target_audience == "Crypto Developers" assert result.sources_required == 10 def test_pydantic_agent_validate_input_with_strict_validation(strict_pydantic_agent): """Test agent with strict Pydantic validation rules.""" valid_input = { "topic": "AI Research", "focus_areas": ["Machine Learning", "NLP"], "target_audience": "Developers", "sources_required": 5, } result = validate_input(valid_input, strict_pydantic_agent.input_schema) assert isinstance(result, StrictResearchTopic) def test_pydantic_agent_validate_input_strict_validation_failures(strict_pydantic_agent): """Test various strict validation failures.""" # Test empty topic (violates min_length=1) with pytest.raises(ValueError): validate_input( {"topic": "", "focus_areas": ["ML"], "target_audience": "Developers", "sources_required": 5}, strict_pydantic_agent.input_schema, ) # Test too many focus areas (violates max_items=5) with pytest.raises(ValueError): validate_input( { "topic": "AI", "focus_areas": ["ML", "NLP", "CV", "RL", "DL", "Extra"], # 6 items > max 5 "target_audience": "Developers", "sources_required": 5, }, strict_pydantic_agent.input_schema, ) # Test sources_required = 0 (violates gt=0) with pytest.raises(ValueError): validate_input( { "topic": "AI", "focus_areas": ["ML"], "target_audience": "Developers", "sources_required": 0, # Should be > 0 }, strict_pydantic_agent.input_schema, ) # Test sources_required > 20 (violates le=20) with pytest.raises(ValueError): validate_input( { "topic": "AI", "focus_areas": ["ML"], "target_audience": "Developers", "sources_required": 25, # Should be <= 20 }, strict_pydantic_agent.input_schema, ) def test_pydantic_agent_validate_input_forbids_extra_fields(strict_pydantic_agent): """Test that strict model forbids extra fields.""" input_with_extra = { "topic": "AI", "focus_areas": ["ML"], "target_audience": "Developers", "sources_required": 5, "extra_field": "not allowed", # Should be forbidden } with pytest.raises(ValueError, match="Failed to parse dict into StrictResearchTopic"): validate_input(input_with_extra, strict_pydantic_agent.input_schema) def test_pydantic_agent_validate_input_different_model_instance(pydantic_agent): """Test agent input validation fails with wrong Pydantic model type.""" wrong_model = OptionalResearchTopic(topic="Test", focus_areas=["Test"]) with pytest.raises(ValueError, match="Expected ResearchTopic but got OptionalResearchTopic"): validate_input(wrong_model, pydantic_agent.input_schema) def test_agent_without_input_schema_handles_pydantic_model(): """Test that agent without input_schema handles Pydantic model input.""" agent = Agent( name="No Schema Agent", model=OpenAIChat(id="gpt-4o-mini"), # No input_schema ) model_instance = ResearchTopic(topic="Test", focus_areas=["Test Area"], target_audience="Test Audience") # Should not raise an exception and return input unchanged result = validate_input(model_instance, agent.input_schema) assert result is model_instance def test_pydantic_field_descriptions_preserved(): """Test that Pydantic Field descriptions are preserved in the model.""" # Check that field info is available (this is how Pydantic stores Field metadata) schema = ResearchTopic.model_json_schema() assert schema["properties"]["focus_areas"]["description"] == "Specific areas to focus on" assert schema["properties"]["target_audience"]["description"] == "Who this research is for" assert schema["properties"]["sources_required"]["description"] == "Number of sources needed" assert schema["properties"]["sources_required"]["default"] == 5 def test_pydantic_json_serialization(): """Test that Pydantic models serialize to JSON properly.""" model = ResearchTopic(topic="AI", focus_areas=["ML", "NLP"], target_audience="Developers", sources_required=7) # Test model_dump_json json_str = model.model_dump_json(indent=2, exclude_none=True) assert isinstance(json_str, str) # Parse back and verify import json parsed = json.loads(json_str) assert parsed["topic"] == "AI" assert parsed["focus_areas"] == ["ML", "NLP"] assert parsed["sources_required"] == 7 def test_pydantic_model_validation_error_messages(): """Test that Pydantic validation errors contain useful information.""" agent = Agent( name="Test Agent", model=OpenAIChat(id="gpt-4o-mini"), input_schema=ResearchTopic, ) invalid_input = { "topic": "AI", "focus_areas": "not a list", # Wrong type "target_audience": "Developers", # Missing sources_required } try: validate_input(invalid_input, agent.input_schema) assert False, "Should have raised ValueError" except ValueError as e: error_msg = str(e) assert "Failed to parse dict into ResearchTopic" in error_msg # The original Pydantic error should be included assert "validation error" in error_msg or "Input should be" in error_msg
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/tests/unit/agent/test_input_schema.py", "license": "Apache License 2.0", "lines": 358, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
agno-agi/agno:libs/agno/agno/os/routers/health.py
from datetime import datetime, timezone from fastapi import APIRouter from agno.os.schema import HealthResponse def get_health_router(health_endpoint: str = "/health") -> APIRouter: router = APIRouter(tags=["Health"]) started_at = datetime.now(timezone.utc) @router.get( health_endpoint, operation_id="health_check", summary="Health Check", description="Check the health status of the AgentOS API. Returns a simple status indicator.", response_model=HealthResponse, responses={ 200: { "description": "API is healthy and operational", "content": { "application/json": {"example": {"status": "ok", "instantiated_at": "2025-06-10T12:00:00Z"}} }, } }, ) async def health_check() -> HealthResponse: return HealthResponse(status="ok", instantiated_at=started_at) return router
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/os/routers/health.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/tools/memory.py
import json from textwrap import dedent from typing import Any, List, Optional from uuid import uuid4 from agno.db.base import BaseDb from agno.db.schemas import UserMemory from agno.run import RunContext from agno.tools import Toolkit from agno.utils.log import log_debug, log_error class MemoryTools(Toolkit): def __init__( self, db: BaseDb, enable_get_memories: bool = True, enable_add_memory: bool = True, enable_update_memory: bool = True, enable_delete_memory: bool = True, enable_analyze: bool = True, enable_think: bool = True, instructions: Optional[str] = None, add_instructions: bool = True, add_few_shot: bool = True, few_shot_examples: Optional[str] = None, all: bool = False, **kwargs, ): # Add instructions for using this toolkit if instructions is None: self.instructions = self.DEFAULT_INSTRUCTIONS if add_few_shot: if few_shot_examples is not None: self.instructions += "\n" + few_shot_examples else: self.instructions += "\n" + self.FEW_SHOT_EXAMPLES else: self.instructions = instructions # The database to use for memory operations self.db: BaseDb = db tools: List[Any] = [] if enable_think or all: tools.append(self.think) if enable_get_memories or all: tools.append(self.get_memories) if enable_add_memory or all: tools.append(self.add_memory) if enable_update_memory or all: tools.append(self.update_memory) if enable_delete_memory or all: tools.append(self.delete_memory) if enable_analyze or all: tools.append(self.analyze) super().__init__( name="memory_tools", instructions=self.instructions, add_instructions=add_instructions, tools=tools, **kwargs, ) def think(self, run_context: RunContext, thought: str) -> str: """Use this tool as a scratchpad to reason about memory operations, refine your approach, brainstorm memory content, or revise your plan. Call `Think` whenever you need to figure out what to do next, analyze the user's requirements, plan memory operations, or decide on execution strategy. You should use this tool as frequently as needed. Args: thought: Your thought process and reasoning about memory operations. """ try: log_debug(f"Memory Thought: {thought}") # Add the thought to the session state if run_context.session_state is None: run_context.session_state = {} if "memory_thoughts" not in run_context.session_state: run_context.session_state["memory_thoughts"] = [] run_context.session_state["memory_thoughts"].append(thought) # Return the full log of thoughts and the new thought thoughts = "\n".join([f"- {t}" for t in run_context.session_state["memory_thoughts"]]) formatted_thoughts = dedent( f"""Memory Thoughts: {thoughts} """ ).strip() return formatted_thoughts except Exception as e: log_error(f"Error recording memory thought: {e}") return f"Error recording memory thought: {e}" def get_memories(self, run_context: RunContext) -> str: """ Use this tool to get a list of memories for the current user from the database. """ try: # Get user info from run context user_id = run_context.user_id memories = self.db.get_user_memories(user_id=user_id) # Store the result in session state for analysis if run_context.session_state is None: run_context.session_state = {} if "memory_operations" not in run_context.session_state: run_context.session_state["memory_operations"] = [] operation_result = { "operation": "get_memories", "success": True, "memories": [memory.to_dict() for memory in memories], # type: ignore "error": None, } run_context.session_state["memory_operations"].append(operation_result) return json.dumps([memory.to_dict() for memory in memories], indent=2) # type: ignore except Exception as e: log_error(f"Error getting memories: {e}") return json.dumps({"error": str(e)}, indent=2) def add_memory( self, run_context: RunContext, memory: str, topics: Optional[List[str]] = None, ) -> str: """Use this tool to add a new memory to the database. Args: memory: The memory content to store topics: Optional list of topics associated with this memory Returns: str: JSON string containing the created memory information """ try: log_debug(f"Adding memory: {memory}") # Get user info from run context user_id = run_context.user_id # Create UserMemory object user_memory = UserMemory( memory_id=str(uuid4()), memory=memory, topics=topics, user_id=user_id, ) # Add to database created_memory = self.db.upsert_user_memory(user_memory) # Store the result in session state for analysis if run_context.session_state is None: run_context.session_state = {} if "memory_operations" not in run_context.session_state: run_context.session_state["memory_operations"] = [] memory_dict = created_memory.to_dict() if created_memory else None # type: ignore operation_result = { "operation": "add_memory", "success": created_memory is not None, "memory": memory_dict, "error": None, } run_context.session_state["memory_operations"].append(operation_result) if created_memory: return json.dumps({"success": True, "operation": "add_memory", "memory": memory_dict}, indent=2) else: return json.dumps( {"success": False, "operation": "add_memory", "error": "Failed to create memory"}, indent=2 ) except Exception as e: log_error(f"Error adding memory: {e}") return json.dumps({"success": False, "operation": "add_memory", "error": str(e)}, indent=2) def update_memory( self, run_context: RunContext, memory_id: str, memory: Optional[str] = None, topics: Optional[List[str]] = None, ) -> str: """Use this tool to update an existing memory in the database. Args: memory_id: The ID of the memory to update memory: Updated memory content (if provided) topics: Updated list of topics (if provided) Returns: str: JSON string containing the updated memory information """ try: log_debug(f"Updating memory: {memory_id}") # First get the existing memory existing_memory = self.db.get_user_memory(memory_id) if not existing_memory: return json.dumps( {"success": False, "operation": "update_memory", "error": f"Memory with ID {memory_id} not found"}, indent=2, ) # Update fields if provided updated_memory = UserMemory( memory=memory if memory is not None else existing_memory.memory, # type: ignore memory_id=memory_id, topics=topics if topics is not None else existing_memory.topics, # type: ignore user_id=existing_memory.user_id, # type: ignore ) # Update in database updated_result = self.db.upsert_user_memory(updated_memory) # Store the result in session state for analysis if run_context.session_state is None: run_context.session_state = {} if "memory_operations" not in run_context.session_state: run_context.session_state["memory_operations"] = [] memory_dict = updated_result.to_dict() if updated_result else None # type: ignore operation_result = { "operation": "update_memory", "success": updated_result is not None, "memory": memory_dict, "error": None, } run_context.session_state["memory_operations"].append(operation_result) if updated_result: return json.dumps({"success": True, "operation": "update_memory", "memory": memory_dict}, indent=2) else: return json.dumps( {"success": False, "operation": "update_memory", "error": "Failed to update memory"}, indent=2 ) except Exception as e: log_error(f"Error updating memory: {e}") return json.dumps({"success": False, "operation": "update_memory", "error": str(e)}, indent=2) def delete_memory( self, run_context: RunContext, memory_id: str, ) -> str: """Use this tool to delete a memory from the database. Args: memory_id: The ID of the memory to delete Returns: str: JSON string containing the deletion result """ try: log_debug(f"Deleting memory: {memory_id}") # Check if memory exists before deletion existing_memory = self.db.get_user_memory(memory_id) if not existing_memory: return json.dumps( {"success": False, "operation": "delete_memory", "error": f"Memory with ID {memory_id} not found"}, indent=2, ) # Delete from database self.db.delete_user_memory(memory_id) # Store the result in session state for analysis if run_context.session_state is None: run_context.session_state = {} if "memory_operations" not in run_context.session_state: run_context.session_state["memory_operations"] = [] memory_dict = existing_memory.to_dict() if existing_memory else None # type: ignore operation_result = { "operation": "delete_memory", "success": True, "memory_id": memory_id, "deleted_memory": memory_dict, "error": None, } run_context.session_state["memory_operations"].append(operation_result) return json.dumps( { "success": True, "operation": "delete_memory", "memory_id": memory_id, "deleted_memory": memory_dict, }, indent=2, ) except Exception as e: log_error(f"Error deleting memory: {e}") return json.dumps({"success": False, "operation": "delete_memory", "error": str(e)}, indent=2) def analyze(self, run_context: RunContext, analysis: str) -> str: """Use this tool to evaluate whether the memory operations results are correct and sufficient. If not, go back to "Think" or use memory operations with refined parameters. Args: analysis: Your analysis of the memory operations results. """ try: log_debug(f"Memory Analysis: {analysis}") # Add the analysis to the session state if run_context.session_state is None: run_context.session_state = {} if "memory_analysis" not in run_context.session_state: run_context.session_state["memory_analysis"] = [] run_context.session_state["memory_analysis"].append(analysis) # Return the full log of analysis and the new analysis analysis_log = "\n".join([f"- {a}" for a in run_context.session_state["memory_analysis"]]) formatted_analysis = dedent( f"""Memory Analysis: {analysis_log} """ ).strip() return formatted_analysis except Exception as e: log_error(f"Error recording memory analysis: {e}") return f"Error recording memory analysis: {e}" DEFAULT_INSTRUCTIONS = dedent("""\ You have access to the Think, Add Memory, Update Memory, Delete Memory, and Analyze tools that will help you manage user memories and analyze their operations. Use these tools as frequently as needed to successfully complete memory management tasks. ## How to use the Think, Memory Operations, and Analyze tools: 1. **Think** - Purpose: A scratchpad for planning memory operations, brainstorming memory content, and refining your approach. You never reveal your "Think" content to the user. - Usage: Call `think` whenever you need to figure out what memory operations to perform, analyze requirements, or decide on strategy. 2. **Get Memories** - Purpose: Retrieves a list of memories from the database for the current user. - Usage: Call `get_memories` when you need to retrieve memories for the current user. 3. **Add Memory** - Purpose: Creates new memories in the database with specified content and metadata. - Usage: Call `add_memory` with memory content and optional topics when you need to store new information. 4. **Update Memory** - Purpose: Modifies existing memories in the database by memory ID. - Usage: Call `update_memory` with a memory ID and the fields you want to change. Only specify the fields that need updating. 5. **Delete Memory** - Purpose: Removes memories from the database by memory ID. - Usage: Call `delete_memory` with a memory ID when a memory is no longer needed or requested to be removed. 6. **Analyze** - Purpose: Evaluate whether the memory operations results are correct and sufficient. If not, go back to "Think" or use memory operations with refined parameters. - Usage: Call `analyze` after performing memory operations to verify: - Success: Did the operation complete successfully? - Accuracy: Is the memory content correct and well-formed? - Completeness: Are all required fields populated appropriately? - Errors: Were there any failures or unexpected behaviors? **Important Guidelines**: - Do not include your internal chain-of-thought in direct user responses. - Use "Think" to reason internally. These notes are never exposed to the user. - When you provide a final answer to the user, be clear, concise, and based on the memory operation results. - If memory operations fail or produce unexpected results, acknowledge limitations and explain what went wrong. - Always verify memory IDs exist before attempting updates or deletions. - Use descriptive topics and clear memory content to make memories easily searchable and understandable.\ """) FEW_SHOT_EXAMPLES = dedent("""\ You can refer to the examples below as guidance for how to use each tool. ### Examples #### Example 1: Adding User Preferences User: I prefer vegetarian recipes and I'm allergic to nuts. Think: I should store the user's dietary preferences. I should create a memory with this information and use relevant topics for easy retrieval. Add Memory: memory="User prefers vegetarian recipes and is allergic to nuts", topics=["dietary_preferences", "allergies", "food"] Analyze: Successfully created memory with dietary preferences. The topics are well-chosen for future retrieval. This should help with future food-related requests. Final Answer: Noted. I've stored your dietary preferences. I'll remember that you prefer vegetarian recipes and have a nut allergy for future reference. #### Example 2: Updating Existing Information User: Actually, update my dietary info - I'm now eating fish too, so I'm pescatarian. Think: The user wants to update their previous dietary preference from vegetarian to pescatarian. I need to find their existing dietary memory and update it. Update Memory: memory_id="previous_memory_id", memory="User follows pescatarian diet (vegetarian + fish) and is allergic to nuts", topics=["dietary_preferences", "allergies", "food", "pescatarian"] Analyze: Successfully updated the dietary preference memory. The content now accurately reflects pescatarian diet and maintains the nut allergy information. Final Answer: I've updated your dietary preferences to reflect that you follow a pescatarian diet (vegetarian plus fish) while maintaining your nut allergy information. #### Example 3: Removing Outdated Information User: Please forget about my old work schedule - it's completely changed. Think: The user wants me to delete their old work schedule memory since it's no longer relevant. I should find and remove that memory. Delete Memory: memory_id="work_schedule_memory_id" Analyze: Successfully deleted the outdated work schedule memory. The old information won't interfere with future scheduling requests. Final Answer: I've removed your old work schedule information. Feel free to share your new schedule when you're ready, and I'll store the updated information. #### Example 4: Retrieving Memories User: What have you remembered about me? Think: The user wants to retrieve memories about themselves. I should use the get_memories tool to retrieve the memories. Get Memories: Analyze: Successfully retrieved the memories about the user. The memories are relevant to the user's preferences and activities. Final Answer: I've retrieved the memories about you. You like to hike in the mountains on weekends and travel to new places and experience different cultures. You are planning to travel to Africa in December.\ """)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/tools/memory.py", "license": "Apache License 2.0", "lines": 345, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/tools/workflow.py
import json from textwrap import dedent from typing import Any, Dict, Optional from pydantic import BaseModel, Field from agno.run import RunContext from agno.tools import Toolkit from agno.utils.log import log_debug, log_error from agno.workflow.workflow import Workflow, WorkflowRunOutput class RunWorkflowInput(BaseModel): input_data: str = Field(..., description="The input data for the workflow.") additional_data: Optional[Dict[str, Any]] = Field(default=None, description="The additional data for the workflow.") class WorkflowTools(Toolkit): def __init__( self, workflow: Workflow, enable_run_workflow: bool = True, enable_think: bool = False, enable_analyze: bool = False, all: bool = False, instructions: Optional[str] = None, add_instructions: bool = True, add_few_shot: bool = False, few_shot_examples: Optional[str] = None, async_mode: bool = False, **kwargs, ): # Add instructions for using this toolkit if instructions is None: self.instructions = self.DEFAULT_INSTRUCTIONS if add_few_shot: if few_shot_examples is not None: self.instructions += "\n" + few_shot_examples else: self.instructions = instructions # The workflow to execute self.workflow: Workflow = workflow super().__init__( name="workflow_tools", instructions=self.instructions, add_instructions=add_instructions, auto_register=False, **kwargs, ) if enable_think or all: if async_mode: self.register(self.async_think, name="think") else: self.register(self.think, name="think") if enable_run_workflow or all: if async_mode: self.register(self.async_run_workflow, name="run_workflow") else: self.register(self.run_workflow, name="run_workflow") if enable_analyze or all: if async_mode: self.register(self.async_analyze, name="analyze") else: self.register(self.analyze, name="analyze") def think(self, run_context: RunContext, thought: str) -> str: """Use this tool as a scratchpad to reason about the workflow execution, refine your approach, brainstorm workflow inputs, or revise your plan. Call `Think` whenever you need to figure out what to do next, analyze the user's requirements, plan workflow inputs, or decide on execution strategy. You should use this tool as frequently as needed. Args: thought: Your thought process and reasoning about workflow execution. """ try: log_debug(f"Workflow Thought: {thought}") # Add the thought to the session state if run_context.session_state is None: run_context.session_state = {} if "workflow_thoughts" not in run_context.session_state: run_context.session_state["workflow_thoughts"] = [] run_context.session_state["workflow_thoughts"].append(thought) # Return the full log of thoughts and the new thought thoughts = "\n".join([f"- {t}" for t in run_context.session_state["workflow_thoughts"]]) formatted_thoughts = dedent( f"""Workflow Thoughts: {thoughts} """ ).strip() return formatted_thoughts except Exception as e: log_error(f"Error recording workflow thought: {e}") return f"Error recording workflow thought: {e}" async def async_think(self, run_context: RunContext, thought: str) -> str: """Use this tool as a scratchpad to reason about the workflow execution, refine your approach, brainstorm workflow inputs, or revise your plan. Call `Think` whenever you need to figure out what to do next, analyze the user's requirements, plan workflow inputs, or decide on execution strategy. You should use this tool as frequently as needed. Args: thought: Your thought process and reasoning about workflow execution. """ try: log_debug(f"Workflow Thought: {thought}") # Add the thought to the session state if run_context.session_state is None: run_context.session_state = {} if "workflow_thoughts" not in run_context.session_state: run_context.session_state["workflow_thoughts"] = [] run_context.session_state["workflow_thoughts"].append(thought) # Return the full log of thoughts and the new thought thoughts = "\n".join([f"- {t}" for t in run_context.session_state["workflow_thoughts"]]) formatted_thoughts = dedent( f"""Workflow Thoughts: {thoughts} """ ).strip() return formatted_thoughts except Exception as e: log_error(f"Error recording workflow thought: {e}") return f"Error recording workflow thought: {e}" def run_workflow( self, run_context: RunContext, input: RunWorkflowInput, ) -> str: """Use this tool to execute the workflow with the specified inputs and parameters. After thinking through the requirements, use this tool to run the workflow with appropriate inputs. Args: input: The input data for the workflow. """ if isinstance(input, dict): input = RunWorkflowInput.model_validate(input) try: log_debug(f"Running workflow with input: {input.input_data}") if run_context.session_state is None: run_context.session_state = {} # Execute the workflow result: WorkflowRunOutput = self.workflow.run( input=input.input_data, user_id=run_context.user_id, session_id=run_context.session_id, session_state=run_context.session_state, additional_data=input.additional_data, ) if "workflow_results" not in run_context.session_state: run_context.session_state["workflow_results"] = [] run_context.session_state["workflow_results"].append(result.to_dict()) return json.dumps(result.to_dict(), indent=2) except Exception as e: log_error(f"Error running workflow: {e}") return f"Error running workflow: {e}" async def async_run_workflow( self, run_context: RunContext, input: RunWorkflowInput, ) -> str: """Use this tool to execute the workflow with the specified inputs and parameters. After thinking through the requirements, use this tool to run the workflow with appropriate inputs. Args: input_data: The input data for the workflow (use a `str` for a simple input) additional_data: The additional data for the workflow. This is a dictionary of key-value pairs that will be passed to the workflow. E.g. {"topic": "food", "style": "Humour"} """ if isinstance(input, dict): input = RunWorkflowInput.model_validate(input) try: log_debug(f"Running workflow with input: {input.input_data}") if run_context.session_state is None: run_context.session_state = {} # Execute the workflow result: WorkflowRunOutput = await self.workflow.arun( input=input.input_data, user_id=run_context.user_id, session_id=run_context.session_id, session_state=run_context.session_state, additional_data=input.additional_data, ) if "workflow_results" not in run_context.session_state: run_context.session_state["workflow_results"] = [] run_context.session_state["workflow_results"].append(result.to_dict()) return json.dumps(result.to_dict(), indent=2) except Exception as e: log_error(f"Error running workflow: {e}") return f"Error running workflow: {e}" def analyze(self, run_context: RunContext, analysis: str) -> str: """Use this tool to evaluate whether the workflow execution results are correct and sufficient. If not, go back to "Think" or "Run" with refined inputs or parameters. Args: analysis: Your analysis of the workflow execution results. """ try: log_debug(f"Workflow Analysis: {analysis}") # Add the analysis to the session state if run_context.session_state is None: run_context.session_state = {} if "workflow_analysis" not in run_context.session_state: run_context.session_state["workflow_analysis"] = [] run_context.session_state["workflow_analysis"].append(analysis) # Return the full log of analysis and the new analysis analysis_log = "\n".join([f"- {a}" for a in run_context.session_state["workflow_analysis"]]) formatted_analysis = dedent( f"""Workflow Analysis: {analysis_log} """ ).strip() return formatted_analysis except Exception as e: log_error(f"Error recording workflow analysis: {e}") return f"Error recording workflow analysis: {e}" async def async_analyze(self, run_context: RunContext, analysis: str) -> str: """Use this tool to evaluate whether the workflow execution results are correct and sufficient. If not, go back to "Think" or "Run" with refined inputs or parameters. Args: analysis: Your analysis of the workflow execution results. """ try: log_debug(f"Workflow Analysis: {analysis}") # Add the analysis to the session state if run_context.session_state is None: run_context.session_state = {} if "workflow_analysis" not in run_context.session_state: run_context.session_state["workflow_analysis"] = [] run_context.session_state["workflow_analysis"].append(analysis) # Return the full log of analysis and the new analysis analysis_log = "\n".join([f"- {a}" for a in run_context.session_state["workflow_analysis"]]) formatted_analysis = dedent( f"""Workflow Analysis: {analysis_log} """ ).strip() return formatted_analysis except Exception as e: log_error(f"Error recording workflow analysis: {e}") return f"Error recording workflow analysis: {e}" DEFAULT_INSTRUCTIONS = dedent("""\ You have access to the Think, Run Workflow, and Analyze tools that will help you execute workflows and analyze their results. Use these tools as frequently as needed to successfully complete workflow-based tasks. ## How to use the Think, Run Workflow, and Analyze tools: 1. **Think** - Purpose: A scratchpad for planning workflow execution, brainstorming inputs, and refining your approach. You never reveal your "Think" content to the user. - Usage: Call `think` whenever you need to figure out what workflow inputs to use, analyze requirements, or decide on execution strategy before (or after) you run the workflow. 2. **Run Workflow** - Purpose: Executes the workflow with specified inputs and parameters. - Usage: Call `run_workflow` with appropriate input data whenever you want to execute the workflow. - For all workflows, start with simple inputs and gradually increase complexity 3. **Analyze** - Purpose: Evaluate whether the workflow execution results are correct and sufficient. If not, go back to "Think" or "Run Workflow" with refined inputs. - Usage: Call `analyze` after getting workflow results to verify the quality and correctness of the execution. Consider: - Completeness: Did the workflow complete all expected steps? - Quality: Are the results accurate and meet the requirements? - Errors: Were there any failures or unexpected behaviors? **Important Guidelines**: - Do not include your internal chain-of-thought in direct user responses. - Use "Think" to reason internally. These notes are never exposed to the user. - When you provide a final answer to the user, be clear, concise, and based on the workflow results. - If workflow execution fails or produces unexpected results, acknowledge limitations and explain what went wrong. - Synthesize information from multiple workflow runs if you execute the workflow several times with different inputs.\ """)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/tools/workflow.py", "license": "Apache License 2.0", "lines": 246, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/api/os.py
from agno.api.api import api from agno.api.routes import ApiRoutes from agno.api.schemas.os import OSLaunch from agno.utils.log import log_debug def log_os_telemetry(launch: OSLaunch) -> None: """Telemetry recording for OS launches""" with api.Client() as api_client: try: response = api_client.post( ApiRoutes.AGENT_OS_LAUNCH, json=launch.model_dump(exclude_none=True), ) response.raise_for_status() except Exception as e: log_debug(f"Could not register OS launch for telemetry: {e}")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/api/os.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/api/schemas/os.py
from typing import Any, Dict, Optional from pydantic import BaseModel, Field from agno.api.schemas.utils import get_sdk_version class OSLaunch(BaseModel): """Data sent to API to create an OS Launch""" os_id: Optional[str] = None data: Optional[Dict[Any, Any]] = None sdk_version: str = Field(default_factory=get_sdk_version)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/api/schemas/os.py", "license": "Apache License 2.0", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/api/schemas/utils.py
from enum import Enum class TelemetryRunEventType(str, Enum): AGENT = "agent" EVAL = "eval" TEAM = "team" WORKFLOW = "workflow" def get_sdk_version() -> str: """Return the installed agno SDK version from package metadata. Falls back to "unknown" if the package metadata isn't available. """ from importlib.metadata import version as pkg_version try: return pkg_version("agno") except Exception: return "unknown"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/api/schemas/utils.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/api/settings.py
from __future__ import annotations from importlib import metadata from pydantic import field_validator from pydantic_core.core_schema import ValidationInfo from pydantic_settings import BaseSettings, SettingsConfigDict from agno.utils.log import logger class AgnoAPISettings(BaseSettings): app_name: str = "agno" app_version: str = metadata.version("agno") api_runtime: str = "prd" alpha_features: bool = False api_url: str = "https://os-api.agno.com" model_config = SettingsConfigDict(env_prefix="AGNO_") @field_validator("api_runtime", mode="before") def validate_runtime_env(cls, v): """Validate api_runtime.""" valid_api_runtimes = ["dev", "stg", "prd"] if v.lower() not in valid_api_runtimes: raise ValueError(f"Invalid api_runtime: {v}") return v.lower() @field_validator("api_url", mode="before") def update_api_url(cls, v, info: ValidationInfo): api_runtime = info.data["api_runtime"] if api_runtime == "dev": from os import getenv if getenv("AGNO_RUNTIME") == "docker": return "http://host.docker.internal:7070" return "http://localhost:7070" elif api_runtime == "stg": return "https://api-stg.agno.com" else: return "https://os-api.agno.com" def gate_alpha_feature(self): if not self.alpha_features: logger.error("This is an Alpha feature not for general use.\nPlease message the Agno team for access.") exit(1) agno_api_settings = AgnoAPISettings()
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/api/settings.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/api/workflow.py
from agno.api.api import api from agno.api.routes import ApiRoutes from agno.api.schemas.workflows import WorkflowRunCreate from agno.utils.log import log_debug def create_workflow_run(workflow: WorkflowRunCreate) -> None: """Telemetry recording for Workflow runs""" with api.Client() as api_client: try: api_client.post( ApiRoutes.RUN_CREATE, json=workflow.model_dump(exclude_none=True), ) except Exception as e: log_debug(f"Could not create Workflow: {e}") async def acreate_workflow_run(workflow: WorkflowRunCreate) -> None: """Telemetry recording for async Workflow runs""" async with api.AsyncClient() as api_client: try: await api_client.post( ApiRoutes.RUN_CREATE, json=workflow.model_dump(exclude_none=True), ) except Exception as e: log_debug(f"Could not create Team: {e}")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/api/workflow.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/cloud/aws/base.py
from typing import Any, Optional from pydantic import BaseModel, ConfigDict from agno.cloud.aws.s3.api_client import AwsApiClient from agno.utils.log import logger class AwsResource(BaseModel): """Base class for AWS Resources.""" # Resource name (required) name: str # Resource type resource_type: Optional[str] = None active_resource: Optional[Any] = None skip_delete: bool = False skip_create: bool = False skip_read: bool = False skip_update: bool = False wait_for_create: bool = True wait_for_update: bool = True wait_for_delete: bool = True waiter_delay: int = 30 waiter_max_attempts: int = 50 save_output: bool = False use_cache: bool = True service_name: str service_client: Optional[Any] = None service_resource: Optional[Any] = None aws_region: Optional[str] = None aws_profile: Optional[str] = None aws_client: Optional[AwsApiClient] = None model_config = ConfigDict(arbitrary_types_allowed=True, populate_by_name=True) def get_resource_name(self) -> str: return self.name or self.__class__.__name__ def get_resource_type(self) -> str: if self.resource_type is None: return self.__class__.__name__ return self.resource_type def get_service_client(self, aws_client: AwsApiClient): from boto3 import session if self.service_client is None: boto3_session: session = aws_client.boto3_session self.service_client = boto3_session.client(service_name=self.service_name) return self.service_client def get_service_resource(self, aws_client: AwsApiClient): from boto3 import session if self.service_resource is None: boto3_session: session = aws_client.boto3_session self.service_resource = boto3_session.resource(service_name=self.service_name) return self.service_resource def get_aws_region(self) -> Optional[str]: if self.aws_region: return self.aws_region from os import getenv aws_region_env = getenv("AWS_REGION") if aws_region_env is not None: logger.debug(f"{'AWS_REGION'}: {aws_region_env}") self.aws_region = aws_region_env return self.aws_region def get_aws_profile(self) -> Optional[str]: if self.aws_profile: return self.aws_profile from os import getenv aws_profile_env = getenv("AWS_PROFILE") if aws_profile_env is not None: logger.debug(f"{'AWS_PROFILE'}: {aws_profile_env}") self.aws_profile = aws_profile_env return self.aws_profile def get_aws_client(self) -> AwsApiClient: if self.aws_client is not None: return self.aws_client self.aws_client = AwsApiClient(aws_region=self.get_aws_region(), aws_profile=self.get_aws_profile()) return self.aws_client def _read(self, aws_client: AwsApiClient) -> Any: logger.warning(f"@_read method not defined for {self.get_resource_name()}") return True def read(self, aws_client: Optional[AwsApiClient] = None) -> Any: """Reads the resource from Aws""" # Step 1: Use cached value if available if self.use_cache and self.active_resource is not None: return self.active_resource # Step 2: Skip resource creation if skip_read = True if self.skip_read: print(f"Skipping read: {self.get_resource_name()}") return True # Step 3: Read resource client: AwsApiClient = aws_client or self.get_aws_client() return self._read(client) def is_active(self, aws_client: AwsApiClient) -> bool: """Returns True if the resource is active on Aws""" _resource = self.read(aws_client=aws_client) return True if _resource is not None else False def _create(self, aws_client: AwsApiClient) -> bool: logger.warning(f"@_create method not defined for {self.get_resource_name()}") return True def create(self, aws_client: Optional[AwsApiClient] = None) -> bool: """Creates the resource on Aws""" # Step 1: Skip resource creation if skip_create = True if self.skip_create: print(f"Skipping create: {self.get_resource_name()}") return True # Step 2: Check if resource is active and use_cache = True client: AwsApiClient = aws_client or self.get_aws_client() if self.use_cache and self.is_active(client): self.resource_created = True print(f"{self.get_resource_type()}: {self.get_resource_name()} already exists") # Step 3: Create the resource else: self.resource_created = self._create(client) if self.resource_created: print(f"{self.get_resource_type()}: {self.get_resource_name()} created") # Step 4: Run post create steps if self.resource_created: logger.debug(f"Running post-create for {self.get_resource_type()}: {self.get_resource_name()}") return self.post_create(client) logger.error(f"Failed to create {self.get_resource_type()}: {self.get_resource_name()}") return self.resource_created def post_create(self, aws_client: AwsApiClient) -> bool: return True def _update(self, aws_client: AwsApiClient) -> Any: logger.warning(f"@_update method not defined for {self.get_resource_name()}") return True def update(self, aws_client: Optional[AwsApiClient] = None) -> bool: """Updates the resource on Aws""" # Step 1: Skip resource update if skip_update = True if self.skip_update: print(f"Skipping update: {self.get_resource_name()}") return True # Step 2: Update the resource client: AwsApiClient = aws_client or self.get_aws_client() if self.is_active(client): self.resource_updated = self._update(client) else: print(f"{self.get_resource_type()}: {self.get_resource_name()} does not exist") return True # Step 3: Run post update steps if self.resource_updated: print(f"{self.get_resource_type()}: {self.get_resource_name()} updated") logger.debug(f"Running post-update for {self.get_resource_type()}: {self.get_resource_name()}") return self.post_update(client) logger.error(f"Failed to update {self.get_resource_type()}: {self.get_resource_name()}") return self.resource_updated def post_update(self, aws_client: AwsApiClient) -> bool: return True def _delete(self, aws_client: AwsApiClient) -> Any: logger.warning(f"@_delete method not defined for {self.get_resource_name()}") return True def delete(self, aws_client: Optional[AwsApiClient] = None) -> bool: """Deletes the resource from Aws""" # Step 1: Skip resource deletion if skip_delete = True if self.skip_delete: print(f"Skipping delete: {self.get_resource_name()}") return True # Step 2: Delete the resource client: AwsApiClient = aws_client or self.get_aws_client() if self.is_active(client): self.resource_deleted = self._delete(client) else: print(f"{self.get_resource_type()}: {self.get_resource_name()} does not exist") return True # Step 3: Run post delete steps if self.resource_deleted: print(f"{self.get_resource_type()}: {self.get_resource_name()} deleted") logger.debug(f"Running post-delete for {self.get_resource_type()}: {self.get_resource_name()}.") return self.post_delete(client) logger.error(f"Failed to delete {self.get_resource_type()}: {self.get_resource_name()}") return self.resource_deleted def post_delete(self, aws_client: AwsApiClient) -> bool: return True
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/cloud/aws/base.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/cloud/aws/s3/bucket.py
from typing import Any, Dict, List, Optional from typing_extensions import Literal from agno.cloud.aws.base import AwsResource from agno.cloud.aws.s3.api_client import AwsApiClient from agno.cloud.aws.s3.object import S3Object from agno.utils.log import logger class S3Bucket(AwsResource): """ Reference: - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#service-resource """ resource_type: str = "s3" service_name: str = "s3" # Name of the bucket name: str # The canned ACL to apply to the bucket. acl: Optional[Literal["private", "public-read", "public-read-write", "authenticated-read"]] = None grant_full_control: Optional[str] = None grant_read: Optional[str] = None grant_read_ACP: Optional[str] = None grant_write: Optional[str] = None grant_write_ACP: Optional[str] = None object_lock_enabled_for_bucket: Optional[bool] = None object_ownership: Optional[Literal["BucketOwnerPreferred", "ObjectWriter", "BucketOwnerEnforced"]] = None @property def uri(self) -> str: """Returns the URI of the s3.Bucket Returns: str: The URI of the s3.Bucket """ return f"s3://{self.name}" def get_resource(self, aws_client: Optional[AwsApiClient] = None) -> Optional[Any]: """Returns the s3.Bucket Args: aws_client: The AwsApiClient for the current cluster """ client: AwsApiClient = aws_client or self.get_aws_client() service_resource = self.get_service_resource(client) return service_resource.Bucket(name=self.name) def _create(self, aws_client: AwsApiClient) -> bool: """Creates the s3.Bucket Args: aws_client: The AwsApiClient for the current cluster """ print(f"Creating {self.get_resource_type()}: {self.get_resource_name()}") # Step 1: Build bucket configuration # Bucket names are GLOBALLY unique! # AWS will give you the IllegalLocationConstraintException if you collide # with an already existing bucket if you've specified a region different than # the region of the already existing bucket. If you happen to guess the correct region of the # existing bucket it will give you the BucketAlreadyExists exception. bucket_configuration = None if aws_client.aws_region is not None and aws_client.aws_region != "us-east-1": bucket_configuration = {"LocationConstraint": aws_client.aws_region} # create a dict of args which are not null, otherwise aws type validation fails not_null_args: Dict[str, Any] = {} if bucket_configuration: not_null_args["CreateBucketConfiguration"] = bucket_configuration if self.acl: not_null_args["ACL"] = self.acl if self.grant_full_control: not_null_args["GrantFullControl"] = self.grant_full_control if self.grant_read: not_null_args["GrantRead"] = self.grant_read if self.grant_read_ACP: not_null_args["GrantReadACP"] = self.grant_read_ACP if self.grant_write: not_null_args["GrantWrite"] = self.grant_write if self.grant_write_ACP: not_null_args["GrantWriteACP"] = self.grant_write_ACP if self.object_lock_enabled_for_bucket: not_null_args["ObjectLockEnabledForBucket"] = self.object_lock_enabled_for_bucket if self.object_ownership: not_null_args["ObjectOwnership"] = self.object_ownership # Step 2: Create Bucket service_client = self.get_service_client(aws_client) try: response = service_client.create_bucket( Bucket=self.name, **not_null_args, ) logger.debug(f"Response: {response}") bucket_location = response.get("Location") if bucket_location is not None: logger.debug(f"Bucket created: {bucket_location}") self.active_resource = response return True except Exception as e: logger.error(f"{self.get_resource_type()} could not be created.") logger.error(e) return False def post_create(self, aws_client: AwsApiClient) -> bool: # Wait for Bucket to be created if self.wait_for_create: try: print(f"Waiting for {self.get_resource_type()} to be created.") waiter = self.get_service_client(aws_client).get_waiter("bucket_exists") waiter.wait( Bucket=self.name, WaiterConfig={ "Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts, }, ) except Exception as e: logger.error("Waiter failed.") logger.error(e) return True def _read(self, aws_client: AwsApiClient) -> Optional[Any]: """Returns the s3.Bucket Args: aws_client: The AwsApiClient for the current cluster """ logger.debug(f"Reading {self.get_resource_type()}: {self.get_resource_name()}") from botocore.exceptions import ClientError try: service_resource = self.get_service_resource(aws_client) bucket = service_resource.Bucket(name=self.name) bucket.load() creation_date = bucket.creation_date logger.debug(f"Bucket creation_date: {creation_date}") if creation_date is not None: logger.debug(f"Bucket found: {bucket.name}") self.active_resource = { "name": bucket.name, "creation_date": creation_date, } except ClientError as ce: logger.debug(f"ClientError: {ce}") except Exception as e: logger.error(f"Error reading {self.get_resource_type()}.") logger.error(e) return self.active_resource def _delete(self, aws_client: AwsApiClient) -> bool: """Deletes the s3.Bucket Args: aws_client: The AwsApiClient for the current cluster """ print(f"Deleting {self.get_resource_type()}: {self.get_resource_name()}") service_client = self.get_service_client(aws_client) self.active_resource = None try: response = service_client.delete_bucket(Bucket=self.name) logger.debug(f"Response: {response}") return True except Exception as e: logger.error(f"{self.get_resource_type()} could not be deleted.") logger.error("Please try again or delete resources manually.") logger.error(e) return False def get_objects(self, aws_client: Optional[AwsApiClient] = None, prefix: Optional[str] = None) -> List[Any]: """Returns a list of s3.Object objects for the s3.Bucket Args: aws_client: The AwsApiClient for the current cluster prefix: Prefix to filter objects by """ bucket = self.get_resource(aws_client) if bucket is None: logger.warning(f"Could not get bucket: {self.name}") return [] logger.debug(f"Getting objects for bucket: {bucket.name}") # Get all objects in bucket object_summaries = bucket.objects.all() all_objects: List[S3Object] = [] for object_summary in object_summaries: if prefix is not None and not object_summary.key.startswith(prefix): continue all_objects.append(S3Object(bucket_name=bucket.name, name=object_summary.key)) return all_objects
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/cloud/aws/s3/bucket.py", "license": "Apache License 2.0", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/cloud/aws/s3/object.py
from pathlib import Path from typing import Any, Optional from agno.cloud.aws.base import AwsResource from agno.cloud.aws.s3.api_client import AwsApiClient from agno.utils.log import logger class S3Object(AwsResource): """ Reference: - https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/object/index.html """ resource_type: str = "s3" service_name: str = "s3" # The Object’s bucket_name identifier. This must be set. bucket_name: str @property def uri(self) -> str: """Returns the URI of the s3.Object Returns: str: The URI of the s3.Object """ return f"s3://{self.bucket_name}/{self.name}" def get_resource(self, aws_client: Optional[AwsApiClient] = None) -> Any: """Returns the s3.Object Args: aws_client: The AwsApiClient for the current cluster Returns: The s3.Object """ client: AwsApiClient = aws_client or self.get_aws_client() service_resource = self.get_service_resource(client) return service_resource.Object( bucket_name=self.bucket_name, key=self.name, ) def download(self, path: Path, aws_client: Optional[AwsApiClient] = None) -> None: """Downloads the s3.Object to the specified path Args: path: The path to download the s3.Object to aws_client: The AwsApiClient for the current cluster """ logger.info(f"Downloading {self.uri} to {path}") object_resource = self.get_resource(aws_client=aws_client) path.parent.mkdir(parents=True, exist_ok=True) with path.open(mode="wb") as f: object_resource.download_fileobj(f)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/cloud/aws/s3/object.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
agno-agi/agno:libs/agno/agno/db/base.py
from abc import ABC, abstractmethod from datetime import date, datetime from enum import Enum from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.schemas import UserMemory from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.run.base import RunStatus from agno.session import Session class SessionType(str, Enum): AGENT = "agent" TEAM = "team" WORKFLOW = "workflow" class ComponentType(str, Enum): AGENT = "agent" TEAM = "team" WORKFLOW = "workflow" class BaseDb(ABC): """Base abstract class for all our Database implementations.""" # We assume the database to be up to date with the 2.0.0 release default_schema_version = "2.0.0" def __init__( self, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, versions_table: Optional[str] = None, components_table: Optional[str] = None, component_configs_table: Optional[str] = None, component_links_table: Optional[str] = None, learnings_table: Optional[str] = None, schedules_table: Optional[str] = None, schedule_runs_table: Optional[str] = None, approvals_table: Optional[str] = None, id: Optional[str] = None, ): self.id = id or str(uuid4()) self.session_table_name = session_table or "agno_sessions" self.culture_table_name = culture_table or "agno_culture" self.memory_table_name = memory_table or "agno_memories" self.metrics_table_name = metrics_table or "agno_metrics" self.eval_table_name = eval_table or "agno_eval_runs" self.knowledge_table_name = knowledge_table or "agno_knowledge" self.trace_table_name = traces_table or "agno_traces" self.span_table_name = spans_table or "agno_spans" self.versions_table_name = versions_table or "agno_schema_versions" self.components_table_name = components_table or "agno_components" self.component_configs_table_name = component_configs_table or "agno_component_configs" self.component_links_table_name = component_links_table or "agno_component_links" self.learnings_table_name = learnings_table or "agno_learnings" self.schedules_table_name = schedules_table or "agno_schedules" self.schedule_runs_table_name = schedule_runs_table or "agno_schedule_runs" self.approvals_table_name = approvals_table or "agno_approvals" def to_dict(self) -> Dict[str, Any]: """ Serialize common DB fields (table names + id). Subclasses may extend this. """ return { "id": self.id, "session_table": self.session_table_name, "culture_table": self.culture_table_name, "memory_table": self.memory_table_name, "metrics_table": self.metrics_table_name, "eval_table": self.eval_table_name, "knowledge_table": self.knowledge_table_name, "traces_table": self.trace_table_name, "spans_table": self.span_table_name, "versions_table": self.versions_table_name, "components_table": self.components_table_name, "component_configs_table": self.component_configs_table_name, "component_links_table": self.component_links_table_name, "learnings_table": self.learnings_table_name, "schedules_table": self.schedules_table_name, "schedule_runs_table": self.schedule_runs_table_name, "approvals_table": self.approvals_table_name, } @classmethod def from_dict(cls, data: Dict[str, Any]) -> "BaseDb": """ Reconstruct using only fields defined in BaseDb. Subclasses should override this. """ return cls( session_table=data.get("session_table"), culture_table=data.get("culture_table"), memory_table=data.get("memory_table"), metrics_table=data.get("metrics_table"), eval_table=data.get("eval_table"), knowledge_table=data.get("knowledge_table"), traces_table=data.get("traces_table"), spans_table=data.get("spans_table"), versions_table=data.get("versions_table"), components_table=data.get("components_table"), component_configs_table=data.get("component_configs_table"), component_links_table=data.get("component_links_table"), learnings_table=data.get("learnings_table"), schedules_table=data.get("schedules_table"), schedule_runs_table=data.get("schedule_runs_table"), approvals_table=data.get("approvals_table"), id=data.get("id"), ) @abstractmethod def table_exists(self, table_name: str) -> bool: raise NotImplementedError def _create_all_tables(self) -> None: """Create all tables for this database.""" pass def close(self) -> None: """Close database connections and release resources. Override in subclasses to properly dispose of connection pools. Should be called during application shutdown. """ pass # --- Schema Version --- @abstractmethod def get_latest_schema_version(self, table_name: str): raise NotImplementedError @abstractmethod def upsert_schema_version(self, table_name: str, version: str): """Upsert the schema version into the database.""" raise NotImplementedError # --- Sessions --- @abstractmethod def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: raise NotImplementedError @abstractmethod def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def get_sessions( self, session_type: SessionType, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False, ) -> List[Union[Session, Dict[str, Any]]]: """Bulk upsert multiple sessions for improved performance on large datasets.""" raise NotImplementedError # --- Memory --- @abstractmethod def clear_memories(self) -> None: raise NotImplementedError @abstractmethod def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]: raise NotImplementedError @abstractmethod def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None, ) -> Optional[Union[UserMemory, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: raise NotImplementedError @abstractmethod def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False, ) -> List[Union[UserMemory, Dict[str, Any]]]: """Bulk upsert multiple memories for improved performance on large datasets.""" raise NotImplementedError # --- Metrics --- @abstractmethod def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[Dict[str, Any]], Optional[int]]: raise NotImplementedError @abstractmethod def calculate_metrics(self) -> Optional[Any]: raise NotImplementedError # --- Knowledge --- @abstractmethod def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. """ raise NotImplementedError @abstractmethod def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. """ raise NotImplementedError @abstractmethod def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ raise NotImplementedError @abstractmethod def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ raise NotImplementedError # --- Evals --- @abstractmethod def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: raise NotImplementedError @abstractmethod def delete_eval_runs(self, eval_run_ids: List[str]) -> None: raise NotImplementedError @abstractmethod def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: raise NotImplementedError @abstractmethod def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: raise NotImplementedError # --- Traces --- @abstractmethod def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ raise NotImplementedError @abstractmethod def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). session_id: Filter by session ID (returns first match). user_id: Filter by user ID (returns first match). agent_id: Filter by agent ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ raise NotImplementedError @abstractmethod def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Supports composable queries with AND/OR/NOT logic and operators like EQ, NEQ, GT, GTE, LT, LTE, IN, CONTAINS, STARTSWITH. Returns: tuple[List[Trace], int]: Tuple of (list of matching traces with datetime fields, total count). """ raise NotImplementedError @abstractmethod def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, first_trace_at (datetime), last_trace_at (datetime). """ raise NotImplementedError # --- Spans --- @abstractmethod def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ raise NotImplementedError @abstractmethod def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ raise NotImplementedError @abstractmethod def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ raise NotImplementedError @abstractmethod def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ raise NotImplementedError # --- Cultural Knowledge --- @abstractmethod def clear_cultural_knowledge(self) -> None: raise NotImplementedError @abstractmethod def delete_cultural_knowledge(self, id: str) -> None: raise NotImplementedError @abstractmethod def get_cultural_knowledge(self, id: str) -> Optional[CulturalKnowledge]: raise NotImplementedError @abstractmethod def get_all_cultural_knowledge( self, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, ) -> Optional[List[CulturalKnowledge]]: raise NotImplementedError @abstractmethod def upsert_cultural_knowledge(self, cultural_knowledge: CulturalKnowledge) -> Optional[CulturalKnowledge]: raise NotImplementedError # --- Components (Optional) --- # These methods are optional. Override in subclasses to enable component persistence. def get_component( self, component_id: str, component_type: Optional[ComponentType] = None, ) -> Optional[Dict[str, Any]]: """Get a component by ID. Args: component_id: The component ID. component_type: Optional filter by type (agent|team|workflow). Returns: Component dictionary or None if not found. """ raise NotImplementedError def upsert_component( self, component_id: str, component_type: Optional[ComponentType] = None, name: Optional[str] = None, description: Optional[str] = None, current_version: Optional[int] = None, metadata: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Create or update a component. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). Required for create, optional for update. name: Display name. description: Optional description. current_version: Optional current version. metadata: Optional metadata dict. Returns: Created/updated component dictionary. Raises: ValueError: If creating and component_type is not provided. """ raise NotImplementedError def delete_component( self, component_id: str, hard_delete: bool = False, ) -> bool: """Delete a component and all its configs/links. Args: component_id: The component ID. hard_delete: If True, permanently delete. Otherwise soft-delete. Returns: True if deleted, False if not found or already deleted. """ raise NotImplementedError def list_components( self, component_type: Optional[ComponentType] = None, include_deleted: bool = False, limit: int = 20, offset: int = 0, exclude_component_ids: Optional[Set[str]] = None, ) -> Tuple[List[Dict[str, Any]], int]: """List components with pagination. Args: component_type: Filter by type (agent|team|workflow). include_deleted: Include soft-deleted components. limit: Maximum number of items to return. offset: Number of items to skip. exclude_component_ids: Component IDs to exclude from results. Returns: Tuple of (list of component dicts, total count). """ raise NotImplementedError def create_component_with_config( self, component_id: str, component_type: ComponentType, name: Optional[str], config: Dict[str, Any], description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, label: Optional[str] = None, stage: str = "draft", notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """Create a component with its initial config atomically. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). name: Display name. config: The config data. description: Optional description. metadata: Optional metadata dict. label: Optional config label. stage: "draft" or "published". notes: Optional notes. links: Optional list of links. Each must have child_version set. Returns: Tuple of (component dict, config dict). Raises: ValueError: If component already exists, invalid stage, or link missing child_version. """ raise NotImplementedError # --- Component Configs (Optional) --- def get_config( self, component_id: str, version: Optional[int] = None, label: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Get a config by component ID and version or label. Args: component_id: The component ID. version: Specific version number. If None, uses current. label: Config label to lookup. Ignored if version is provided. Returns: Config dictionary or None if not found. """ raise NotImplementedError def upsert_config( self, component_id: str, config: Optional[Dict[str, Any]] = None, version: Optional[int] = None, label: Optional[str] = None, stage: Optional[str] = None, notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, Any]: """Create or update a config version for a component. Rules: - Draft configs can be edited freely - Published configs are immutable - Publishing a config automatically sets it as current_version Args: component_id: The component ID. config: The config data. Required for create, optional for update. version: If None, creates new version. If provided, updates that version. label: Optional human-readable label. stage: "draft" or "published". Defaults to "draft" for new configs. notes: Optional notes. links: Optional list of links. Each link must have child_version set. Returns: Created/updated config dictionary. Raises: ValueError: If component doesn't exist, version not found, label conflict, or attempting to update a published config. """ raise NotImplementedError def delete_config( self, component_id: str, version: int, ) -> bool: """Delete a specific config version. Only draft configs can be deleted. Published configs are immutable. Cannot delete the current version. Args: component_id: The component ID. version: The version to delete. Returns: True if deleted, False if not found. Raises: ValueError: If attempting to delete a published or current config. """ raise NotImplementedError def list_configs( self, component_id: str, include_config: bool = False, ) -> List[Dict[str, Any]]: """List all config versions for a component. Args: component_id: The component ID. include_config: If True, include full config blob. Otherwise just metadata. Returns: List of config dictionaries, newest first. Returns empty list if component not found or deleted. """ raise NotImplementedError def set_current_version( self, component_id: str, version: int, ) -> bool: """Set a specific published version as current. Only published configs can be set as current. This is used for rollback scenarios where you want to switch to a previous published version. Args: component_id: The component ID. version: The version to set as current (must be published). Returns: True if successful, False if component or version not found. Raises: ValueError: If attempting to set a draft config as current. """ raise NotImplementedError # --- Component Links (Optional) --- def get_links( self, component_id: str, version: int, link_kind: Optional[str] = None, ) -> List[Dict[str, Any]]: """Get links for a config version. Args: component_id: The component ID. version: The config version. link_kind: Optional filter by link kind (member|step). Returns: List of link dictionaries, ordered by position. """ raise NotImplementedError def get_dependents( self, component_id: str, version: Optional[int] = None, ) -> List[Dict[str, Any]]: """Find all components that reference this component. Args: component_id: The component ID to find dependents of. version: Optional specific version. If None, finds links to any version. Returns: List of link dictionaries showing what depends on this component. """ raise NotImplementedError def load_component_graph( self, component_id: str, version: Optional[int] = None, label: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Load a component with its full resolved graph. Handles cycles by returning a stub with cycle_detected=True. Args: component_id: The component ID. version: Specific version or None for current. label: Optional label of the component. Returns: Dictionary with component, config, children, and resolved_versions. Returns None if component not found. """ raise NotImplementedError # --- Learnings --- @abstractmethod def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Retrieve a learning record. Args: learning_type: Type of learning ('user_profile', 'session_context', etc.) user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). Returns: Dict with 'content' key containing the learning data, or None. """ raise NotImplementedError @abstractmethod def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: """Insert or update a learning record. Args: id: Unique identifier for the learning. learning_type: Type of learning ('user_profile', 'session_context', etc.) content: The learning content as a dict. user_id: Associated user ID. agent_id: Associated agent ID. team_id: Associated team ID. session_id: Associated session ID. namespace: Namespace for scoping ('user', 'global', or custom). entity_id: Associated entity ID (for entity-specific learnings). entity_type: Entity type ('person', 'company', etc.). metadata: Optional metadata. """ raise NotImplementedError @abstractmethod def delete_learning(self, id: str) -> bool: """Delete a learning record. Args: id: The learning ID to delete. Returns: True if deleted, False otherwise. """ raise NotImplementedError @abstractmethod def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: """Get multiple learning records. Args: learning_type: Filter by learning type. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). limit: Maximum number of records to return. Returns: List of learning records. """ raise NotImplementedError # --- Schedules (Optional) --- # These methods are optional. Override in subclasses to enable scheduler persistence. def get_schedule(self, schedule_id: str) -> Optional[Dict[str, Any]]: """Get a schedule by ID.""" raise NotImplementedError def get_schedule_by_name(self, name: str) -> Optional[Dict[str, Any]]: """Get a schedule by name.""" raise NotImplementedError def get_schedules( self, enabled: Optional[bool] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List schedules with optional filtering. Returns: Tuple of (schedules, total_count) """ raise NotImplementedError def create_schedule(self, schedule_data: Dict[str, Any]) -> Dict[str, Any]: """Create a new schedule.""" raise NotImplementedError def update_schedule(self, schedule_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: """Update a schedule by ID.""" raise NotImplementedError def delete_schedule(self, schedule_id: str) -> bool: """Delete a schedule and its associated runs.""" raise NotImplementedError def claim_due_schedule(self, worker_id: str, lock_grace_seconds: int = 300) -> Optional[Dict[str, Any]]: """Atomically claim a due schedule for execution.""" raise NotImplementedError def release_schedule(self, schedule_id: str, next_run_at: Optional[int] = None) -> bool: """Release a claimed schedule and optionally update next_run_at.""" raise NotImplementedError # --- Schedule Runs (Optional) --- def create_schedule_run(self, run_data: Dict[str, Any]) -> Dict[str, Any]: """Create a schedule run record.""" raise NotImplementedError def update_schedule_run(self, schedule_run_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: """Update a schedule run record.""" raise NotImplementedError def get_schedule_run(self, run_id: str) -> Optional[Dict[str, Any]]: """Get a schedule run by ID.""" raise NotImplementedError def get_schedule_runs( self, schedule_id: str, limit: int = 20, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List runs for a schedule. Returns: Tuple of (runs, total_count) """ raise NotImplementedError # --- Approvals (Optional) --- # These methods are optional. Override in subclasses to enable approval persistence. def create_approval(self, approval_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Create an approval record.""" raise NotImplementedError def get_approval(self, approval_id: str) -> Optional[Dict[str, Any]]: """Get an approval by ID.""" raise NotImplementedError def get_approvals( self, status: Optional[str] = None, source_type: Optional[str] = None, approval_type: Optional[str] = None, pause_type: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, user_id: Optional[str] = None, schedule_id: Optional[str] = None, run_id: Optional[str] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List approvals with optional filtering. Returns (items, total_count).""" raise NotImplementedError def update_approval( self, approval_id: str, expected_status: Optional[str] = None, **kwargs: Any ) -> Optional[Dict[str, Any]]: """Update an approval. If expected_status is set, only updates if current status matches (atomic guard).""" raise NotImplementedError def delete_approval(self, approval_id: str) -> bool: """Delete an approval by ID.""" raise NotImplementedError def get_pending_approval_count(self, user_id: Optional[str] = None) -> int: """Get count of pending approvals.""" raise NotImplementedError def update_approval_run_status(self, run_id: str, run_status: RunStatus) -> int: """Update run_status on all approvals for a given run_id. Args: run_id: The run ID to match. run_status: The new run status. Returns: Number of approvals updated. """ raise NotImplementedError class AsyncBaseDb(ABC): """Base abstract class for all our async database implementations.""" def __init__( self, id: Optional[str] = None, session_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, culture_table: Optional[str] = None, versions_table: Optional[str] = None, learnings_table: Optional[str] = None, schedules_table: Optional[str] = None, schedule_runs_table: Optional[str] = None, approvals_table: Optional[str] = None, ): self.id = id or str(uuid4()) self.session_table_name = session_table or "agno_sessions" self.memory_table_name = memory_table or "agno_memories" self.metrics_table_name = metrics_table or "agno_metrics" self.eval_table_name = eval_table or "agno_eval_runs" self.knowledge_table_name = knowledge_table or "agno_knowledge" self.trace_table_name = traces_table or "agno_traces" self.span_table_name = spans_table or "agno_spans" self.culture_table_name = culture_table or "agno_culture" self.versions_table_name = versions_table or "agno_schema_versions" self.learnings_table_name = learnings_table or "agno_learnings" self.schedules_table_name = schedules_table or "agno_schedules" self.schedule_runs_table_name = schedule_runs_table or "agno_schedule_runs" self.approvals_table_name = approvals_table or "agno_approvals" async def _create_all_tables(self) -> None: """Create all tables for this database. Override in subclasses.""" pass async def close(self) -> None: """Close database connections and release resources. Override in subclasses to properly dispose of connection pools. Should be called during application shutdown. """ pass @abstractmethod async def table_exists(self, table_name: str) -> bool: """Check if a table with the given name exists in this database. Default implementation returns True if the table name is configured. Subclasses should override this to perform actual existence checks. Args: table_name: Name of the table to check Returns: bool: True if the table exists, False otherwise """ raise NotImplementedError @abstractmethod async def get_latest_schema_version(self, table_name: str) -> str: raise NotImplementedError @abstractmethod async def upsert_schema_version(self, table_name: str, version: str): """Upsert the schema version into the database.""" raise NotImplementedError # --- Sessions --- @abstractmethod async def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: raise NotImplementedError @abstractmethod async def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod async def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError @abstractmethod async def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod async def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError @abstractmethod async def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: raise NotImplementedError # --- Memory --- @abstractmethod async def clear_memories(self) -> None: raise NotImplementedError @abstractmethod async def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod async def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: raise NotImplementedError @abstractmethod async def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]: raise NotImplementedError @abstractmethod async def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None, ) -> Optional[Union[UserMemory, Dict[str, Any]]]: raise NotImplementedError @abstractmethod async def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod async def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: raise NotImplementedError @abstractmethod async def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: raise NotImplementedError # --- Metrics --- @abstractmethod async def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None ) -> Tuple[List[Dict[str, Any]], Optional[int]]: raise NotImplementedError @abstractmethod async def calculate_metrics(self) -> Optional[Any]: raise NotImplementedError # --- Knowledge --- @abstractmethod async def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. """ raise NotImplementedError @abstractmethod async def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. """ raise NotImplementedError @abstractmethod async def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ raise NotImplementedError @abstractmethod async def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ raise NotImplementedError # --- Evals --- @abstractmethod async def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: raise NotImplementedError @abstractmethod async def delete_eval_runs(self, eval_run_ids: List[str]) -> None: raise NotImplementedError @abstractmethod async def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: raise NotImplementedError @abstractmethod async def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod async def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: raise NotImplementedError # --- Traces --- @abstractmethod async def upsert_trace(self, trace) -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to update (one per trace_id). """ raise NotImplementedError @abstractmethod async def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). session_id: Filter by session ID (returns first match). user_id: Filter by user ID (returns first match). agent_id: Filter by agent ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ raise NotImplementedError @abstractmethod async def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Supports composable queries with AND/OR/NOT logic and operators like EQ, NEQ, GT, GTE, LT, LTE, IN, CONTAINS, STARTSWITH. Returns: tuple[List[Trace], int]: Tuple of (list of matching traces with datetime fields, total count). """ raise NotImplementedError @abstractmethod async def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, first_trace_at (datetime), last_trace_at (datetime). """ raise NotImplementedError # --- Spans --- @abstractmethod async def create_span(self, span) -> None: """Create a single span in the database. Args: span: The Span object to store. """ raise NotImplementedError @abstractmethod async def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ raise NotImplementedError @abstractmethod async def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ raise NotImplementedError @abstractmethod async def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ raise NotImplementedError # --- Cultural Notions --- @abstractmethod async def clear_cultural_knowledge(self) -> None: raise NotImplementedError @abstractmethod async def delete_cultural_knowledge(self, id: str) -> None: raise NotImplementedError @abstractmethod async def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: raise NotImplementedError @abstractmethod async def get_all_cultural_knowledge( self, agent_id: Optional[str] = None, team_id: Optional[str] = None, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: raise NotImplementedError @abstractmethod async def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: raise NotImplementedError # --- Learnings --- @abstractmethod async def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Async retrieve a learning record. Args: learning_type: Type of learning ('user_profile', 'session_context', etc.) user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). Returns: Dict with 'content' key containing the learning data, or None. """ raise NotImplementedError @abstractmethod async def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: """Async insert or update a learning record. Args: id: Unique identifier for the learning. learning_type: Type of learning ('user_profile', 'session_context', etc.) content: The learning content as a dict. user_id: Associated user ID. agent_id: Associated agent ID. team_id: Associated team ID. session_id: Associated session ID. namespace: Namespace for scoping ('user', 'global', or custom). entity_id: Associated entity ID (for entity-specific learnings). entity_type: Entity type ('person', 'company', etc.). metadata: Optional metadata. """ raise NotImplementedError @abstractmethod async def delete_learning(self, id: str) -> bool: """Async delete a learning record. Args: id: The learning ID to delete. Returns: True if deleted, False otherwise. """ raise NotImplementedError @abstractmethod async def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: """Async get multiple learning records. Args: learning_type: Filter by learning type. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). limit: Maximum number of records to return. Returns: List of learning records. """ raise NotImplementedError # --- Schedules (Optional) --- # These methods are optional. Override in subclasses to enable scheduler persistence. async def get_schedule(self, schedule_id: str) -> Optional[Dict[str, Any]]: """Get a schedule by ID.""" raise NotImplementedError async def get_schedule_by_name(self, name: str) -> Optional[Dict[str, Any]]: """Get a schedule by name.""" raise NotImplementedError async def get_schedules( self, enabled: Optional[bool] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List schedules with optional filtering. Returns: Tuple of (schedules, total_count) """ raise NotImplementedError async def create_schedule(self, schedule_data: Dict[str, Any]) -> Dict[str, Any]: """Create a new schedule.""" raise NotImplementedError async def update_schedule(self, schedule_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: """Update a schedule by ID.""" raise NotImplementedError async def delete_schedule(self, schedule_id: str) -> bool: """Delete a schedule and its associated runs.""" raise NotImplementedError async def claim_due_schedule(self, worker_id: str, lock_grace_seconds: int = 300) -> Optional[Dict[str, Any]]: """Atomically claim a due schedule for execution.""" raise NotImplementedError async def release_schedule(self, schedule_id: str, next_run_at: Optional[int] = None) -> bool: """Release a claimed schedule and optionally update next_run_at.""" raise NotImplementedError # --- Schedule Runs (Optional) --- async def create_schedule_run(self, run_data: Dict[str, Any]) -> Dict[str, Any]: """Create a schedule run record.""" raise NotImplementedError async def update_schedule_run(self, schedule_run_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: """Update a schedule run record.""" raise NotImplementedError async def get_schedule_run(self, run_id: str) -> Optional[Dict[str, Any]]: """Get a schedule run by ID.""" raise NotImplementedError async def get_schedule_runs( self, schedule_id: str, limit: int = 20, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List runs for a schedule. Returns: Tuple of (runs, total_count) """ raise NotImplementedError # --- Approvals (Optional) --- # These methods are optional. Override in subclasses to enable approval persistence. async def create_approval(self, approval_data: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Create an approval record.""" raise NotImplementedError async def get_approval(self, approval_id: str) -> Optional[Dict[str, Any]]: """Get an approval by ID.""" raise NotImplementedError async def get_approvals( self, status: Optional[str] = None, source_type: Optional[str] = None, approval_type: Optional[str] = None, pause_type: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, user_id: Optional[str] = None, schedule_id: Optional[str] = None, run_id: Optional[str] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: """List approvals with optional filtering. Returns (items, total_count).""" raise NotImplementedError async def update_approval( self, approval_id: str, expected_status: Optional[str] = None, **kwargs: Any ) -> Optional[Dict[str, Any]]: """Update an approval. If expected_status is set, only updates if current status matches (atomic guard).""" raise NotImplementedError async def delete_approval(self, approval_id: str) -> bool: """Delete an approval by ID.""" raise NotImplementedError async def get_pending_approval_count(self, user_id: Optional[str] = None) -> int: """Get count of pending approvals.""" raise NotImplementedError async def update_approval_run_status(self, run_id: str, run_status: RunStatus) -> int: """Update run_status on all approvals for a given run_id. Args: run_id: The run ID to match. run_status: The new run status. Returns: Number of approvals updated. """ raise NotImplementedError
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/base.py", "license": "Apache License 2.0", "lines": 1540, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/dynamo/dynamo.py
import json import time from datetime import date, datetime, timedelta, timezone from os import getenv from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.dynamo.schemas import get_table_schema_definition from agno.db.dynamo.utils import ( apply_pagination, apply_sorting, build_query_filter_expression, build_topic_filter_expression, calculate_date_metrics, create_table_if_not_exists, deserialize_cultural_knowledge_from_db, deserialize_eval_record, deserialize_from_dynamodb_item, deserialize_knowledge_row, deserialize_session, deserialize_session_result, execute_query_with_pagination, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, merge_with_existing_session, prepare_session_data, serialize_cultural_knowledge_for_db, serialize_eval_record, serialize_knowledge_row, serialize_to_dynamo_item, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info from agno.utils.string import generate_id try: import boto3 # type: ignore[import-untyped] except ImportError: raise ImportError("`boto3` not installed. Please install it using `pip install boto3`") # DynamoDB batch_write_item has a hard limit of 25 items per request DYNAMO_BATCH_SIZE_LIMIT = 25 class DynamoDb(BaseDb): def __init__( self, db_client=None, region_name: Optional[str] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, id: Optional[str] = None, ): """ Interface for interacting with a DynamoDB database. Args: db_client: The DynamoDB client to use. region_name: AWS region name. aws_access_key_id: AWS access key ID. aws_secret_access_key: AWS secret access key. session_table: The name of the session table. culture_table: The name of the culture table. memory_table: The name of the memory table. metrics_table: The name of the metrics table. eval_table: The name of the eval table. knowledge_table: The name of the knowledge table. traces_table: The name of the traces table. spans_table: The name of the spans table. id: ID of the database. """ if id is None: seed = str(db_client) if db_client else f"{region_name}_{aws_access_key_id}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, culture_table=culture_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, traces_table=traces_table, spans_table=spans_table, ) if db_client is not None: self.client = db_client else: if not region_name and not getenv("AWS_REGION"): raise ValueError("AWS_REGION is not set. Please set the AWS_REGION environment variable.") if not aws_access_key_id and not getenv("AWS_ACCESS_KEY_ID"): raise ValueError("AWS_ACCESS_KEY_ID is not set. Please set the AWS_ACCESS_KEY_ID environment variable.") if not aws_secret_access_key and not getenv("AWS_SECRET_ACCESS_KEY"): raise ValueError( "AWS_SECRET_ACCESS_KEY is not set. Please set the AWS_SECRET_ACCESS_KEY environment variable." ) session_kwargs = {} session_kwargs["region_name"] = region_name or getenv("AWS_REGION") session_kwargs["aws_access_key_id"] = aws_access_key_id or getenv("AWS_ACCESS_KEY_ID") session_kwargs["aws_secret_access_key"] = aws_secret_access_key or getenv("AWS_SECRET_ACCESS_KEY") session = boto3.Session(**session_kwargs) self.client = session.client("dynamodb") def table_exists(self, table_name: str) -> bool: """Check if a DynamoDB table exists. Args: table_name: The name of the table to check Returns: bool: True if the table exists, False otherwise """ try: self.client.describe_table(TableName=table_name) return True except self.client.exceptions.ResourceNotFoundException: return False def _create_all_tables(self): """Create all configured DynamoDB tables if they don't exist.""" tables_to_create = [ ("sessions", self.session_table_name), ("memories", self.memory_table_name), ("metrics", self.metrics_table_name), ("evals", self.eval_table_name), ("knowledge", self.knowledge_table_name), ("culture", self.culture_table_name), ] for table_type, table_name in tables_to_create: if not self.table_exists(table_name): schema = get_table_schema_definition(table_type) schema["TableName"] = table_name create_table_if_not_exists(self.client, table_name, schema) def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = True) -> Optional[str]: """ Get table name and ensure the table exists, creating it if needed. Args: table_type: Type of table ("sessions", "memories", "metrics", "evals", "knowledge", "culture", "traces", "spans") Returns: str: The table name Raises: ValueError: If table name is not configured or table type is unknown """ table_name = None if table_type == "sessions": table_name = self.session_table_name elif table_type == "memories": table_name = self.memory_table_name elif table_type == "metrics": table_name = self.metrics_table_name elif table_type == "evals": table_name = self.eval_table_name elif table_type == "knowledge": table_name = self.knowledge_table_name elif table_type == "culture": table_name = self.culture_table_name elif table_type == "traces": table_name = self.trace_table_name elif table_type == "spans": # Ensure traces table exists first (spans reference traces) self._get_table("traces", create_table_if_not_found=True) table_name = self.span_table_name else: raise ValueError(f"Unknown table type: {table_type}") # Check if table exists, create if it doesn't if not self.table_exists(table_name) and create_table_if_not_found: schema = get_table_schema_definition(table_type) schema["TableName"] = table_name create_table_if_not_exists(self.client, table_name, schema) return table_name def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # --- Sessions --- def delete_session(self, session_id: Optional[str] = None, user_id: Optional[str] = None) -> bool: """ Delete a session from the database. Args: session_id: The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If any error occurs while deleting the session. """ if not session_id: return False try: kwargs: Dict[str, Any] = { "TableName": self.session_table_name, "Key": {"session_id": {"S": session_id}}, } if user_id is not None: kwargs["ConditionExpression"] = "user_id = :user_id" kwargs["ExpressionAttributeValues"] = {":user_id": {"S": user_id}} self.client.delete_item(**kwargs) return True except self.client.exceptions.ConditionalCheckFailedException: log_debug(f"No session found to delete with session_id: {session_id} and user_id: {user_id}") return False except Exception as e: log_error(f"Failed to delete session {session_id}: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """ Delete sessions from the database in batches. Args: session_ids: List of session IDs to delete user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If any error occurs while deleting the sessions. """ if not session_ids or not self.session_table_name: return try: if user_id is not None: for session_id in session_ids: try: self.client.delete_item( TableName=self.session_table_name, Key={"session_id": {"S": session_id}}, ConditionExpression="user_id = :user_id", ExpressionAttributeValues={":user_id": {"S": user_id}}, ) except self.client.exceptions.ConditionalCheckFailedException: pass else: for i in range(0, len(session_ids), DYNAMO_BATCH_SIZE_LIMIT): batch = session_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT] delete_requests = [] for session_id in batch: delete_requests.append({"DeleteRequest": {"Key": {"session_id": {"S": session_id}}}}) if delete_requests: self.client.batch_write_item(RequestItems={self.session_table_name: delete_requests}) except Exception as e: log_error(f"Failed to delete sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Get a session from the database as a Session object. Args: session_id (str): The ID of the session to get. session_type (SessionType): The type of session to get. user_id (Optional[str]): The ID of the user to get the session for. deserialize (Optional[bool]): Whether to deserialize the session. Returns: Optional[Session]: The session data as a Session object. Raises: Exception: If any error occurs while getting the session. """ try: table_name = self._get_table("sessions") response = self.client.get_item( TableName=table_name, Key={"session_id": {"S": session_id}}, ) item = response.get("Item") if not item: return None session = deserialize_from_dynamodb_item(item) if user_id is not None and session.get("user_id") != user_id: return None if not session: return None if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Failed to get session {session_id}: {e}") raise e def get_sessions( self, session_type: SessionType, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: try: table_name = self._get_table("sessions") if table_name is None: return [] if deserialize else ([], 0) # Build filter expression for additional filters filter_expression = None expression_attribute_names = {} expression_attribute_values = {":session_type": {"S": session_type.value}} if user_id is not None: filter_expression = "#user_id = :user_id" expression_attribute_names["#user_id"] = "user_id" expression_attribute_values[":user_id"] = {"S": user_id} if component_id: # Map component_id to the appropriate field based on session type if session_type == SessionType.AGENT: component_filter = "#agent_id = :component_id" expression_attribute_names["#agent_id"] = "agent_id" elif session_type == SessionType.TEAM: component_filter = "#team_id = :component_id" expression_attribute_names["#team_id"] = "team_id" else: component_filter = "#workflow_id = :component_id" expression_attribute_names["#workflow_id"] = "workflow_id" if component_filter: expression_attribute_values[":component_id"] = {"S": component_id} if filter_expression: filter_expression += f" AND {component_filter}" else: filter_expression = component_filter if session_name: name_filter = "#session_name = :session_name" expression_attribute_names["#session_name"] = "session_name" expression_attribute_values[":session_name"] = {"S": session_name} if filter_expression: filter_expression += f" AND {name_filter}" else: filter_expression = name_filter # Use GSI query for session_type query_kwargs = { "TableName": table_name, "IndexName": "session_type-created_at-index", "KeyConditionExpression": "session_type = :session_type", "ExpressionAttributeValues": expression_attribute_values, } if filter_expression: query_kwargs["FilterExpression"] = filter_expression if expression_attribute_names: query_kwargs["ExpressionAttributeNames"] = expression_attribute_names # Apply sorting if sort_by == "created_at": query_kwargs["ScanIndexForward"] = sort_order != "desc" # type: ignore # Apply limit at DynamoDB level if limit and not page: query_kwargs["Limit"] = limit # type: ignore items = [] response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) # Handle pagination while "LastEvaluatedKey" in response: query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) # Convert DynamoDB items to session data sessions_data = [] for item in items: session_data = deserialize_from_dynamodb_item(item) if session_data: sessions_data.append(session_data) # Apply in-memory sorting for fields not supported by DynamoDB if sort_by and sort_by != "created_at": sessions_data = apply_sorting(sessions_data, sort_by, sort_order) # Get total count before pagination total_count = len(sessions_data) # Apply pagination if page: sessions_data = apply_pagination(sessions_data, limit, page) if not deserialize: return sessions_data, total_count sessions = [] for session_data in sessions_data: session = deserialize_session(session_data) if session: sessions.append(session) return sessions except Exception as e: log_error(f"Failed to get sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Rename a session in the database. Args: session_id: The ID of the session to rename. session_type: The type of session to rename. session_name: The new name for the session. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: Optional[Session]: The renamed session if successful, None otherwise. Raises: Exception: If any error occurs while renaming the session. """ try: if not self.session_table_name: raise Exception("Sessions table not found") # Get current session_data get_response = self.client.get_item( TableName=self.session_table_name, Key={"session_id": {"S": session_id}}, ) current_item = get_response.get("Item") if not current_item: return None # Verify user_id if provided if user_id is not None: item_data = deserialize_from_dynamodb_item(current_item) if item_data.get("user_id") != user_id: return None # Update session_data with the new session_name session_data = deserialize_from_dynamodb_item(current_item).get("session_data", {}) session_data["session_name"] = session_name condition_expr = "session_type = :session_type" attr_values: Dict[str, Any] = { ":session_data": {"S": json.dumps(session_data)}, ":session_type": {"S": session_type.value}, ":updated_at": {"N": str(int(time.time()))}, } if user_id is not None: condition_expr += " AND user_id = :user_id" attr_values[":user_id"] = {"S": user_id} response = self.client.update_item( TableName=self.session_table_name, Key={"session_id": {"S": session_id}}, UpdateExpression="SET session_data = :session_data, updated_at = :updated_at", ConditionExpression=condition_expr, ExpressionAttributeValues=attr_values, ReturnValues="ALL_NEW", ) item = response.get("Attributes") if not item: return None session = deserialize_from_dynamodb_item(item) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) else: return WorkflowSession.from_dict(session) except Exception as e: log_error(f"Failed to rename session {session_id}: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """ Upsert a session into the database. This method provides true upsert behavior: creates a new session if it doesn't exist, or updates an existing session while preserving important fields. Args: session (Session): The session to upsert. deserialize (Optional[bool]): Whether to deserialize the session. Returns: Optional[Session]: The upserted session if successful, None otherwise. """ try: table_name = self._get_table("sessions", create_table_if_not_found=True) # Get session if it already exists in the db. # We need to do this to handle updating nested fields. response = self.client.get_item(TableName=table_name, Key={"session_id": {"S": session.session_id}}) existing_item = response.get("Item") if existing_item: existing_uid = existing_item.get("user_id", {}).get("S") if existing_uid is not None and existing_uid != session.user_id: return None # Prepare the session to upsert, merging with existing session if it exists. serialized_session = prepare_session_data(session) if existing_item: serialized_session = merge_with_existing_session(serialized_session, existing_item) serialized_session["updated_at"] = int(time.time()) else: serialized_session["updated_at"] = serialized_session["created_at"] item = serialize_to_dynamo_item(serialized_session) put_kwargs: Dict[str, Any] = {"TableName": table_name, "Item": item} expr_names = {"#uid": "user_id"} if session.user_id is not None: put_kwargs["ConditionExpression"] = ( "attribute_not_exists(session_id) OR #uid = :incoming_uid OR attribute_not_exists(#uid)" ) put_kwargs["ExpressionAttributeValues"] = {":incoming_uid": {"S": session.user_id}} else: put_kwargs["ConditionExpression"] = "attribute_not_exists(session_id) OR attribute_not_exists(#uid)" put_kwargs["ExpressionAttributeNames"] = expr_names try: self.client.put_item(**put_kwargs) except self.client.exceptions.ConditionalCheckFailedException: return None return deserialize_session_result(serialized_session, session, deserialize) except Exception as e: log_error(f"Failed to upsert session {session.session_id}: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info( f"DynamoDb doesn't support efficient bulk operations, falling back to individual upserts for {len(sessions)} sessions" ) # Fall back to individual upserts results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] # --- User Memory --- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None) -> None: """ Delete a user memory from the database. Args: memory_id: The ID of the memory to delete. user_id: The ID of the user (optional, for filtering). Raises: Exception: If any error occurs while deleting the user memory. """ try: # If user_id is provided, verify the memory belongs to the user before deleting if user_id is not None: response = self.client.get_item( TableName=self.memory_table_name, Key={"memory_id": {"S": memory_id}}, ) item = response.get("Item") if item: memory_data = deserialize_from_dynamodb_item(item) if memory_data.get("user_id") != user_id: log_debug(f"Memory {memory_id} does not belong to user {user_id}") return self.client.delete_item( TableName=self.memory_table_name, Key={"memory_id": {"S": memory_id}}, ) log_debug(f"Deleted user memory {memory_id}") except Exception as e: log_error(f"Failed to delete user memory {memory_id}: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """ Delete user memories from the database in batches. Args: memory_ids: List of memory IDs to delete user_id: The ID of the user (optional, for filtering). Raises: Exception: If any error occurs while deleting the user memories. """ try: # If user_id is provided, filter memory_ids to only those belonging to the user if user_id is not None: filtered_memory_ids = [] for memory_id in memory_ids: response = self.client.get_item( TableName=self.memory_table_name, Key={"memory_id": {"S": memory_id}}, ) item = response.get("Item") if item: memory_data = deserialize_from_dynamodb_item(item) if memory_data.get("user_id") == user_id: filtered_memory_ids.append(memory_id) memory_ids = filtered_memory_ids for i in range(0, len(memory_ids), DYNAMO_BATCH_SIZE_LIMIT): batch = memory_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT] delete_requests = [] for memory_id in batch: delete_requests.append({"DeleteRequest": {"Key": {"memory_id": {"S": memory_id}}}}) self.client.batch_write_item(RequestItems={self.memory_table_name: delete_requests}) except Exception as e: log_error(f"Failed to delete user memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the database. Args: user_id: The ID of the user (optional, for filtering). Returns: List[str]: List of unique memory topics. """ try: table_name = self._get_table("memories") if table_name is None: return [] # Build filter expression for user_id if provided scan_kwargs = {"TableName": table_name} # Scan the table to get memories response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Extract topics from all memories all_topics = set() for item in items: memory_data = deserialize_from_dynamodb_item(item) topics = memory_data.get("memory", {}).get("topics", []) all_topics.update(topics) return list(all_topics) except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None, ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """ Get a user memory from the database as a UserMemory object. Args: memory_id: The ID of the memory to get. deserialize: Whether to deserialize the memory. user_id: The ID of the user (optional, for filtering). Returns: Optional[UserMemory]: The user memory data if found, None otherwise. Raises: Exception: If any error occurs while getting the user memory. """ try: table_name = self._get_table("memories") response = self.client.get_item(TableName=table_name, Key={"memory_id": {"S": memory_id}}) item = response.get("Item") if not item: return None item = deserialize_from_dynamodb_item(item) # Filter by user_id if provided if user_id and item.get("user_id") != user_id: return None if not deserialize: return item return UserMemory.from_dict(item) except Exception as e: log_error(f"Failed to get user memory {memory_id}: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """ Get user memories from the database as a list of UserMemory objects. Args: user_id: The ID of the user to get the memories for. agent_id: The ID of the agent to get the memories for. team_id: The ID of the team to get the memories for. workflow_id: The ID of the workflow to get the memories for. topics: The topics to filter the memories by. search_content: The content to search for in the memories. limit: The maximum number of memories to return. page: The page number to return. sort_by: The field to sort the memories by. sort_order: The order to sort the memories by. deserialize: Whether to deserialize the memories. Returns: Union[List[UserMemory], List[Dict[str, Any]], Tuple[List[Dict[str, Any]], int]]: The user memories data. Raises: Exception: If any error occurs while getting the user memories. """ try: table_name = self._get_table("memories") if table_name is None: return [] if deserialize else ([], 0) # Build filter expressions for component filters ( filter_expression, expression_attribute_names, expression_attribute_values, ) = build_query_filter_expression(filters={"agent_id": agent_id, "team_id": team_id}) # Build topic filter expression if topics provided if topics: topic_filter, topic_values = build_topic_filter_expression(topics) expression_attribute_values.update(topic_values) filter_expression = f"{filter_expression} AND {topic_filter}" if filter_expression else topic_filter # Add search content filter if provided if search_content: search_filter = "contains(memory, :search_content)" expression_attribute_values[":search_content"] = {"S": search_content} filter_expression = f"{filter_expression} AND {search_filter}" if filter_expression else search_filter # Determine whether to use GSI query or table scan if user_id is not None: # Use GSI query when user_id is provided key_condition_expression = "#user_id = :user_id" # Set up expression attributes for GSI key condition expression_attribute_names["#user_id"] = "user_id" expression_attribute_values[":user_id"] = {"S": user_id} # Execute query with pagination items = execute_query_with_pagination( self.client, table_name, "user_id-updated_at-index", key_condition_expression, expression_attribute_names, expression_attribute_values, filter_expression, sort_by, sort_order, limit, page, ) else: # Use table scan when user_id is None scan_kwargs = {"TableName": table_name} if filter_expression: scan_kwargs["FilterExpression"] = filter_expression if expression_attribute_names: scan_kwargs["ExpressionAttributeNames"] = expression_attribute_names # type: ignore if expression_attribute_values: scan_kwargs["ExpressionAttributeValues"] = expression_attribute_values # type: ignore # Execute scan response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Handle pagination for scan while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) items = [deserialize_from_dynamodb_item(item) for item in items] if sort_by and sort_by != "updated_at": items = apply_sorting(items, sort_by, sort_order) if page: paginated_items = apply_pagination(items, limit, page) if not deserialize: return paginated_items, len(items) return [UserMemory.from_dict(item) for item in items] except Exception as e: log_error(f"Failed to get user memories: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. user_id (Optional[str]): The ID of the user (optional, for filtering). Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. Example: ( [ { "user_id": "123", "total_memories": 10, "last_memory_updated_at": 1714560000, }, ], total_count: 1, ) """ try: table_name = self._get_table("memories") # Build filter expression for user_id if provided filter_expression = None expression_attribute_values = {} if user_id is not None: filter_expression = "user_id = :user_id" expression_attribute_values[":user_id"] = {"S": user_id} scan_kwargs = {"TableName": table_name} if filter_expression: scan_kwargs["FilterExpression"] = filter_expression if expression_attribute_values: scan_kwargs["ExpressionAttributeValues"] = expression_attribute_values # type: ignore response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Aggregate stats by user_id user_stats = {} for item in items: memory_data = deserialize_from_dynamodb_item(item) current_user_id = memory_data.get("user_id") if current_user_id: if current_user_id not in user_stats: user_stats[current_user_id] = { "user_id": current_user_id, "total_memories": 0, "last_memory_updated_at": None, } user_stats[current_user_id]["total_memories"] += 1 updated_at = memory_data.get("updated_at") if updated_at: updated_at_dt = datetime.fromisoformat(updated_at.replace("Z", "+00:00")) updated_at_timestamp = int(updated_at_dt.timestamp()) if updated_at_timestamp and ( user_stats[current_user_id]["last_memory_updated_at"] is None or updated_at_timestamp > user_stats[current_user_id]["last_memory_updated_at"] ): user_stats[current_user_id]["last_memory_updated_at"] = updated_at_timestamp # Convert to list and apply sorting stats_list = list(user_stats.values()) stats_list.sort( key=lambda x: x["last_memory_updated_at"] if x["last_memory_updated_at"] is not None else 0, reverse=True, ) total_count = len(stats_list) # Apply pagination if limit is not None: start_index = 0 if page is not None and page > 1: start_index = (page - 1) * limit stats_list = stats_list[start_index : start_index + limit] return stats_list, total_count except Exception as e: log_error(f"Failed to get user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """ Upsert a user memory into the database. Args: memory: The memory to upsert. Returns: Optional[Dict[str, Any]]: The upserted memory data if successful, None otherwise. """ try: table_name = self._get_table("memories", create_table_if_not_found=True) memory_dict = memory.to_dict() memory_dict["updated_at"] = datetime.now(timezone.utc).isoformat() item = serialize_to_dynamo_item(memory_dict) self.client.put_item(TableName=table_name, Item=item) if not deserialize: return memory_dict return UserMemory.from_dict(memory_dict) except Exception as e: log_error(f"Failed to upsert user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info( f"DynamoDb doesn't support efficient bulk operations, falling back to individual upserts for {len(memories)} memories" ) # Fall back to individual upserts results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: table_name = self._get_table("memories") # Scan the table to get all items response = self.client.scan(TableName=table_name) items = response.get("Items", []) # Handle pagination for scan while "LastEvaluatedKey" in response: response = self.client.scan(TableName=table_name, ExclusiveStartKey=response["LastEvaluatedKey"]) items.extend(response.get("Items", [])) if not items: return # Delete items in batches for i in range(0, len(items), DYNAMO_BATCH_SIZE_LIMIT): batch = items[i : i + DYNAMO_BATCH_SIZE_LIMIT] delete_requests = [] for item in batch: # Extract the memory_id from the item memory_id = item.get("memory_id", {}).get("S") if memory_id: delete_requests.append({"DeleteRequest": {"Key": {"memory_id": {"S": memory_id}}}}) if delete_requests: self.client.batch_write_item(RequestItems={table_name: delete_requests}) except Exception as e: from agno.utils.log import log_warning log_warning(f"Exception deleting all memories: {e}") raise e # --- Metrics --- def calculate_metrics(self) -> Optional[Any]: """Calculate metrics for all dates without complete metrics. Returns: Optional[Any]: The calculated metrics or None if no metrics table. Raises: Exception: If an error occurs during metrics calculation. """ if not self.metrics_table_name: return None try: from agno.utils.log import log_info # Get starting date for metrics calculation starting_date = self._get_metrics_calculation_starting_date() if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None # Get dates that need metrics calculation dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None # Get timestamp range for session data start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) # Get all sessions for the date range sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) # Process session data for metrics calculation all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp, ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None # Calculate metrics for each date results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) # Store metrics in DynamoDB if metrics_records: results = self._bulk_upsert_metrics(metrics_records) log_debug("Updated metrics calculations") return results except Exception as e: log_error(f"Failed to calculate metrics: {e}") raise e def _get_metrics_calculation_starting_date(self) -> Optional[date]: """Get the first date for which metrics calculation is needed: 1. If there are metrics records, return the date of the first day without a complete metrics record. 2. If there are no metrics records, return the date of the first recorded session. 3. If there are no metrics records and no sessions records, return None. Returns: Optional[date]: The starting date for which metrics calculation is needed. """ try: metrics_table_name = self._get_table("metrics") # 1. Check for existing metrics records response = self.client.scan( TableName=metrics_table_name, ProjectionExpression="#date, completed", ExpressionAttributeNames={"#date": "date"}, Limit=1000, # Get reasonable number of records to find incomplete ones ) metrics_items = response.get("Items", []) # Handle pagination to get all metrics records while "LastEvaluatedKey" in response: response = self.client.scan( TableName=metrics_table_name, ProjectionExpression="#date, completed", ExpressionAttributeNames={"#date": "date"}, ExclusiveStartKey=response["LastEvaluatedKey"], Limit=1000, ) metrics_items.extend(response.get("Items", [])) if metrics_items: # Find the latest date with metrics latest_complete_date = None incomplete_dates = [] for item in metrics_items: metrics_data = deserialize_from_dynamodb_item(item) record_date = datetime.fromisoformat(metrics_data["date"]).date() is_completed = metrics_data.get("completed", False) if is_completed: if latest_complete_date is None or record_date > latest_complete_date: latest_complete_date = record_date else: incomplete_dates.append(record_date) # Return the earliest incomplete date, or the day after the latest complete date if incomplete_dates: return min(incomplete_dates) elif latest_complete_date: return latest_complete_date + timedelta(days=1) # 2. No metrics records. Return the date of the first recorded session. sessions_table_name = self._get_table("sessions") earliest_session_date = None for session_type in ["agent", "team", "workflow"]: response = self.client.query( TableName=sessions_table_name, IndexName="session_type-created_at-index", KeyConditionExpression="session_type = :session_type", ExpressionAttributeValues={":session_type": {"S": session_type}}, ScanIndexForward=True, # Ascending order to get earliest Limit=1, ) items = response.get("Items", []) if items: first_session = deserialize_from_dynamodb_item(items[0]) first_session_timestamp = first_session.get("created_at") if first_session_timestamp: session_date = datetime.fromtimestamp(first_session_timestamp, tz=timezone.utc).date() if earliest_session_date is None or session_date < earliest_session_date: earliest_session_date = session_date # 3. Return the earliest session date or None if no sessions exist return earliest_session_date except Exception as e: log_error(f"Failed to get metrics calculation starting date: {e}") raise e def _get_all_sessions_for_metrics_calculation( self, start_timestamp: int, end_timestamp: int ) -> List[Dict[str, Any]]: """Get all sessions within a timestamp range for metrics calculation. Args: start_timestamp: Start timestamp (inclusive) end_timestamp: End timestamp (exclusive) Returns: List[Dict[str, Any]]: List of session data dictionaries """ try: table_name = self._get_table("sessions") all_sessions = [] # Query sessions by different types within the time range for session_type in ["agent", "team", "workflow"]: response = self.client.query( TableName=table_name, IndexName="session_type-created_at-index", KeyConditionExpression="session_type = :session_type AND created_at BETWEEN :start_ts AND :end_ts", ExpressionAttributeValues={ ":session_type": {"S": session_type}, ":start_ts": {"N": str(start_timestamp)}, ":end_ts": {"N": str(end_timestamp)}, }, ) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: response = self.client.query( TableName=table_name, IndexName="session_type-created_at-index", KeyConditionExpression="session_type = :session_type AND created_at BETWEEN :start_ts AND :end_ts", ExpressionAttributeValues={ ":session_type": {"S": session_type}, ":start_ts": {"N": str(start_timestamp)}, ":end_ts": {"N": str(end_timestamp)}, }, ExclusiveStartKey=response["LastEvaluatedKey"], ) items.extend(response.get("Items", [])) # Deserialize sessions for item in items: session_data = deserialize_from_dynamodb_item(item) if session_data: all_sessions.append(session_data) return all_sessions except Exception as e: log_error(f"Failed to get sessions for metrics calculation: {e}") raise e def _bulk_upsert_metrics(self, metrics_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Bulk upsert metrics records into DynamoDB with proper deduplication. Args: metrics_records: List of metrics records to upsert Returns: List[Dict[str, Any]]: List of upserted records """ try: table_name = self._get_table("metrics") if table_name is None: return [] results = [] # Process each record individually to handle proper upsert for record in metrics_records: upserted_record = self._upsert_single_metrics_record(table_name, record) if upserted_record: results.append(upserted_record) return results except Exception as e: log_error(f"Failed to bulk upsert metrics: {e}") raise e def _upsert_single_metrics_record(self, table_name: str, record: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Upsert a single metrics record, checking for existing records with the same date. Args: table_name: The DynamoDB table name record: The metrics record to upsert Returns: Optional[Dict[str, Any]]: The upserted record or None if failed """ try: date_str = record.get("date") if not date_str: log_error("Metrics record missing date field") return None # Convert date object to string if needed if hasattr(date_str, "isoformat"): date_str = date_str.isoformat() # Check if a record already exists for this date existing_record = self._get_existing_metrics_record(table_name, date_str) if existing_record: return self._update_existing_metrics_record(table_name, existing_record, record) else: return self._create_new_metrics_record(table_name, record) except Exception as e: log_error(f"Failed to upsert single metrics record: {e}") raise e def _get_existing_metrics_record(self, table_name: str, date_str: str) -> Optional[Dict[str, Any]]: """Get existing metrics record for a given date. Args: table_name: The DynamoDB table name date_str: The date string to search for Returns: Optional[Dict[str, Any]]: The existing record or None if not found """ try: # Query using the date-aggregation_period-index response = self.client.query( TableName=table_name, IndexName="date-aggregation_period-index", KeyConditionExpression="#date = :date AND aggregation_period = :period", ExpressionAttributeNames={"#date": "date"}, ExpressionAttributeValues={ ":date": {"S": date_str}, ":period": {"S": "daily"}, }, Limit=1, ) items = response.get("Items", []) if items: return deserialize_from_dynamodb_item(items[0]) return None except Exception as e: log_error(f"Failed to get existing metrics record for date {date_str}: {e}") raise e def _update_existing_metrics_record( self, table_name: str, existing_record: Dict[str, Any], new_record: Dict[str, Any], ) -> Optional[Dict[str, Any]]: """Update an existing metrics record. Args: table_name: The DynamoDB table name existing_record: The existing record new_record: The new record data Returns: Optional[Dict[str, Any]]: The updated record or None if failed """ try: # Use the existing record's ID new_record["id"] = existing_record["id"] new_record["updated_at"] = int(time.time()) # Prepare and serialize the record prepared_record = self._prepare_metrics_record_for_dynamo(new_record) item = self._serialize_metrics_to_dynamo_item(prepared_record) # Update the record self.client.put_item(TableName=table_name, Item=item) return new_record except Exception as e: log_error(f"Failed to update existing metrics record: {e}") raise e def _create_new_metrics_record(self, table_name: str, record: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Create a new metrics record. Args: table_name: The DynamoDB table name record: The record to create Returns: Optional[Dict[str, Any]]: The created record or None if failed """ try: # Prepare and serialize the record prepared_record = self._prepare_metrics_record_for_dynamo(record) item = self._serialize_metrics_to_dynamo_item(prepared_record) # Create the record self.client.put_item(TableName=table_name, Item=item) return record except Exception as e: log_error(f"Failed to create new metrics record: {e}") raise e def _prepare_metrics_record_for_dynamo(self, record: Dict[str, Any]) -> Dict[str, Any]: """Prepare a metrics record for DynamoDB serialization by converting all data types properly. Args: record: The metrics record to prepare Returns: Dict[str, Any]: The prepared record ready for DynamoDB serialization """ def convert_value(value): """Recursively convert values to DynamoDB-compatible types.""" if value is None: return None elif isinstance(value, bool): return value elif isinstance(value, (int, float)): return value elif isinstance(value, str): return value elif hasattr(value, "isoformat"): # date/datetime objects return value.isoformat() elif isinstance(value, dict): return {k: convert_value(v) for k, v in value.items()} elif isinstance(value, list): return [convert_value(item) for item in value] else: return str(value) return {key: convert_value(value) for key, value in record.items()} def _serialize_metrics_to_dynamo_item(self, data: Dict[str, Any]) -> Dict[str, Any]: """Serialize metrics data to DynamoDB item format with proper boolean handling. Args: data: The metrics data to serialize Returns: Dict[str, Any]: DynamoDB-ready item """ import json item: Dict[str, Any] = {} for key, value in data.items(): if value is not None: if isinstance(value, bool): item[key] = {"BOOL": value} elif isinstance(value, (int, float)): item[key] = {"N": str(value)} elif isinstance(value, str): item[key] = {"S": str(value)} elif isinstance(value, (dict, list)): item[key] = {"S": json.dumps(value)} else: item[key] = {"S": str(value)} return item def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[Any], Optional[int]]: """ Get metrics from the database. Args: starting_date: The starting date to filter metrics by. ending_date: The ending date to filter metrics by. Returns: Tuple[List[Any], Optional[int]]: A tuple containing the metrics data and the total count. Raises: Exception: If any error occurs while getting the metrics. """ try: table_name = self._get_table("metrics") if table_name is None: return ([], None) # Build query parameters scan_kwargs: Dict[str, Any] = {"TableName": table_name} if starting_date or ending_date: filter_expressions = [] expression_values = {} if starting_date: filter_expressions.append("#date >= :start_date") expression_values[":start_date"] = {"S": starting_date.isoformat()} if ending_date: filter_expressions.append("#date <= :end_date") expression_values[":end_date"] = {"S": ending_date.isoformat()} scan_kwargs["FilterExpression"] = " AND ".join(filter_expressions) scan_kwargs["ExpressionAttributeNames"] = {"#date": "date"} scan_kwargs["ExpressionAttributeValues"] = expression_values # Execute scan response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Convert to metrics data metrics_data = [] for item in items: metric_data = deserialize_from_dynamodb_item(item) if metric_data: metrics_data.append(metric_data) return metrics_data, len(metrics_data) except Exception as e: log_error(f"Failed to get metrics: {e}") raise e # --- Knowledge methods --- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ try: table_name = self._get_table("knowledge") self.client.delete_item(TableName=table_name, Key={"id": {"S": id}}) log_debug(f"Deleted knowledge content {id}") except Exception as e: log_error(f"Failed to delete knowledge content {id}: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. """ try: table_name = self._get_table("knowledge") response = self.client.get_item(TableName=table_name, Key={"id": {"S": id}}) item = response.get("Item") if item: return deserialize_knowledge_row(item) return None except Exception as e: log_error(f"Failed to get knowledge content {id}: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ try: table_name = self._get_table("knowledge") if table_name is None: return [], 0 response = self.client.scan(TableName=table_name) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: response = self.client.scan( TableName=table_name, ExclusiveStartKey=response["LastEvaluatedKey"], ) items.extend(response.get("Items", [])) # Convert to knowledge rows knowledge_rows = [] for item in items: try: knowledge_row = deserialize_knowledge_row(item) knowledge_rows.append(knowledge_row) except Exception as e: log_error(f"Failed to deserialize knowledge row: {e}") # Apply linked_to filter if provided if linked_to is not None: knowledge_rows = [row for row in knowledge_rows if row.linked_to == linked_to] # Apply sorting if sort_by: reverse = sort_order == "desc" knowledge_rows = sorted( knowledge_rows, key=lambda x: getattr(x, sort_by, ""), reverse=reverse, ) # Get total count before pagination total_count = len(knowledge_rows) # Apply pagination if limit: start_index = 0 if page and page > 1: start_index = (page - 1) * limit knowledge_rows = knowledge_rows[start_index : start_index + limit] return knowledge_rows, total_count except Exception as e: log_error(f"Failed to get knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ try: table_name = self._get_table("knowledge", create_table_if_not_found=True) item = serialize_knowledge_row(knowledge_row) self.client.put_item(TableName=table_name, Item=item) return knowledge_row except Exception as e: log_error(f"Failed to upsert knowledge content {knowledge_row.id}: {e}") raise e # --- Eval --- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an eval run in the database. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run, or None if the operation fails. Raises: Exception: If an error occurs during creation. """ try: table_name = self._get_table("evals", create_table_if_not_found=True) item = serialize_eval_record(eval_run) current_time = int(datetime.now(timezone.utc).timestamp()) item["created_at"] = {"N": str(current_time)} item["updated_at"] = {"N": str(current_time)} self.client.put_item(TableName=table_name, Item=item) return eval_run except Exception as e: log_error(f"Failed to create eval run: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: if not eval_run_ids or not self.eval_table_name: return try: for i in range(0, len(eval_run_ids), DYNAMO_BATCH_SIZE_LIMIT): batch = eval_run_ids[i : i + DYNAMO_BATCH_SIZE_LIMIT] delete_requests = [] for eval_run_id in batch: delete_requests.append({"DeleteRequest": {"Key": {"run_id": {"S": eval_run_id}}}}) self.client.batch_write_item(RequestItems={self.eval_table_name: delete_requests}) except Exception as e: log_error(f"Failed to delete eval runs: {e}") raise e def get_eval_run_raw(self, eval_run_id: str, table: Optional[Any] = None) -> Optional[Dict[str, Any]]: if not self.eval_table_name: return None try: response = self.client.get_item(TableName=self.eval_table_name, Key={"run_id": {"S": eval_run_id}}) item = response.get("Item") if item: return deserialize_from_dynamodb_item(item) return None except Exception as e: log_error(f"Failed to get eval run {eval_run_id}: {e}") raise e def get_eval_run(self, eval_run_id: str, table: Optional[Any] = None) -> Optional[EvalRunRecord]: if not self.eval_table_name: return None try: response = self.client.get_item(TableName=self.eval_table_name, Key={"run_id": {"S": eval_run_id}}) item = response.get("Item") if item: return deserialize_eval_record(item) return None except Exception as e: log_error(f"Failed to get eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: try: table_name = self._get_table("evals") if table_name is None: return [] if deserialize else ([], 0) scan_kwargs = {"TableName": table_name} filter_expressions = [] expression_values = {} if agent_id: filter_expressions.append("agent_id = :agent_id") expression_values[":agent_id"] = {"S": agent_id} if team_id: filter_expressions.append("team_id = :team_id") expression_values[":team_id"] = {"S": team_id} if workflow_id: filter_expressions.append("workflow_id = :workflow_id") expression_values[":workflow_id"] = {"S": workflow_id} if model_id: filter_expressions.append("model_id = :model_id") expression_values[":model_id"] = {"S": model_id} if eval_type is not None and len(eval_type) > 0: eval_type_conditions = [] for i, et in enumerate(eval_type): param_name = f":eval_type_{i}" eval_type_conditions.append(f"eval_type = {param_name}") expression_values[param_name] = {"S": str(et.value)} filter_expressions.append(f"({' OR '.join(eval_type_conditions)})") if filter_type is not None: if filter_type == EvalFilterType.AGENT: filter_expressions.append("attribute_exists(agent_id)") elif filter_type == EvalFilterType.TEAM: filter_expressions.append("attribute_exists(team_id)") elif filter_type == EvalFilterType.WORKFLOW: filter_expressions.append("attribute_exists(workflow_id)") if filter_expressions: scan_kwargs["FilterExpression"] = " AND ".join(filter_expressions) if expression_values: scan_kwargs["ExpressionAttributeValues"] = expression_values # type: ignore # Execute scan response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Handle pagination while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Convert to eval data eval_data = [] for item in items: eval_item = deserialize_from_dynamodb_item(item) if eval_item: eval_data.append(eval_item) # Apply sorting eval_data = apply_sorting(eval_data, sort_by, sort_order) # Get total count before pagination total_count = len(eval_data) # Apply pagination eval_data = apply_pagination(eval_data, limit, page) if not deserialize: return eval_data, total_count eval_runs = [] for eval_item in eval_data: eval_run = EvalRunRecord.model_validate(eval_item) eval_runs.append(eval_run) return eval_runs except Exception as e: log_error(f"Failed to get eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: if not self.eval_table_name: return None try: response = self.client.update_item( TableName=self.eval_table_name, Key={"run_id": {"S": eval_run_id}}, UpdateExpression="SET #name = :name, updated_at = :updated_at", ExpressionAttributeNames={"#name": "name"}, ExpressionAttributeValues={ ":name": {"S": name}, ":updated_at": {"N": str(int(time.time()))}, }, ReturnValues="ALL_NEW", ) item = response.get("Attributes") if item is None: return None log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") item = deserialize_from_dynamodb_item(item) return EvalRunRecord.model_validate(item) if deserialize else item except Exception as e: log_error(f"Failed to rename eval run {eval_run_id}: {e}") raise e # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database.""" try: table_name = self._get_table("culture") response = self.client.scan(TableName=table_name, ProjectionExpression="id") with self.client.batch_writer(table_name) as batch: for item in response.get("Items", []): batch.delete_item(Key={"id": item["id"]}) except Exception as e: log_error(f"Failed to clear cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from the database.""" try: table_name = self._get_table("culture") self.client.delete_item(TableName=table_name, Key={"id": {"S": id}}) except Exception as e: log_error(f"Failed to delete cultural knowledge {id}: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from the database.""" try: table_name = self._get_table("culture") response = self.client.get_item(TableName=table_name, Key={"id": {"S": id}}) item = response.get("Item") if not item: return None db_row = deserialize_from_dynamodb_item(item) if not deserialize: return db_row return deserialize_cultural_knowledge_from_db(db_row) except Exception as e: log_error(f"Failed to get cultural knowledge {id}: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from the database.""" try: table_name = self._get_table("culture") # Build filter expression filter_expressions = [] expression_values = {} if name: filter_expressions.append("#name = :name") expression_values[":name"] = {"S": name} if agent_id: filter_expressions.append("agent_id = :agent_id") expression_values[":agent_id"] = {"S": agent_id} if team_id: filter_expressions.append("team_id = :team_id") expression_values[":team_id"] = {"S": team_id} scan_kwargs: Dict[str, Any] = {"TableName": table_name} if filter_expressions: scan_kwargs["FilterExpression"] = " AND ".join(filter_expressions) scan_kwargs["ExpressionAttributeValues"] = expression_values if name: scan_kwargs["ExpressionAttributeNames"] = {"#name": "name"} # Execute scan response = self.client.scan(**scan_kwargs) items = response.get("Items", []) # Continue scanning if there's more data while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Deserialize items from DynamoDB format db_rows = [deserialize_from_dynamodb_item(item) for item in items] # Apply sorting if sort_by: reverse = sort_order == "desc" if sort_order else False db_rows.sort(key=lambda x: x.get(sort_by, ""), reverse=reverse) # Apply pagination total_count = len(db_rows) if limit and page: start = (page - 1) * limit db_rows = db_rows[start : start + limit] elif limit: db_rows = db_rows[:limit] if not deserialize: return db_rows, total_count return [deserialize_cultural_knowledge_from_db(row) for row in db_rows] except Exception as e: log_error(f"Failed to get all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into the database.""" try: from uuid import uuid4 table_name = self._get_table("culture", create_table_if_not_found=True) if not cultural_knowledge.id: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the item dict with serialized content item_dict = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } # Convert to DynamoDB format item = serialize_to_dynamo_item(item_dict) self.client.put_item(TableName=table_name, Item=item) return self.get_cultural_knowledge(cultural_knowledge.id, deserialize=deserialize) except Exception as e: log_error(f"Failed to upsert cultural knowledge: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ try: table_name = self._get_table("traces", create_table_if_not_found=True) if table_name is None: return # Check if trace already exists response = self.client.get_item( TableName=table_name, Key={"trace_id": {"S": trace.trace_id}}, ) existing_item = response.get("Item") if existing_item: # Update existing trace existing = deserialize_from_dynamodb_item(existing_item) # Determine component level for name update priority def get_component_level(workflow_id, team_id, agent_id, name): is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 elif workflow_id: return 3 elif team_id: return 2 elif agent_id: return 1 else: return 0 existing_level = get_component_level( existing.get("workflow_id"), existing.get("team_id"), existing.get("agent_id"), existing.get("name", ""), ) new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) should_update_name = new_level > existing_level # Parse existing start_time to calculate correct duration existing_start_time_str = existing.get("start_time") if isinstance(existing_start_time_str, str): existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00")) else: existing_start_time = trace.start_time recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000) # Build update expression update_parts = [ "end_time = :end_time", "duration_ms = :duration_ms", "#status = :status", ] expression_attr_names = {"#status": "status"} expression_attr_values: Dict[str, Any] = { ":end_time": {"S": trace.end_time.isoformat()}, ":duration_ms": {"N": str(recalculated_duration_ms)}, ":status": {"S": trace.status}, } if should_update_name: update_parts.append("#name = :name") expression_attr_names["#name"] = "name" expression_attr_values[":name"] = {"S": trace.name} if trace.run_id is not None: update_parts.append("run_id = :run_id") expression_attr_values[":run_id"] = {"S": trace.run_id} if trace.session_id is not None: update_parts.append("session_id = :session_id") expression_attr_values[":session_id"] = {"S": trace.session_id} if trace.user_id is not None: update_parts.append("user_id = :user_id") expression_attr_values[":user_id"] = {"S": trace.user_id} if trace.agent_id is not None: update_parts.append("agent_id = :agent_id") expression_attr_values[":agent_id"] = {"S": trace.agent_id} if trace.team_id is not None: update_parts.append("team_id = :team_id") expression_attr_values[":team_id"] = {"S": trace.team_id} if trace.workflow_id is not None: update_parts.append("workflow_id = :workflow_id") expression_attr_values[":workflow_id"] = {"S": trace.workflow_id} self.client.update_item( TableName=table_name, Key={"trace_id": {"S": trace.trace_id}}, UpdateExpression="SET " + ", ".join(update_parts), ExpressionAttributeNames=expression_attr_names, ExpressionAttributeValues=expression_attr_values, ) else: # Create new trace with initialized counters trace_dict = trace.to_dict() trace_dict["total_spans"] = 0 trace_dict["error_count"] = 0 item = serialize_to_dynamo_item(trace_dict) self.client.put_item(TableName=table_name, Item=item) except Exception as e: log_error(f"Error creating trace: {e}") def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace table_name = self._get_table("traces") if table_name is None: return None if trace_id: # Direct lookup by primary key response = self.client.get_item( TableName=table_name, Key={"trace_id": {"S": trace_id}}, ) item = response.get("Item") if item: trace_data = deserialize_from_dynamodb_item(item) trace_data.setdefault("total_spans", 0) trace_data.setdefault("error_count", 0) return Trace.from_dict(trace_data) return None elif run_id: # Query using GSI response = self.client.query( TableName=table_name, IndexName="run_id-start_time-index", KeyConditionExpression="run_id = :run_id", ExpressionAttributeValues={":run_id": {"S": run_id}}, ScanIndexForward=False, # Descending order Limit=1, ) items = response.get("Items", []) if items: trace_data = deserialize_from_dynamodb_item(items[0]) # Use stored values (default to 0 if not present) trace_data.setdefault("total_spans", 0) trace_data.setdefault("error_count", 0) return Trace.from_dict(trace_data) return None else: log_debug("get_trace called without any filter parameters") return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace table_name = self._get_table("traces") if table_name is None: return [], 0 # Determine if we can use a GSI query or need to scan use_gsi = False gsi_name = None key_condition = None key_values: Dict[str, Any] = {} # Check for GSI-compatible filters (only one can be used as key condition) if session_id: use_gsi = True gsi_name = "session_id-start_time-index" key_condition = "session_id = :session_id" key_values[":session_id"] = {"S": session_id} elif user_id is not None: use_gsi = True gsi_name = "user_id-start_time-index" key_condition = "user_id = :user_id" key_values[":user_id"] = {"S": user_id} elif agent_id: use_gsi = True gsi_name = "agent_id-start_time-index" key_condition = "agent_id = :agent_id" key_values[":agent_id"] = {"S": agent_id} elif team_id: use_gsi = True gsi_name = "team_id-start_time-index" key_condition = "team_id = :team_id" key_values[":team_id"] = {"S": team_id} elif workflow_id: use_gsi = True gsi_name = "workflow_id-start_time-index" key_condition = "workflow_id = :workflow_id" key_values[":workflow_id"] = {"S": workflow_id} elif run_id: use_gsi = True gsi_name = "run_id-start_time-index" key_condition = "run_id = :run_id" key_values[":run_id"] = {"S": run_id} elif status: use_gsi = True gsi_name = "status-start_time-index" key_condition = "#status = :status" key_values[":status"] = {"S": status} # Build filter expression for additional filters filter_parts = [] filter_values: Dict[str, Any] = {} expression_attr_names: Dict[str, str] = {} if start_time: filter_parts.append("start_time >= :start_time") filter_values[":start_time"] = {"S": start_time.isoformat()} if end_time: filter_parts.append("end_time <= :end_time") filter_values[":end_time"] = {"S": end_time.isoformat()} if status and gsi_name != "status-start_time-index": filter_parts.append("#status = :filter_status") filter_values[":filter_status"] = {"S": status} expression_attr_names["#status"] = "status" items = [] if use_gsi and gsi_name and key_condition: # Use GSI query query_kwargs: Dict[str, Any] = { "TableName": table_name, "IndexName": gsi_name, "KeyConditionExpression": key_condition, "ExpressionAttributeValues": {**key_values, **filter_values}, "ScanIndexForward": False, # Descending order by start_time } if gsi_name == "status-start_time-index": expression_attr_names["#status"] = "status" if expression_attr_names: query_kwargs["ExpressionAttributeNames"] = expression_attr_names if filter_parts: query_kwargs["FilterExpression"] = " AND ".join(filter_parts) response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response: query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) else: # Use scan scan_kwargs: Dict[str, Any] = {"TableName": table_name} if filter_parts: scan_kwargs["FilterExpression"] = " AND ".join(filter_parts) scan_kwargs["ExpressionAttributeValues"] = filter_values if expression_attr_names: scan_kwargs["ExpressionAttributeNames"] = expression_attr_names response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Deserialize items traces_data = [deserialize_from_dynamodb_item(item) for item in items] # Sort by start_time descending traces_data.sort(key=lambda x: x.get("start_time", ""), reverse=True) # Get total count total_count = len(traces_data) # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_data = traces_data[offset : offset + limit] if limit else traces_data # Use stored total_spans and error_count (default to 0 if not present) traces = [] for trace_data in paginated_data: # Use stored values - these are updated by create_spans trace_data.setdefault("total_spans", 0) trace_data.setdefault("error_count", 0) traces.append(Trace.from_dict(trace_data)) return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, workflow_id, total_traces, first_trace_at, last_trace_at. """ try: table_name = self._get_table("traces") if table_name is None: return [], 0 # Fetch all traces and aggregate in memory (DynamoDB doesn't support GROUP BY) scan_kwargs: Dict[str, Any] = {"TableName": table_name} # Build filter expression filter_parts = [] filter_values: Dict[str, Any] = {} if user_id is not None: filter_parts.append("user_id = :user_id") filter_values[":user_id"] = {"S": user_id} if agent_id: filter_parts.append("agent_id = :agent_id") filter_values[":agent_id"] = {"S": agent_id} if team_id: filter_parts.append("team_id = :team_id") filter_values[":team_id"] = {"S": team_id} if workflow_id: filter_parts.append("workflow_id = :workflow_id") filter_values[":workflow_id"] = {"S": workflow_id} if start_time: filter_parts.append("created_at >= :start_time") filter_values[":start_time"] = {"S": start_time.isoformat()} if end_time: filter_parts.append("created_at <= :end_time") filter_values[":end_time"] = {"S": end_time.isoformat()} # Filter for records with session_id filter_parts.append("attribute_exists(session_id)") if filter_parts: scan_kwargs["FilterExpression"] = " AND ".join(filter_parts) if filter_values: scan_kwargs["ExpressionAttributeValues"] = filter_values # Scan all matching traces items = [] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response: scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Aggregate by session_id session_stats: Dict[str, Dict[str, Any]] = {} for item in items: trace_data = deserialize_from_dynamodb_item(item) session_id = trace_data.get("session_id") if not session_id: continue if session_id not in session_stats: session_stats[session_id] = { "session_id": session_id, "user_id": trace_data.get("user_id"), "agent_id": trace_data.get("agent_id"), "team_id": trace_data.get("team_id"), "workflow_id": trace_data.get("workflow_id"), "total_traces": 0, "first_trace_at": trace_data.get("created_at"), "last_trace_at": trace_data.get("created_at"), } session_stats[session_id]["total_traces"] += 1 created_at = trace_data.get("created_at") if ( created_at and session_stats[session_id]["first_trace_at"] and session_stats[session_id]["last_trace_at"] ): if created_at < session_stats[session_id]["first_trace_at"]: session_stats[session_id]["first_trace_at"] = created_at if created_at > session_stats[session_id]["last_trace_at"]: session_stats[session_id]["last_trace_at"] = created_at # Convert to list and sort by last_trace_at descending stats_list = list(session_stats.values()) stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True) # Convert datetime strings to datetime objects for stat in stats_list: first_trace_at = stat["first_trace_at"] last_trace_at = stat["last_trace_at"] if isinstance(first_trace_at, str): stat["first_trace_at"] = datetime.fromisoformat(first_trace_at.replace("Z", "+00:00")) if isinstance(last_trace_at, str): stat["last_trace_at"] = datetime.fromisoformat(last_trace_at.replace("Z", "+00:00")) # Get total count total_count = len(stats_list) # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_stats = stats_list[offset : offset + limit] if limit else stats_list return paginated_stats, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: table_name = self._get_table("spans", create_table_if_not_found=True) if table_name is None: return span_dict = span.to_dict() # Serialize attributes as JSON string if "attributes" in span_dict and isinstance(span_dict["attributes"], dict): span_dict["attributes"] = json.dumps(span_dict["attributes"]) item = serialize_to_dynamo_item(span_dict) self.client.put_item(TableName=table_name, Item=item) # Increment total_spans and error_count on trace traces_table_name = self._get_table("traces") if traces_table_name: try: update_expr = "ADD total_spans :inc" expr_values: Dict[str, Any] = {":inc": {"N": "1"}} if span.status_code == "ERROR": update_expr += ", error_count :inc" self.client.update_item( TableName=traces_table_name, Key={"trace_id": {"S": span.trace_id}}, UpdateExpression=update_expr, ExpressionAttributeValues=expr_values, ) except Exception as update_error: log_debug(f"Could not update trace span counts: {update_error}") except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: table_name = self._get_table("spans", create_table_if_not_found=True) if table_name is None: return for i in range(0, len(spans), DYNAMO_BATCH_SIZE_LIMIT): batch = spans[i : i + DYNAMO_BATCH_SIZE_LIMIT] put_requests = [] for span in batch: span_dict = span.to_dict() # Serialize attributes as JSON string if "attributes" in span_dict and isinstance(span_dict["attributes"], dict): span_dict["attributes"] = json.dumps(span_dict["attributes"]) item = serialize_to_dynamo_item(span_dict) put_requests.append({"PutRequest": {"Item": item}}) if put_requests: self.client.batch_write_item(RequestItems={table_name: put_requests}) # Update trace with total_spans and error_count using ADD (atomic increment) trace_id = spans[0].trace_id spans_count = len(spans) error_count = sum(1 for s in spans if s.status_code == "ERROR") traces_table_name = self._get_table("traces") if traces_table_name: try: # Use ADD for atomic increment - works even if attributes don't exist yet update_expr = "ADD total_spans :spans_inc" expr_values: Dict[str, Any] = {":spans_inc": {"N": str(spans_count)}} if error_count > 0: update_expr += ", error_count :error_inc" expr_values[":error_inc"] = {"N": str(error_count)} self.client.update_item( TableName=traces_table_name, Key={"trace_id": {"S": trace_id}}, UpdateExpression=update_expr, ExpressionAttributeValues=expr_values, ) except Exception as update_error: log_debug(f"Could not update trace span counts: {update_error}") except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span table_name = self._get_table("spans") if table_name is None: return None response = self.client.get_item( TableName=table_name, Key={"span_id": {"S": span_id}}, ) item = response.get("Item") if item: span_data = deserialize_from_dynamodb_item(item) # Deserialize attributes from JSON string if "attributes" in span_data and isinstance(span_data["attributes"], str): span_data["attributes"] = json.loads(span_data["attributes"]) return Span.from_dict(span_data) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span table_name = self._get_table("spans") if table_name is None: return [] items = [] if trace_id: # Use GSI query query_kwargs: Dict[str, Any] = { "TableName": table_name, "IndexName": "trace_id-start_time-index", "KeyConditionExpression": "trace_id = :trace_id", "ExpressionAttributeValues": {":trace_id": {"S": trace_id}}, } if limit: query_kwargs["Limit"] = limit response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response and (limit is None or len(items) < limit): query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) elif parent_span_id: # Use GSI query query_kwargs = { "TableName": table_name, "IndexName": "parent_span_id-start_time-index", "KeyConditionExpression": "parent_span_id = :parent_span_id", "ExpressionAttributeValues": {":parent_span_id": {"S": parent_span_id}}, } if limit: query_kwargs["Limit"] = limit response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response and (limit is None or len(items) < limit): query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.query(**query_kwargs) items.extend(response.get("Items", [])) else: # Scan all spans scan_kwargs: Dict[str, Any] = {"TableName": table_name} if limit: scan_kwargs["Limit"] = limit response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) while "LastEvaluatedKey" in response and (limit is None or len(items) < limit): scan_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = self.client.scan(**scan_kwargs) items.extend(response.get("Items", [])) # Deserialize items spans = [] for item in items[:limit] if limit else items: span_data = deserialize_from_dynamodb_item(item) # Deserialize attributes from JSON string if "attributes" in span_data and isinstance(span_data["attributes"], str): span_data["attributes"] = json.loads(span_data["attributes"]) spans.append(Span.from_dict(span_data)) return spans except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for DynamoDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for DynamoDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for DynamoDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for DynamoDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/dynamo/dynamo.py", "license": "Apache License 2.0", "lines": 2376, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/dynamo/schemas.py
"""Table schemas and related utils used by the DynamoDb class""" from typing import Any, Dict SESSION_TABLE_SCHEMA = { "TableName": "agno_sessions", "KeySchema": [{"AttributeName": "session_id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "session_id", "AttributeType": "S"}, {"AttributeName": "session_type", "AttributeType": "S"}, {"AttributeName": "user_id", "AttributeType": "S"}, {"AttributeName": "agent_id", "AttributeType": "S"}, {"AttributeName": "team_id", "AttributeType": "S"}, {"AttributeName": "workflow_id", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "N"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "session_type-created_at-index", "KeySchema": [ {"AttributeName": "session_type", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "user_id-created_at-index", "KeySchema": [ {"AttributeName": "user_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "agent_id-created_at-index", "KeySchema": [ {"AttributeName": "agent_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "team_id-created_at-index", "KeySchema": [ {"AttributeName": "team_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "workflow_id-created_at-index", "KeySchema": [ {"AttributeName": "workflow_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } USER_MEMORY_TABLE_SCHEMA = { "TableName": "agno_user_memory", "KeySchema": [{"AttributeName": "memory_id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "memory_id", "AttributeType": "S"}, {"AttributeName": "user_id", "AttributeType": "S"}, {"AttributeName": "agent_id", "AttributeType": "S"}, {"AttributeName": "team_id", "AttributeType": "S"}, {"AttributeName": "workflow_id", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "S"}, {"AttributeName": "updated_at", "AttributeType": "S"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "user_id-updated_at-index", "KeySchema": [ {"AttributeName": "user_id", "KeyType": "HASH"}, {"AttributeName": "updated_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "agent_id-updated_at-index", "KeySchema": [ {"AttributeName": "agent_id", "KeyType": "HASH"}, {"AttributeName": "updated_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "team_id-updated_at-index", "KeySchema": [ {"AttributeName": "team_id", "KeyType": "HASH"}, {"AttributeName": "updated_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "workflow_id-updated_at-index", "KeySchema": [ {"AttributeName": "workflow_id", "KeyType": "HASH"}, {"AttributeName": "updated_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "workflow_id-created_at-index", "KeySchema": [ {"AttributeName": "workflow_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } EVAL_TABLE_SCHEMA = { "TableName": "agno_eval", "KeySchema": [{"AttributeName": "run_id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "run_id", "AttributeType": "S"}, {"AttributeName": "eval_type", "AttributeType": "S"}, {"AttributeName": "agent_id", "AttributeType": "S"}, {"AttributeName": "team_id", "AttributeType": "S"}, {"AttributeName": "workflow_id", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "N"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "eval_type-created_at-index", "KeySchema": [ {"AttributeName": "eval_type", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "agent_id-created_at-index", "KeySchema": [ {"AttributeName": "agent_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "team_id-created_at-index", "KeySchema": [ {"AttributeName": "team_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "workflow_id-created_at-index", "KeySchema": [ {"AttributeName": "workflow_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } KNOWLEDGE_TABLE_SCHEMA = { "TableName": "agno_knowledge", "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "id", "AttributeType": "S"}, {"AttributeName": "user_id", "AttributeType": "S"}, {"AttributeName": "type", "AttributeType": "S"}, {"AttributeName": "status", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "N"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "user_id-created_at-index", "KeySchema": [ {"AttributeName": "user_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "type-created_at-index", "KeySchema": [ {"AttributeName": "type", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "status-created_at-index", "KeySchema": [ {"AttributeName": "status", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } METRICS_TABLE_SCHEMA = { "TableName": "agno_metrics", "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "id", "AttributeType": "S"}, {"AttributeName": "date", "AttributeType": "S"}, {"AttributeName": "aggregation_period", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "N"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "date-aggregation_period-index", "KeySchema": [ {"AttributeName": "date", "KeyType": "HASH"}, {"AttributeName": "aggregation_period", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "created_at-index", "KeySchema": [{"AttributeName": "created_at", "KeyType": "HASH"}], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } CULTURAL_KNOWLEDGE_TABLE_SCHEMA = { "TableName": "agno_cultural_knowledge", "KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "id", "AttributeType": "S"}, {"AttributeName": "name", "AttributeType": "S"}, {"AttributeName": "agent_id", "AttributeType": "S"}, {"AttributeName": "team_id", "AttributeType": "S"}, {"AttributeName": "created_at", "AttributeType": "N"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "name-created_at-index", "KeySchema": [ {"AttributeName": "name", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "agent_id-created_at-index", "KeySchema": [ {"AttributeName": "agent_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "team_id-created_at-index", "KeySchema": [ {"AttributeName": "team_id", "KeyType": "HASH"}, {"AttributeName": "created_at", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } TRACE_TABLE_SCHEMA = { "TableName": "agno_traces", "KeySchema": [{"AttributeName": "trace_id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "trace_id", "AttributeType": "S"}, {"AttributeName": "run_id", "AttributeType": "S"}, {"AttributeName": "session_id", "AttributeType": "S"}, {"AttributeName": "user_id", "AttributeType": "S"}, {"AttributeName": "agent_id", "AttributeType": "S"}, {"AttributeName": "team_id", "AttributeType": "S"}, {"AttributeName": "workflow_id", "AttributeType": "S"}, {"AttributeName": "status", "AttributeType": "S"}, {"AttributeName": "start_time", "AttributeType": "S"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "run_id-start_time-index", "KeySchema": [ {"AttributeName": "run_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "session_id-start_time-index", "KeySchema": [ {"AttributeName": "session_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "user_id-start_time-index", "KeySchema": [ {"AttributeName": "user_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "agent_id-start_time-index", "KeySchema": [ {"AttributeName": "agent_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "team_id-start_time-index", "KeySchema": [ {"AttributeName": "team_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "workflow_id-start_time-index", "KeySchema": [ {"AttributeName": "workflow_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "status-start_time-index", "KeySchema": [ {"AttributeName": "status", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } SPAN_TABLE_SCHEMA = { "TableName": "agno_spans", "KeySchema": [{"AttributeName": "span_id", "KeyType": "HASH"}], "AttributeDefinitions": [ {"AttributeName": "span_id", "AttributeType": "S"}, {"AttributeName": "trace_id", "AttributeType": "S"}, {"AttributeName": "parent_span_id", "AttributeType": "S"}, {"AttributeName": "start_time", "AttributeType": "S"}, ], "GlobalSecondaryIndexes": [ { "IndexName": "trace_id-start_time-index", "KeySchema": [ {"AttributeName": "trace_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, { "IndexName": "parent_span_id-start_time-index", "KeySchema": [ {"AttributeName": "parent_span_id", "KeyType": "HASH"}, {"AttributeName": "start_time", "KeyType": "RANGE"}, ], "Projection": {"ProjectionType": "ALL"}, "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, }, ], "BillingMode": "PROVISIONED", "ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}, } def get_table_schema_definition(table_type: str) -> Dict[str, Any]: """ Get the expected schema definition for the given table. Args: table_type (str): The type of table to get the schema for. Returns: Dict[str, Any]: Dictionary containing DynamoDB table schema definition """ schemas = { "sessions": SESSION_TABLE_SCHEMA, "memories": USER_MEMORY_TABLE_SCHEMA, "evals": EVAL_TABLE_SCHEMA, "knowledge": KNOWLEDGE_TABLE_SCHEMA, "metrics": METRICS_TABLE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA, "traces": TRACE_TABLE_SCHEMA, "spans": SPAN_TABLE_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema.copy() # Return a copy to avoid modifying the original schema
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/dynamo/schemas.py", "license": "Apache License 2.0", "lines": 427, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/dynamo/utils.py
import json import time from datetime import date, datetime, timedelta, timezone from typing import Any, Callable, Dict, List, Optional, Union from uuid import uuid4 from agno.db.base import SessionType from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalRunRecord from agno.db.schemas.knowledge import KnowledgeRow from agno.db.utils import get_sort_value from agno.session import Session from agno.utils.log import log_debug, log_error, log_info # -- Serialization utils -- def serialize_to_dynamo_item(data: Dict[str, Any]) -> Dict[str, Any]: """Serialize the given dict to a valid DynamoDB item Args: data: The dict to serialize Returns: A DynamoDB-ready dict with the serialized data """ item: Dict[str, Any] = {} for key, value in data.items(): if value is not None: if isinstance(value, (int, float)): item[key] = {"N": str(value)} elif isinstance(value, str): item[key] = {"S": value} elif isinstance(value, bool): item[key] = {"BOOL": value} elif isinstance(value, (dict, list)): item[key] = {"S": json.dumps(value)} else: item[key] = {"S": str(value)} return item def deserialize_from_dynamodb_item(item: Dict[str, Any]) -> Dict[str, Any]: data = {} for key, value in item.items(): if "S" in value: try: data[key] = json.loads(value["S"]) except (json.JSONDecodeError, TypeError): data[key] = value["S"] elif "N" in value: data[key] = float(value["N"]) if "." in value["N"] else int(value["N"]) elif "BOOL" in value: data[key] = value["BOOL"] elif "SS" in value: data[key] = value["SS"] elif "NS" in value: data[key] = [float(n) if "." in n else int(n) for n in value["NS"]] elif "M" in value: data[key] = deserialize_from_dynamodb_item(value["M"]) elif "L" in value: data[key] = [deserialize_from_dynamodb_item({"item": item})["item"] for item in value["L"]] return data def serialize_knowledge_row(knowledge: KnowledgeRow) -> Dict[str, Any]: """Convert KnowledgeRow to DynamoDB item format.""" return serialize_to_dynamo_item( { "id": knowledge.id, "name": knowledge.name, "description": knowledge.description, "type": getattr(knowledge, "type", None), "status": getattr(knowledge, "status", None), "status_message": getattr(knowledge, "status_message", None), "metadata": getattr(knowledge, "metadata", None), "size": getattr(knowledge, "size", None), "linked_to": getattr(knowledge, "linked_to", None), "access_count": getattr(knowledge, "access_count", None), "created_at": int(knowledge.created_at) if knowledge.created_at else None, "updated_at": int(knowledge.updated_at) if knowledge.updated_at else None, } ) def deserialize_knowledge_row(item: Dict[str, Any]) -> KnowledgeRow: """Convert DynamoDB item to KnowledgeRow.""" data = deserialize_from_dynamodb_item(item) return KnowledgeRow( id=data["id"], name=data["name"], description=data["description"], metadata=data.get("metadata"), type=data.get("type"), size=data.get("size"), linked_to=data.get("linked_to"), access_count=data.get("access_count"), status=data.get("status"), status_message=data.get("status_message"), created_at=data.get("created_at"), updated_at=data.get("updated_at"), ) def serialize_eval_record(eval_record: EvalRunRecord) -> Dict[str, Any]: """Convert EvalRunRecord to DynamoDB item format.""" return serialize_to_dynamo_item( { "run_id": eval_record.run_id, "eval_type": eval_record.eval_type, "eval_data": eval_record.eval_data, "name": getattr(eval_record, "name", None), "agent_id": getattr(eval_record, "agent_id", None), "team_id": getattr(eval_record, "team_id", None), "workflow_id": getattr(eval_record, "workflow_id", None), "model_id": getattr(eval_record, "model_id", None), "model_provider": getattr(eval_record, "model_provider", None), "evaluated_component_name": getattr(eval_record, "evaluated_component_name", None), } ) def deserialize_eval_record(item: Dict[str, Any]) -> EvalRunRecord: """Convert DynamoDB item to EvalRunRecord.""" data = deserialize_from_dynamodb_item(item) # Convert timestamp fields back to datetime if "created_at" in data and data["created_at"]: data["created_at"] = datetime.fromtimestamp(data["created_at"], tz=timezone.utc) if "updated_at" in data and data["updated_at"]: data["updated_at"] = datetime.fromtimestamp(data["updated_at"], tz=timezone.utc) return EvalRunRecord(run_id=data["run_id"], eval_type=data["eval_type"], eval_data=data["eval_data"]) # -- DB Utils -- def create_table_if_not_exists(dynamodb_client, table_name: str, schema: Dict[str, Any]) -> bool: """Create DynamoDB table if it doesn't exist.""" try: dynamodb_client.describe_table(TableName=table_name) return True except dynamodb_client.exceptions.ResourceNotFoundException: log_info(f"Creating table {table_name}") try: dynamodb_client.create_table(**schema) # Wait for table to be created waiter = dynamodb_client.get_waiter("table_exists") waiter.wait(TableName=table_name) log_debug(f"Table {table_name} created successfully") return True except Exception as e: log_error(f"Failed to create table {table_name}: {e}") return False def apply_pagination( items: List[Dict[str, Any]], limit: Optional[int] = None, page: Optional[int] = None ) -> List[Dict[str, Any]]: """Apply pagination to a list of items.""" if limit is None: return items start_index = 0 if page is not None and page > 1: start_index = (page - 1) * limit return items[start_index : start_index + limit] def apply_sorting( items: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to a list of items. Args: items: The list of dictionaries to sort sort_by: The field to sort by (defaults to 'created_at') sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if not items: return items if sort_by is None: sort_by = "created_at" is_descending = sort_order == "desc" # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( items, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records # -- Session utils -- def prepare_session_data(session: "Session") -> Dict[str, Any]: """Prepare session data for storage by serializing JSON fields and setting session type.""" from agno.session import AgentSession, TeamSession, WorkflowSession serialized_session = session.to_dict() # Handle JSON fields json_fields = ["session_data", "memory", "tools", "functions", "additional_data"] for field in json_fields: if field in serialized_session and serialized_session[field] is not None: if isinstance(serialized_session[field], (dict, list)): serialized_session[field] = json.dumps(serialized_session[field]) # Set the session type if isinstance(session, AgentSession): serialized_session["session_type"] = SessionType.AGENT.value elif isinstance(session, TeamSession): serialized_session["session_type"] = SessionType.TEAM.value elif isinstance(session, WorkflowSession): serialized_session["session_type"] = SessionType.WORKFLOW.value return serialized_session def merge_with_existing_session(new_session: Dict[str, Any], existing_item: Dict[str, Any]) -> Dict[str, Any]: """Merge new session data with existing session, preserving important fields.""" existing_session = deserialize_from_dynamodb_item(existing_item) # Start with existing session as base merged_session = existing_session.copy() if "session_data" in new_session: merged_session_data = merge_session_data( existing_session.get("session_data", {}), new_session.get("session_data", {}) ) merged_session["session_data"] = json.dumps(merged_session_data) for key, value in new_session.items(): if key != "created_at" and key != "session_data" and value is not None: merged_session[key] = value # Always preserve created_at and set updated_at merged_session["created_at"] = existing_session.get("created_at") merged_session["updated_at"] = int(time.time()) return merged_session def merge_session_data(existing_data: Any, new_data: Any) -> Dict[str, Any]: """Merge session_data fields, handling JSON string conversion.""" # Parse existing session_data if isinstance(existing_data, str): existing_data = json.loads(existing_data) existing_data = existing_data or {} # Parse new session_data if isinstance(new_data, str): new_data = json.loads(new_data) new_data = new_data or {} # Merge letting new data take precedence return {**existing_data, **new_data} def deserialize_session_result( serialized_session: Dict[str, Any], original_session: "Session", deserialize: Optional[bool] ) -> Optional[Union["Session", Dict[str, Any]]]: """Deserialize the session result based on the deserialize flag and session type.""" from agno.session import AgentSession, TeamSession, WorkflowSession if not deserialize: return serialized_session if isinstance(original_session, AgentSession): return AgentSession.from_dict(serialized_session) elif isinstance(original_session, TeamSession): return TeamSession.from_dict(serialized_session) elif isinstance(original_session, WorkflowSession): return WorkflowSession.from_dict(serialized_session) return None def deserialize_session(session: Dict[str, Any]) -> Optional[Session]: """Deserialize session data from DynamoDB format to Session object.""" try: deserialized = session.copy() # Handle JSON fields json_fields = ["session_data", "memory", "tools", "functions", "additional_data"] for field in json_fields: if field in deserialized and deserialized[field] is not None: if isinstance(deserialized[field], str): try: deserialized[field] = json.loads(deserialized[field]) except json.JSONDecodeError: log_error(f"Failed to deserialize {field} field") deserialized[field] = None # Handle timestamp fields for field in ["created_at", "updated_at"]: if field in deserialized and deserialized[field] is not None: if isinstance(deserialized[field], (int, float)): deserialized[field] = datetime.fromtimestamp(deserialized[field], tz=timezone.utc) elif isinstance(deserialized[field], str): try: deserialized[field] = datetime.fromisoformat(deserialized[field]) except ValueError: deserialized[field] = datetime.fromtimestamp(float(deserialized[field]), tz=timezone.utc) return Session.from_dict(deserialized) # type: ignore except Exception as e: log_error(f"Failed to deserialize session: {e}") return None # -- Metrics utils -- def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: sessions: List of session data dictionaries dates_to_process (list[date]): The dates to fetch session data for. start_timestamp: The start timestamp for the range Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def fetch_all_sessions_data_by_type( dynamodb_client, table_name: str, session_type: str, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, ) -> List[Dict[str, Any]]: """Fetch all sessions data from DynamoDB table using GSI for session_type.""" items = [] try: # Build filter expression for additional filters filter_expression = None expression_attribute_names = {} expression_attribute_values = {":session_type": {"S": session_type}} if user_id is not None: filter_expression = "#user_id = :user_id" expression_attribute_names["#user_id"] = "user_id" expression_attribute_values[":user_id"] = {"S": user_id} if component_id: component_filter = "#component_id = :component_id" expression_attribute_names["#component_id"] = "component_id" expression_attribute_values[":component_id"] = {"S": component_id} if filter_expression: filter_expression += f" AND {component_filter}" else: filter_expression = component_filter if session_name: name_filter = "#session_name = :session_name" expression_attribute_names["#session_name"] = "session_name" expression_attribute_values[":session_name"] = {"S": session_name} if filter_expression: filter_expression += f" AND {name_filter}" else: filter_expression = name_filter # Use GSI query for session_type (more efficient than scan) query_kwargs = { "TableName": table_name, "IndexName": "session_type-created_at-index", "KeyConditionExpression": "session_type = :session_type", "ExpressionAttributeValues": expression_attribute_values, } if filter_expression: query_kwargs["FilterExpression"] = filter_expression if expression_attribute_names: query_kwargs["ExpressionAttributeNames"] = expression_attribute_names response = dynamodb_client.query(**query_kwargs) items.extend(response.get("Items", [])) # Handle pagination while "LastEvaluatedKey" in response: query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = dynamodb_client.query(**query_kwargs) items.extend(response.get("Items", [])) except Exception as e: log_error(f"Failed to fetch sessions: {e}") return items def bulk_upsert_metrics(dynamodb_client, table_name: str, metrics_data: List[Dict[str, Any]]) -> None: """Bulk upsert metrics data to DynamoDB.""" try: # DynamoDB batch write has a limit of 25 items batch_size = 25 for i in range(0, len(metrics_data), batch_size): batch = metrics_data[i : i + batch_size] request_items: Dict[str, List[Dict[str, Any]]] = {table_name: []} for metric in batch: request_items[table_name].append({"PutRequest": {"Item": metric}}) dynamodb_client.batch_write_item(RequestItems=request_items) except Exception as e: log_error(f"Failed to bulk upsert metrics: {e}") # -- Query utils -- def build_query_filter_expression(filters: Dict[str, Any]) -> tuple[Optional[str], Dict[str, str], Dict[str, Any]]: """Build DynamoDB query filter expression from filters dictionary. Args: filters: Dictionary of filter key-value pairs Returns: Tuple of (filter_expression, expression_attribute_names, expression_attribute_values) """ filter_expressions = [] expression_attribute_names = {} expression_attribute_values = {} for field, value in filters.items(): if value is not None: filter_expressions.append(f"#{field} = :{field}") expression_attribute_names[f"#{field}"] = field expression_attribute_values[f":{field}"] = {"S": value} filter_expression = " AND ".join(filter_expressions) if filter_expressions else None return filter_expression, expression_attribute_names, expression_attribute_values def build_topic_filter_expression(topics: List[str]) -> tuple[str, Dict[str, Any]]: """Build DynamoDB filter expression for topics. Args: topics: List of topics to filter by Returns: Tuple of (filter_expression, expression_attribute_values) """ topic_filters = [] expression_attribute_values = {} for i, topic in enumerate(topics): topic_key = f":topic_{i}" topic_filters.append(f"contains(topics, {topic_key})") expression_attribute_values[topic_key] = {"S": topic} filter_expression = f"({' OR '.join(topic_filters)})" return filter_expression, expression_attribute_values def execute_query_with_pagination( dynamodb_client, table_name: str, index_name: str, key_condition_expression: str, expression_attribute_names: Dict[str, str], expression_attribute_values: Dict[str, Any], filter_expression: Optional[str] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, ) -> List[Dict[str, Any]]: """Execute DynamoDB query with pagination support. Args: dynamodb_client: DynamoDB client table_name: Table name index_name: Index name for query key_condition_expression: Key condition expression expression_attribute_names: Expression attribute names expression_attribute_values: Expression attribute values filter_expression: Optional filter expression sort_by: Field to sort by sort_order: Sort order (asc/desc) limit: Limit for pagination page: Page number Returns: List of DynamoDB items """ query_kwargs = { "TableName": table_name, "IndexName": index_name, "KeyConditionExpression": key_condition_expression, "ExpressionAttributeValues": expression_attribute_values, } if expression_attribute_names: query_kwargs["ExpressionAttributeNames"] = expression_attribute_names if filter_expression: query_kwargs["FilterExpression"] = filter_expression # Apply sorting at query level if sorting by created_at if sort_by == "created_at": query_kwargs["ScanIndexForward"] = sort_order != "desc" # type: ignore # Apply limit at DynamoDB level if no pagination if limit and not page: query_kwargs["Limit"] = limit # type: ignore items = [] response = dynamodb_client.query(**query_kwargs) items.extend(response.get("Items", [])) # Handle pagination while "LastEvaluatedKey" in response: query_kwargs["ExclusiveStartKey"] = response["LastEvaluatedKey"] response = dynamodb_client.query(**query_kwargs) items.extend(response.get("Items", [])) return items def process_query_results( items: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, deserialize_func: Optional[Callable] = None, deserialize: bool = True, ) -> Union[List[Any], tuple[List[Any], int]]: """Process query results with sorting, pagination, and deserialization. Args: items: List of DynamoDB items sort_by: Field to sort by sort_order: Sort order (asc/desc) limit: Limit for pagination page: Page number deserialize_func: Function to deserialize items deserialize: Whether to deserialize items Returns: List of processed items or tuple of (items, total_count) """ # Convert DynamoDB items to data processed_data = [] for item in items: data = deserialize_from_dynamodb_item(item) if data: processed_data.append(data) # Apply in-memory sorting for fields not handled by DynamoDB if sort_by and sort_by != "created_at": processed_data = apply_sorting(processed_data, sort_by, sort_order) # Get total count before pagination total_count = len(processed_data) # Apply pagination if page: processed_data = apply_pagination(processed_data, limit, page) if not deserialize or not deserialize_func: return processed_data, total_count # Deserialize items deserialized_items = [] for data in processed_data: try: item = deserialize_func(data) if item: deserialized_items.append(item) except Exception as e: log_error(f"Failed to deserialize item: {e}") return deserialized_items # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single JSON dict for the database content column. DynamoDB supports nested maps/dicts natively. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/dynamo/utils.py", "license": "Apache License 2.0", "lines": 620, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/firestore/firestore.py
import json import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union, cast from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.firestore.utils import ( apply_pagination, apply_pagination_to_records, apply_sorting, apply_sorting_to_records, bulk_upsert_metrics, calculate_date_metrics, create_collection_indexes, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.db.utils import deserialize_session_json_fields from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info from agno.utils.string import generate_id try: from google.cloud.firestore import Client, FieldFilter # type: ignore[import-untyped] except ImportError: raise ImportError( "`google-cloud-firestore` not installed. Please install it using `pip install google-cloud-firestore`" ) class FirestoreDb(BaseDb): def __init__( self, db_client: Optional[Client] = None, project_id: Optional[str] = None, session_collection: Optional[str] = None, memory_collection: Optional[str] = None, metrics_collection: Optional[str] = None, eval_collection: Optional[str] = None, knowledge_collection: Optional[str] = None, culture_collection: Optional[str] = None, traces_collection: Optional[str] = None, spans_collection: Optional[str] = None, id: Optional[str] = None, ): """ Interface for interacting with a Firestore database. Args: db_client (Optional[Client]): The Firestore client to use. project_id (Optional[str]): The GCP project ID for Firestore. session_collection (Optional[str]): Name of the collection to store sessions. memory_collection (Optional[str]): Name of the collection to store memories. metrics_collection (Optional[str]): Name of the collection to store metrics. eval_collection (Optional[str]): Name of the collection to store evaluation runs. knowledge_collection (Optional[str]): Name of the collection to store knowledge documents. culture_collection (Optional[str]): Name of the collection to store cultural knowledge. traces_collection (Optional[str]): Name of the collection to store traces. spans_collection (Optional[str]): Name of the collection to store spans. id (Optional[str]): ID of the database. Raises: ValueError: If neither project_id nor db_client is provided. """ if id is None: seed = project_id or str(db_client) id = generate_id(seed) super().__init__( id=id, session_table=session_collection, memory_table=memory_collection, metrics_table=metrics_collection, eval_table=eval_collection, knowledge_table=knowledge_collection, culture_table=culture_collection, traces_table=traces_collection, spans_table=spans_collection, ) _client: Optional[Client] = db_client if _client is None and project_id is not None: _client = Client(project=project_id) if _client is None: raise ValueError("One of project_id or db_client must be provided") self.project_id: Optional[str] = project_id self.db_client: Client = _client # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a collection with the given name exists in the Firestore database. Args: table_name: Name of the collection to check Returns: bool: True if the collection exists in the database, False otherwise """ return table_name in self.db_client.list_collections() def _get_collection(self, table_type: str, create_collection_if_not_found: Optional[bool] = True): """Get or create a collection based on table type. Args: table_type (str): The type of table to get or create. create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist. Returns: CollectionReference: The collection reference. """ if table_type == "sessions": if self.session_table_name is None: raise ValueError("Session collection was not provided on initialization") self.session_collection = self._get_or_create_collection( collection_name=self.session_table_name, collection_type="sessions", create_collection_if_not_found=create_collection_if_not_found, ) return self.session_collection if table_type == "memories": if self.memory_table_name is None: raise ValueError("Memory collection was not provided on initialization") self.memory_collection = self._get_or_create_collection( collection_name=self.memory_table_name, collection_type="memories", create_collection_if_not_found=create_collection_if_not_found, ) return self.memory_collection if table_type == "metrics": if self.metrics_table_name is None: raise ValueError("Metrics collection was not provided on initialization") self.metrics_collection = self._get_or_create_collection( collection_name=self.metrics_table_name, collection_type="metrics", create_collection_if_not_found=create_collection_if_not_found, ) return self.metrics_collection if table_type == "evals": if self.eval_table_name is None: raise ValueError("Eval collection was not provided on initialization") self.eval_collection = self._get_or_create_collection( collection_name=self.eval_table_name, collection_type="evals", create_collection_if_not_found=create_collection_if_not_found, ) return self.eval_collection if table_type == "knowledge": if self.knowledge_table_name is None: raise ValueError("Knowledge collection was not provided on initialization") self.knowledge_collection = self._get_or_create_collection( collection_name=self.knowledge_table_name, collection_type="knowledge", create_collection_if_not_found=create_collection_if_not_found, ) return self.knowledge_collection if table_type == "culture": if self.culture_table_name is None: raise ValueError("Culture collection was not provided on initialization") self.culture_collection = self._get_or_create_collection( collection_name=self.culture_table_name, collection_type="culture", create_collection_if_not_found=create_collection_if_not_found, ) return self.culture_collection if table_type == "traces": if self.trace_table_name is None: raise ValueError("Traces collection was not provided on initialization") self.traces_collection = self._get_or_create_collection( collection_name=self.trace_table_name, collection_type="traces", create_collection_if_not_found=create_collection_if_not_found, ) return self.traces_collection if table_type == "spans": # Ensure traces collection exists first (spans reference traces) if create_collection_if_not_found: self._get_collection("traces", create_collection_if_not_found=True) if self.span_table_name is None: raise ValueError("Spans collection was not provided on initialization") self.spans_collection = self._get_or_create_collection( collection_name=self.span_table_name, collection_type="spans", create_collection_if_not_found=create_collection_if_not_found, ) return self.spans_collection raise ValueError(f"Unknown table type: {table_type}") def _get_or_create_collection( self, collection_name: str, collection_type: str, create_collection_if_not_found: Optional[bool] = True ): """Get or create a collection with proper indexes. Args: collection_name (str): The name of the collection to get or create. collection_type (str): The type of collection to get or create. create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist. Returns: Optional[CollectionReference]: The collection reference. """ try: collection_ref = self.db_client.collection(collection_name) if not hasattr(self, f"_{collection_name}_initialized"): if not create_collection_if_not_found: return None create_collection_indexes(self.db_client, collection_name, collection_type) setattr(self, f"_{collection_name}_initialized", True) return collection_ref except Exception as e: log_error(f"Error getting collection {collection_name}: {e}") raise # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from the database. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If there is an error deleting the session. """ try: collection_ref = self._get_collection(table_type="sessions") query = collection_ref.where(filter=FieldFilter("session_id", "==", session_id)) if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) docs = query.stream() for doc in docs: doc.reference.delete() log_debug(f"Successfully deleted session with session_id: {session_id}") return True log_debug(f"No session found to delete with session_id: {session_id}") return False except Exception as e: log_error(f"Error deleting session: {e}") raise e def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from the database. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. """ try: collection_ref = self._get_collection(table_type="sessions") batch = self.db_client.batch() deleted_count = 0 for session_id in session_ids: query = collection_ref.where(filter=FieldFilter("session_id", "==", session_id)) if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) docs = query.stream() for doc in docs: batch.delete(doc.reference) deleted_count += 1 batch.commit() log_debug(f"Successfully deleted {deleted_count} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Read a session from the database. Args: session_id (str): The ID of the session to get. session_type (SessionType): The type of session to get. user_id (Optional[str]): The ID of the user to get the session for. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If there is an error reading the session. """ try: collection_ref = self._get_collection(table_type="sessions") query = collection_ref.where(filter=FieldFilter("session_id", "==", session_id)) if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) docs = query.stream() result = None for doc in docs: result = doc.to_dict() break if result is None: return None session = deserialize_session_json_fields(result) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading session: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions. Args: session_type (Optional[SessionType]): The type of session to get. user_id (Optional[str]): The ID of the user to get the session for. component_id (Optional[str]): The ID of the component to get the session for. session_name (Optional[str]): The name of the session to filter by. start_timestamp (Optional[int]): The start timestamp to filter sessions by. end_timestamp (Optional[int]): The end timestamp to filter sessions by. limit (Optional[int]): The limit of the sessions to get. page (Optional[int]): The page number to get. sort_by (Optional[str]): The field to sort the sessions by. sort_order (Optional[str]): The order to sort the sessions by. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. Returns: Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of Session objects - When deserialize=False: List of session dictionaries and the total count Raises: Exception: If there is an error reading the sessions. """ try: collection_ref = self._get_collection(table_type="sessions") if collection_ref is None: return [] if deserialize else ([], 0) query = collection_ref if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) if session_type is not None: query = query.where(filter=FieldFilter("session_type", "==", session_type.value)) if component_id is not None: if session_type == SessionType.AGENT: query = query.where(filter=FieldFilter("agent_id", "==", component_id)) elif session_type == SessionType.TEAM: query = query.where(filter=FieldFilter("team_id", "==", component_id)) elif session_type == SessionType.WORKFLOW: query = query.where(filter=FieldFilter("workflow_id", "==", component_id)) if start_timestamp is not None: query = query.where(filter=FieldFilter("created_at", ">=", start_timestamp)) if end_timestamp is not None: query = query.where(filter=FieldFilter("created_at", "<=", end_timestamp)) if session_name is not None: query = query.where(filter=FieldFilter("session_data.session_name", "==", session_name)) # Apply sorting query = apply_sorting(query, sort_by, sort_order) # Get all documents for counting before pagination all_docs = query.stream() all_records = [doc.to_dict() for doc in all_docs] if not all_records: return [] if deserialize else ([], 0) all_sessions_raw = [deserialize_session_json_fields(record) for record in all_records] # Get total count before pagination total_count = len(all_sessions_raw) # Apply pagination to the results if limit is not None and page is not None: start_index = (page - 1) * limit end_index = start_index + limit sessions_raw = all_sessions_raw[start_index:end_index] elif limit is not None: sessions_raw = all_sessions_raw[:limit] else: sessions_raw = all_sessions_raw if not deserialize: return sessions_raw, total_count sessions: List[Union[AgentSession, TeamSession, WorkflowSession]] = [] for session in sessions_raw: if session["session_type"] == SessionType.AGENT.value: agent_session = AgentSession.from_dict(session) if agent_session is not None: sessions.append(agent_session) elif session["session_type"] == SessionType.TEAM.value: team_session = TeamSession.from_dict(session) if team_session is not None: sessions.append(team_session) elif session["session_type"] == SessionType.WORKFLOW.value: workflow_session = WorkflowSession.from_dict(session) if workflow_session is not None: sessions.append(workflow_session) if not sessions: return [] if deserialize else ([], 0) return sessions except Exception as e: log_error(f"Exception reading sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name of the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If there is an error renaming the session. """ try: collection_ref = self._get_collection(table_type="sessions") query = collection_ref.where(filter=FieldFilter("session_id", "==", session_id)) if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) docs = query.stream() doc_ref = next((doc.reference for doc in docs), None) if doc_ref is None: return None # Check if session_data is stored as JSON string (legacy) or native map. # Legacy sessions stored session_data as a JSON string, but Firestore's dot notation # (e.g., "session_data.session_name") only works with native maps. Using dot notation # on a JSON string overwrites the entire field, causing data loss. # For legacy sessions, we use read-modify-write which also migrates them to native maps. current_doc = doc_ref.get() if not current_doc.exists: return None current_data = current_doc.to_dict() session_data = current_data.get("session_data") if current_data else None if session_data is None or isinstance(session_data, str): existing_session = self.get_session(session_id, session_type, user_id=user_id, deserialize=True) if existing_session is None: return None existing_session = cast(Session, existing_session) if existing_session.session_data is None: existing_session.session_data = {} existing_session.session_data["session_name"] = session_name return self.upsert_session(existing_session, deserialize=deserialize) # Native map format - use efficient dot notation update doc_ref.update({"session_data.session_name": session_name, "updated_at": int(time.time())}) updated_doc = doc_ref.get() if not updated_doc.exists: return None result = updated_doc.to_dict() if result is None: return None deserialized_session = deserialize_session_json_fields(result) log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") if not deserialize: return deserialized_session if session_type == SessionType.AGENT: return AgentSession.from_dict(deserialized_session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(deserialized_session) else: return WorkflowSession.from_dict(deserialized_session) except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """Insert or update a session in the database. Args: session (Session): The session to upsert. Returns: Optional[Session]: The upserted session. Raises: Exception: If there is an error upserting the session. """ try: collection_ref = self._get_collection(table_type="sessions", create_collection_if_not_found=True) session_dict = session.to_dict() if isinstance(session, AgentSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } elif isinstance(session, TeamSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } elif isinstance(session, WorkflowSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } # Find existing document or create new one docs = collection_ref.where(filter=FieldFilter("session_id", "==", record["session_id"])).stream() doc_ref = next((doc.reference for doc in docs), None) if doc_ref is not None: existing_doc = doc_ref.get() if existing_doc.exists: existing_data = existing_doc.to_dict() if ( existing_data and existing_data.get("user_id") is not None and existing_data.get("user_id") != record.get("user_id") ): return None else: # Create new document doc_ref = collection_ref.document() doc_ref.set(record, merge=True) # Get the updated document updated_doc = doc_ref.get() if not updated_doc.exists: return None result = updated_doc.to_dict() if result is None: return None deserialized_session = deserialize_session_json_fields(result) if not deserialize: return deserialized_session if isinstance(session, AgentSession): return AgentSession.from_dict(deserialized_session) elif isinstance(session, TeamSession): return TeamSession.from_dict(deserialized_session) else: return WorkflowSession.from_dict(deserialized_session) except Exception as e: log_error(f"Exception upserting session: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info( f"FirestoreDb doesn't support efficient bulk operations, falling back to individual upserts for {len(sessions)} sessions" ) # Fall back to individual upserts results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user (optional, for filtering). Returns: bool: True if the memory was deleted, False otherwise. Raises: Exception: If there is an error deleting the memory. """ try: collection_ref = self._get_collection(table_type="memories") # If user_id is provided, verify the memory belongs to the user before deleting if user_id is not None: docs = collection_ref.where(filter=FieldFilter("memory_id", "==", memory_id)).stream() for doc in docs: data = doc.to_dict() if data.get("user_id") != user_id: log_debug(f"Memory {memory_id} does not belong to user {user_id}") return doc.reference.delete() log_debug(f"Successfully deleted user memory id: {memory_id}") return else: docs = collection_ref.where(filter=FieldFilter("memory_id", "==", memory_id)).stream() deleted_count = 0 for doc in docs: doc.reference.delete() deleted_count += 1 success = deleted_count > 0 if success: log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting user memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user (optional, for filtering). Raises: Exception: If there is an error deleting the memories. """ try: collection_ref = self._get_collection(table_type="memories") batch = self.db_client.batch() deleted_count = 0 # If user_id is provided, filter memory_ids to only those belonging to the user if user_id is not None: for memory_id in memory_ids: docs = collection_ref.where(filter=FieldFilter("memory_id", "==", memory_id)).stream() for doc in docs: data = doc.to_dict() if data.get("user_id") == user_id: batch.delete(doc.reference) deleted_count += 1 else: for memory_id in memory_ids: docs = collection_ref.where(filter=FieldFilter("memory_id", "==", memory_id)).stream() for doc in docs: batch.delete(doc.reference) deleted_count += 1 batch.commit() if deleted_count == 0: log_info(f"No memories found with ids: {memory_ids}") else: log_info(f"Successfully deleted {deleted_count} memories") except Exception as e: log_error(f"Error deleting memories: {e}") raise e def get_all_memory_topics(self, create_collection_if_not_found: Optional[bool] = True) -> List[str]: """Get all memory topics from the database. Returns: List[str]: The topics. Raises: Exception: If there is an error getting the topics. """ try: collection_ref = self._get_collection(table_type="memories") if collection_ref is None: return [] docs = collection_ref.stream() all_topics = set() for doc in docs: data = doc.to_dict() topics = data.get("topics", []) if topics: all_topics.update(topics) return [topic for topic in all_topics if topic] except Exception as e: log_error(f"Exception getting all memory topics: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[UserMemory]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user (optional, for filtering). Returns: Optional[UserMemory]: - When deserialize=True: UserMemory object - When deserialize=False: Memory dictionary Raises: Exception: If there is an error getting the memory. """ try: collection_ref = self._get_collection(table_type="memories") docs = collection_ref.where(filter=FieldFilter("memory_id", "==", memory_id)).stream() result = None for doc in docs: result = doc.to_dict() break if result is None: return None # Filter by user_id if provided if user_id and result.get("user_id") != user_id: return None if not deserialize: return result return UserMemory.from_dict(result) except Exception as e: log_error(f"Exception getting user memory: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to get the memories for. agent_id (Optional[str]): The ID of the agent to get the memories for. team_id (Optional[str]): The ID of the team to get the memories for. topics (Optional[List[str]]): The topics to filter the memories by. search_content (Optional[str]): The content to filter the memories by. limit (Optional[int]): The limit of the memories to get. page (Optional[int]): The page number to get. sort_by (Optional[str]): The field to sort the memories by. sort_order (Optional[str]): The order to sort the memories by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. create_table_if_not_found: Whether to create the index if it doesn't exist. Returns: Tuple[List[Dict[str, Any]], int]: A tuple containing the memories and the total count. Raises: Exception: If there is an error getting the memories. """ try: collection_ref = self._get_collection(table_type="memories") if collection_ref is None: return [] if deserialize else ([], 0) query = collection_ref if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) if agent_id is not None: query = query.where(filter=FieldFilter("agent_id", "==", agent_id)) if team_id is not None: query = query.where(filter=FieldFilter("team_id", "==", team_id)) if topics is not None and len(topics) > 0: query = query.where(filter=FieldFilter("topics", "array_contains_any", topics)) if search_content is not None: query = query.where(filter=FieldFilter("memory", "==", search_content)) # Apply sorting query = apply_sorting(query, sort_by, sort_order) # Get all documents docs = query.stream() all_records = [doc.to_dict() for doc in docs] total_count = len(all_records) # Apply pagination to the filtered results if limit is not None and page is not None: start_index = (page - 1) * limit end_index = start_index + limit records = all_records[start_index:end_index] elif limit is not None: records = all_records[:limit] else: records = all_records if not deserialize: return records, total_count return [UserMemory.from_dict(record) for record in records] except Exception as e: log_error(f"Exception getting user memories: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The limit of the memories to get. page (Optional[int]): The page number to get. Returns: Tuple[List[Dict[str, Any]], int]: A tuple containing the memories stats and the total count. Raises: Exception: If there is an error getting the memories stats. """ try: collection_ref = self._get_collection(table_type="memories") if user_id is not None: query = collection_ref.where(filter=FieldFilter("user_id", "==", user_id)) else: query = collection_ref.where(filter=FieldFilter("user_id", "!=", None)) docs = query.stream() user_stats = {} for doc in docs: data = doc.to_dict() current_user_id = data.get("user_id") if current_user_id: if current_user_id not in user_stats: user_stats[current_user_id] = { "user_id": current_user_id, "total_memories": 0, "last_memory_updated_at": 0, } user_stats[current_user_id]["total_memories"] += 1 updated_at = data.get("updated_at", 0) if updated_at > user_stats[current_user_id]["last_memory_updated_at"]: user_stats[current_user_id]["last_memory_updated_at"] = updated_at # Convert to list and sort formatted_results = list(user_stats.values()) formatted_results.sort(key=lambda x: x["last_memory_updated_at"], reverse=True) total_count = len(formatted_results) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit formatted_results = formatted_results[start_idx : start_idx + limit] return formatted_results, total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: Memory dictionary Raises: Exception: If there is an error upserting the memory. """ try: collection_ref = self._get_collection(table_type="memories", create_collection_if_not_found=True) if collection_ref is None: return None if memory.memory_id is None: memory.memory_id = str(uuid4()) update_doc = memory.to_dict() update_doc["updated_at"] = int(time.time()) # Find existing document or create new one docs = collection_ref.where("memory_id", "==", memory.memory_id).stream() doc_ref = next((doc.reference for doc in docs), None) if doc_ref is None: doc_ref = collection_ref.document() doc_ref.set(update_doc, merge=True) if not deserialize: return update_doc return UserMemory.from_dict(update_doc) except Exception as e: log_error(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info( f"FirestoreDb doesn't support efficient bulk operations, falling back to individual upserts for {len(memories)} memories" ) # Fall back to individual upserts results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: collection_ref = self._get_collection(table_type="memories") # Get all documents in the collection docs = collection_ref.stream() # Delete all documents in batches batch = self.db_client.batch() batch_count = 0 for doc in docs: batch.delete(doc.reference) batch_count += 1 # Firestore batch has a limit of 500 operations if batch_count >= 500: batch.commit() batch = self.db_client.batch() batch_count = 0 # Commit remaining operations if batch_count > 0: batch.commit() except Exception as e: log_error(f"Exception deleting all memories: {e}") raise e # -- Cultural Knowledge methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: collection_ref = self._get_collection(table_type="culture") # Get all documents in the collection docs = collection_ref.stream() # Delete all documents in batches batch = self.db_client.batch() batch_count = 0 for doc in docs: batch.delete(doc.reference) batch_count += 1 # Firestore batch has a limit of 500 operations if batch_count >= 500: batch.commit() batch = self.db_client.batch() batch_count = 0 # Commit remaining operations if batch_count > 0: batch.commit() except Exception as e: log_error(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: collection_ref = self._get_collection(table_type="culture") docs = collection_ref.where(filter=FieldFilter("id", "==", id)).stream() for doc in docs: doc.reference.delete() log_debug(f"Deleted cultural knowledge with ID: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to retrieve. deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise. Raises: Exception: If an error occurs during retrieval. """ try: collection_ref = self._get_collection(table_type="culture") docs = collection_ref.where(filter=FieldFilter("id", "==", id)).limit(1).stream() for doc in docs: result = doc.to_dict() if not deserialize: return result return deserialize_cultural_knowledge_from_db(result) return None except Exception as e: log_error(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, agent_id: Optional[str] = None, team_id: Optional[str] = None, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge with filtering and pagination. Args: agent_id (Optional[str]): Filter by agent ID. team_id (Optional[str]): Filter by team ID. name (Optional[str]): Filter by name (case-insensitive partial match). limit (Optional[int]): Maximum number of results to return. page (Optional[int]): Page number for pagination. sort_by (Optional[str]): Field to sort by. sort_order (Optional[str]): Sort order ('asc' or 'desc'). deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: Tuple with list of dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: collection_ref = self._get_collection(table_type="culture") # Build query with filters query = collection_ref if agent_id is not None: query = query.where(filter=FieldFilter("agent_id", "==", agent_id)) if team_id is not None: query = query.where(filter=FieldFilter("team_id", "==", team_id)) # Get all matching documents docs = query.stream() results = [doc.to_dict() for doc in docs] # Apply name filter (Firestore doesn't support regex in queries) if name is not None: results = [r for r in results if name.lower() in r.get("name", "").lower()] total_count = len(results) # Apply sorting and pagination to in-memory results sorted_results = apply_sorting_to_records(records=results, sort_by=sort_by, sort_order=sort_order) paginated_results = apply_pagination_to_records(records=sorted_results, limit=limit, page=page) if not deserialize: return paginated_results, total_count return [deserialize_cultural_knowledge_from_db(item) for item in paginated_results] except Exception as e: log_error(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert cultural knowledge in Firestore. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge. Raises: Exception: If an error occurs during upsert. """ try: collection_ref = self._get_collection(table_type="culture", create_collection_if_not_found=True) # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the update document with serialized content update_doc = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } # Find and update or create new document docs = collection_ref.where(filter=FieldFilter("id", "==", cultural_knowledge.id)).limit(1).stream() doc_found = False for doc in docs: doc.reference.set(update_doc) doc_found = True break if not doc_found: collection_ref.add(update_doc) if not deserialize: return update_doc return deserialize_cultural_knowledge_from_db(update_doc) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions of all types for metrics calculation.""" try: collection_ref = self._get_collection(table_type="sessions") query = collection_ref if start_timestamp is not None: query = query.where(filter=FieldFilter("created_at", ">=", start_timestamp)) if end_timestamp is not None: query = query.where(filter=FieldFilter("created_at", "<=", end_timestamp)) docs = query.stream() results = [] for doc in docs: data = doc.to_dict() # Only include required fields for metrics result = { "user_id": data.get("user_id"), "session_data": data.get("session_data"), "runs": data.get("runs"), "created_at": data.get("created_at"), "session_type": data.get("session_type"), } results.append(result) return results except Exception as e: log_error(f"Exception getting all sessions for metrics calculation: {e}") raise e def _get_metrics_calculation_starting_date(self, collection_ref) -> Optional[date]: """Get the first date for which metrics calculation is needed.""" try: query = collection_ref.order_by("date", direction="DESCENDING").limit(1) docs = query.stream() for doc in docs: data = doc.to_dict() result_date = datetime.strptime(data["date"], "%Y-%m-%d").date() if data.get("completed"): return result_date + timedelta(days=1) else: return result_date # No metrics records. Return the date of the first recorded session. first_session_result = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) first_session_date = None if isinstance(first_session_result, list) and len(first_session_result) > 0: first_session_date = first_session_result[0].created_at # type: ignore elif isinstance(first_session_result, tuple) and len(first_session_result[0]) > 0: first_session_date = first_session_result[0][0].get("created_at") if first_session_date is None: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() except Exception as e: log_error(f"Exception getting metrics calculation starting date: {e}") raise e def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics.""" try: collection_ref = self._get_collection(table_type="metrics", create_collection_if_not_found=True) starting_date = self._get_metrics_calculation_starting_date(collection_ref) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: results = bulk_upsert_metrics(collection_ref, metrics_records) log_debug("Updated metrics calculations") return results except Exception as e: log_error(f"Exception calculating metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range.""" try: collection_ref = self._get_collection(table_type="metrics") if collection_ref is None: return [], None query = collection_ref if starting_date: query = query.where(filter=FieldFilter("date", ">=", starting_date.isoformat())) if ending_date: query = query.where(filter=FieldFilter("date", "<=", ending_date.isoformat())) docs = query.stream() records = [] latest_updated_at = 0 for doc in docs: data = doc.to_dict() records.append(data) updated_at = data.get("updated_at", 0) if updated_at > latest_updated_at: latest_updated_at = updated_at if not records: return [], None return records, latest_updated_at except Exception as e: log_error(f"Exception getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ try: collection_ref = self._get_collection(table_type="knowledge") docs = collection_ref.where(filter=FieldFilter("id", "==", id)).stream() for doc in docs: doc.reference.delete() except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: collection_ref = self._get_collection(table_type="knowledge") docs = collection_ref.where(filter=FieldFilter("id", "==", id)).stream() for doc in docs: data = doc.to_dict() return KnowledgeRow.model_validate(data) return None except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ try: collection_ref = self._get_collection(table_type="knowledge") if collection_ref is None: return [], 0 query = collection_ref # Apply linked_to filter if provided if linked_to is not None: query = query.where("linked_to", "==", linked_to) # Apply sorting query = apply_sorting(query, sort_by, sort_order) # Apply pagination query = apply_pagination(query, limit, page) docs = query.stream() records = [] for doc in docs: records.append(doc.to_dict()) knowledge_rows = [KnowledgeRow.model_validate(record) for record in records] total_count = len(knowledge_rows) # Simplified count return knowledge_rows, total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ try: collection_ref = self._get_collection(table_type="knowledge", create_collection_if_not_found=True) if collection_ref is None: return None update_doc = knowledge_row.model_dump() # Find existing document or create new one docs = collection_ref.where(filter=FieldFilter("id", "==", knowledge_row.id)).stream() doc_ref = next((doc.reference for doc in docs), None) if doc_ref is None: doc_ref = collection_ref.document() doc_ref.set(update_doc, merge=True) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge content: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database.""" try: collection_ref = self._get_collection(table_type="evals", create_collection_if_not_found=True) current_time = int(time.time()) eval_dict = eval_run.model_dump() eval_dict["created_at"] = current_time eval_dict["updated_at"] = current_time doc_ref = collection_ref.document() doc_ref.set(eval_dict) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database.""" try: collection_ref = self._get_collection(table_type="evals") docs = collection_ref.where(filter=FieldFilter("run_id", "==", eval_run_id)).stream() deleted_count = 0 for doc in docs: doc.reference.delete() deleted_count += 1 if deleted_count == 0: log_info(f"No eval run found with ID: {eval_run_id}") else: log_info(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database. Args: eval_run_ids (List[str]): The IDs of the eval runs to delete. Raises: Exception: If there is an error deleting the eval runs. """ try: collection_ref = self._get_collection(table_type="evals") batch = self.db_client.batch() deleted_count = 0 for eval_run_id in eval_run_ids: docs = collection_ref.where(filter=FieldFilter("run_id", "==", eval_run_id)).stream() for doc in docs: batch.delete(doc.reference) deleted_count += 1 batch.commit() if deleted_count == 0: log_info(f"No eval runs found with IDs: {eval_run_ids}") else: log_info(f"Deleted {deleted_count} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If there is an error getting the eval run. """ try: collection_ref = self._get_collection(table_type="evals") if not collection_ref: return None docs = collection_ref.where(filter=FieldFilter("run_id", "==", eval_run_id)).stream() eval_run_raw = None for doc in docs: eval_run_raw = doc.to_dict() break if not eval_run_raw: return None if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number to return. sort_by (Optional[str]): The field to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type of eval to filter by. filter_type (Optional[EvalFilterType]): The type of filter to apply. deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of eval run dictionaries and the total count Raises: Exception: If there is an error getting the eval runs. """ try: collection_ref = self._get_collection(table_type="evals") if collection_ref is None: return [] if deserialize else ([], 0) query = collection_ref if agent_id is not None: query = query.where(filter=FieldFilter("agent_id", "==", agent_id)) if team_id is not None: query = query.where(filter=FieldFilter("team_id", "==", team_id)) if workflow_id is not None: query = query.where(filter=FieldFilter("workflow_id", "==", workflow_id)) if model_id is not None: query = query.where(filter=FieldFilter("model_id", "==", model_id)) if eval_type is not None and len(eval_type) > 0: eval_values = [et.value for et in eval_type] query = query.where(filter=FieldFilter("eval_type", "in", eval_values)) if filter_type is not None: if filter_type == EvalFilterType.AGENT: query = query.where(filter=FieldFilter("agent_id", "!=", None)) elif filter_type == EvalFilterType.TEAM: query = query.where(filter=FieldFilter("team_id", "!=", None)) elif filter_type == EvalFilterType.WORKFLOW: query = query.where(filter=FieldFilter("workflow_id", "!=", None)) # Apply default sorting by created_at desc if no sort parameters provided if sort_by is None: from google.cloud.firestore import Query query = query.order_by("created_at", direction=Query.DESCENDING) else: query = apply_sorting(query, sort_by, sort_order) # Get all documents for counting before pagination all_docs = query.stream() all_records = [doc.to_dict() for doc in all_docs] if not all_records: return [] if deserialize else ([], 0) # Get total count before pagination total_count = len(all_records) # Apply pagination to the results if limit is not None and page is not None: start_index = (page - 1) * limit end_index = start_index + limit records = all_records[start_index:end_index] elif limit is not None: records = all_records[:limit] else: records = all_records if not deserialize: return records, total_count return [EvalRunRecord.model_validate(row) for row in records] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Update the name of an eval run in the database. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If there is an error updating the eval run. """ try: collection_ref = self._get_collection(table_type="evals") if not collection_ref: return None docs = collection_ref.where(filter=FieldFilter("run_id", "==", eval_run_id)).stream() doc_ref = next((doc.reference for doc in docs), None) if doc_ref is None: return None doc_ref.update({"name": name, "updated_at": int(time.time())}) updated_doc = doc_ref.get() if not updated_doc.exists: return None result = updated_doc.to_dict() log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not result or not deserialize: return result return EvalRunRecord.model_validate(result) except Exception as e: log_error(f"Error updating eval run name {eval_run_id}: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ try: collection_ref = self._get_collection(table_type="traces", create_collection_if_not_found=True) if collection_ref is None: return # Check if trace already exists docs = collection_ref.where(filter=FieldFilter("trace_id", "==", trace.trace_id)).limit(1).stream() existing_doc = None existing_data = None for doc in docs: existing_doc = doc existing_data = doc.to_dict() break if existing_data and existing_doc is not None: # Update existing trace def get_component_level(workflow_id, team_id, agent_id, name): is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 elif workflow_id: return 3 elif team_id: return 2 elif agent_id: return 1 else: return 0 existing_level = get_component_level( existing_data.get("workflow_id"), existing_data.get("team_id"), existing_data.get("agent_id"), existing_data.get("name", ""), ) new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) should_update_name = new_level > existing_level # Parse existing start_time to calculate correct duration existing_start_time_str = existing_data.get("start_time") if isinstance(existing_start_time_str, str): existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00")) else: existing_start_time = trace.start_time recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000) update_values: Dict[str, Any] = { "end_time": trace.end_time.isoformat(), "duration_ms": recalculated_duration_ms, "status": trace.status, } if should_update_name: update_values["name"] = trace.name # Update context fields only if new value is not None if trace.run_id is not None: update_values["run_id"] = trace.run_id if trace.session_id is not None: update_values["session_id"] = trace.session_id if trace.user_id is not None: update_values["user_id"] = trace.user_id if trace.agent_id is not None: update_values["agent_id"] = trace.agent_id if trace.team_id is not None: update_values["team_id"] = trace.team_id if trace.workflow_id is not None: update_values["workflow_id"] = trace.workflow_id existing_doc.reference.update(update_values) else: # Create new trace with initialized counters trace_dict = trace.to_dict() trace_dict["total_spans"] = 0 trace_dict["error_count"] = 0 collection_ref.add(trace_dict) except Exception as e: log_error(f"Error creating trace: {e}") def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace collection_ref = self._get_collection(table_type="traces") if collection_ref is None: return None if trace_id: docs = collection_ref.where(filter=FieldFilter("trace_id", "==", trace_id)).limit(1).stream() elif run_id: from google.cloud.firestore import Query docs = ( collection_ref.where(filter=FieldFilter("run_id", "==", run_id)) .order_by("start_time", direction=Query.DESCENDING) .limit(1) .stream() ) else: log_debug("get_trace called without any filter parameters") return None for doc in docs: trace_data = doc.to_dict() # Use stored values (default to 0 if not present) trace_data.setdefault("total_spans", 0) trace_data.setdefault("error_count", 0) return Trace.from_dict(trace_data) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace collection_ref = self._get_collection(table_type="traces") if collection_ref is None: return [], 0 query = collection_ref # Apply filters if run_id: query = query.where(filter=FieldFilter("run_id", "==", run_id)) if session_id: query = query.where(filter=FieldFilter("session_id", "==", session_id)) if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) if agent_id: query = query.where(filter=FieldFilter("agent_id", "==", agent_id)) if team_id: query = query.where(filter=FieldFilter("team_id", "==", team_id)) if workflow_id: query = query.where(filter=FieldFilter("workflow_id", "==", workflow_id)) if status: query = query.where(filter=FieldFilter("status", "==", status)) if start_time: query = query.where(filter=FieldFilter("start_time", ">=", start_time.isoformat())) if end_time: query = query.where(filter=FieldFilter("end_time", "<=", end_time.isoformat())) # Get all matching documents docs = query.stream() all_records = [doc.to_dict() for doc in docs] # Sort by start_time descending all_records.sort(key=lambda x: x.get("start_time", ""), reverse=True) # Get total count total_count = len(all_records) # Apply pagination if limit and page: offset = (page - 1) * limit paginated_records = all_records[offset : offset + limit] elif limit: paginated_records = all_records[:limit] else: paginated_records = all_records # Convert to Trace objects with stored span counts traces = [] for trace_data in paginated_records: trace_data.setdefault("total_spans", 0) trace_data.setdefault("error_count", 0) traces.append(Trace.from_dict(trace_data)) return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, workflow_id, total_traces, first_trace_at, last_trace_at. """ try: collection_ref = self._get_collection(table_type="traces") if collection_ref is None: return [], 0 query = collection_ref # Apply filters if user_id is not None: query = query.where(filter=FieldFilter("user_id", "==", user_id)) if agent_id: query = query.where(filter=FieldFilter("agent_id", "==", agent_id)) if team_id: query = query.where(filter=FieldFilter("team_id", "==", team_id)) if workflow_id: query = query.where(filter=FieldFilter("workflow_id", "==", workflow_id)) if start_time: query = query.where(filter=FieldFilter("created_at", ">=", start_time.isoformat())) if end_time: query = query.where(filter=FieldFilter("created_at", "<=", end_time.isoformat())) # Get all matching documents docs = query.stream() # Aggregate by session_id session_stats: Dict[str, Dict[str, Any]] = {} for doc in docs: trace_data = doc.to_dict() session_id = trace_data.get("session_id") if not session_id: continue if session_id not in session_stats: session_stats[session_id] = { "session_id": session_id, "user_id": trace_data.get("user_id"), "agent_id": trace_data.get("agent_id"), "team_id": trace_data.get("team_id"), "workflow_id": trace_data.get("workflow_id"), "total_traces": 0, "first_trace_at": trace_data.get("created_at"), "last_trace_at": trace_data.get("created_at"), } session_stats[session_id]["total_traces"] += 1 created_at = trace_data.get("created_at") if ( created_at and session_stats[session_id]["first_trace_at"] and session_stats[session_id]["last_trace_at"] ): if created_at < session_stats[session_id]["first_trace_at"]: session_stats[session_id]["first_trace_at"] = created_at if created_at > session_stats[session_id]["last_trace_at"]: session_stats[session_id]["last_trace_at"] = created_at # Convert to list and sort by last_trace_at descending stats_list = list(session_stats.values()) stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True) # Convert datetime strings to datetime objects for stat in stats_list: first_trace_at = stat["first_trace_at"] last_trace_at = stat["last_trace_at"] if isinstance(first_trace_at, str): stat["first_trace_at"] = datetime.fromisoformat(first_trace_at.replace("Z", "+00:00")) if isinstance(last_trace_at, str): stat["last_trace_at"] = datetime.fromisoformat(last_trace_at.replace("Z", "+00:00")) # Get total count total_count = len(stats_list) # Apply pagination if limit and page: offset = (page - 1) * limit paginated_stats = stats_list[offset : offset + limit] elif limit: paginated_stats = stats_list[:limit] else: paginated_stats = stats_list return paginated_stats, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: collection_ref = self._get_collection(table_type="spans", create_collection_if_not_found=True) if collection_ref is None: return span_dict = span.to_dict() # Serialize attributes as JSON string if "attributes" in span_dict and isinstance(span_dict["attributes"], dict): span_dict["attributes"] = json.dumps(span_dict["attributes"]) collection_ref.add(span_dict) # Increment total_spans and error_count on trace traces_collection = self._get_collection(table_type="traces") if traces_collection: try: docs = ( traces_collection.where(filter=FieldFilter("trace_id", "==", span.trace_id)).limit(1).stream() ) for doc in docs: trace_data = doc.to_dict() current_total = trace_data.get("total_spans", 0) current_errors = trace_data.get("error_count", 0) update_values = {"total_spans": current_total + 1} if span.status_code == "ERROR": update_values["error_count"] = current_errors + 1 doc.reference.update(update_values) break except Exception as update_error: log_debug(f"Could not update trace span counts: {update_error}") except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: collection_ref = self._get_collection(table_type="spans", create_collection_if_not_found=True) if collection_ref is None: return # Firestore batch has a limit of 500 operations batch = self.db_client.batch() batch_count = 0 for span in spans: span_dict = span.to_dict() # Serialize attributes as JSON string if "attributes" in span_dict and isinstance(span_dict["attributes"], dict): span_dict["attributes"] = json.dumps(span_dict["attributes"]) doc_ref = collection_ref.document() batch.set(doc_ref, span_dict) batch_count += 1 # Commit batch if reaching limit if batch_count >= 500: batch.commit() batch = self.db_client.batch() batch_count = 0 # Commit remaining operations if batch_count > 0: batch.commit() # Update trace with total_spans and error_count trace_id = spans[0].trace_id spans_count = len(spans) error_count = sum(1 for s in spans if s.status_code == "ERROR") traces_collection = self._get_collection(table_type="traces") if traces_collection: try: docs = traces_collection.where(filter=FieldFilter("trace_id", "==", trace_id)).limit(1).stream() for doc in docs: trace_data = doc.to_dict() current_total = trace_data.get("total_spans", 0) current_errors = trace_data.get("error_count", 0) doc.reference.update( { "total_spans": current_total + spans_count, "error_count": current_errors + error_count, } ) break except Exception as update_error: log_debug(f"Could not update trace span counts: {update_error}") except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span collection_ref = self._get_collection(table_type="spans") if collection_ref is None: return None docs = collection_ref.where(filter=FieldFilter("span_id", "==", span_id)).limit(1).stream() for doc in docs: span_data = doc.to_dict() # Deserialize attributes from JSON string if "attributes" in span_data and isinstance(span_data["attributes"], str): span_data["attributes"] = json.loads(span_data["attributes"]) return Span.from_dict(span_data) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span collection_ref = self._get_collection(table_type="spans") if collection_ref is None: return [] query = collection_ref if trace_id: query = query.where(filter=FieldFilter("trace_id", "==", trace_id)) if parent_span_id: query = query.where(filter=FieldFilter("parent_span_id", "==", parent_span_id)) if limit: query = query.limit(limit) docs = query.stream() spans = [] for doc in docs: span_data = doc.to_dict() # Deserialize attributes from JSON string if "attributes" in span_data and isinstance(span_data["attributes"], str): span_data["attributes"] = json.loads(span_data["attributes"]) spans.append(Span.from_dict(span_data)) return spans except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for FirestoreDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for FirestoreDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for FirestoreDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for FirestoreDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/firestore/firestore.py", "license": "Apache License 2.0", "lines": 2017, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/firestore/schemas.py
"""Firestore collection schemas and related utilities""" from typing import Any, Dict, List SESSION_COLLECTION_SCHEMA = [ {"key": "session_id"}, {"key": "user_id"}, {"key": "session_type"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "created_at"}, {"key": "updated_at"}, {"key": "session_data.session_name"}, # Composite indexes for get_sessions queries with sorting # These match the actual query patterns: filters + created_at ordering {"key": [("session_type", "ASCENDING"), ("created_at", "DESCENDING")], "collection_group": False}, { "key": [("session_type", "ASCENDING"), ("agent_id", "ASCENDING"), ("created_at", "DESCENDING")], "collection_group": False, }, { "key": [("session_type", "ASCENDING"), ("team_id", "ASCENDING"), ("created_at", "DESCENDING")], "collection_group": False, }, { "key": [("session_type", "ASCENDING"), ("workflow_id", "ASCENDING"), ("created_at", "DESCENDING")], "collection_group": False, }, # For user-specific queries with sorting { "key": [("user_id", "ASCENDING"), ("session_type", "ASCENDING"), ("created_at", "DESCENDING")], "collection_group": False, }, { "key": [ ("user_id", "ASCENDING"), ("session_type", "ASCENDING"), ("agent_id", "ASCENDING"), ("created_at", "DESCENDING"), ], "collection_group": False, }, { "key": [ ("user_id", "ASCENDING"), ("session_type", "ASCENDING"), ("team_id", "ASCENDING"), ("created_at", "DESCENDING"), ], "collection_group": False, }, { "key": [ ("user_id", "ASCENDING"), ("session_type", "ASCENDING"), ("workflow_id", "ASCENDING"), ("created_at", "DESCENDING"), ], "collection_group": False, }, ] USER_MEMORY_COLLECTION_SCHEMA = [ {"key": "memory_id", "unique": True}, {"key": "user_id"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "topics"}, {"key": "created_at"}, {"key": "updated_at"}, # Composite indexes for memory queries {"key": [("user_id", "ASCENDING"), ("agent_id", "ASCENDING")], "collection_group": False}, {"key": [("user_id", "ASCENDING"), ("team_id", "ASCENDING")], "collection_group": False}, {"key": [("user_id", "ASCENDING"), ("workflow_id", "ASCENDING")], "collection_group": False}, ] EVAL_COLLECTION_SCHEMA = [ {"key": "run_id", "unique": True}, {"key": "eval_type"}, {"key": "eval_input"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "model_id"}, {"key": "created_at"}, {"key": "updated_at"}, ] KNOWLEDGE_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "name"}, {"key": "description"}, {"key": "type"}, {"key": "status"}, {"key": "status_message"}, {"key": "metadata"}, {"key": "size"}, {"key": "linked_to"}, {"key": "access_count"}, {"key": "created_at"}, {"key": "updated_at"}, {"key": "external_id"}, ] METRICS_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "date"}, {"key": "aggregation_period"}, {"key": "created_at"}, {"key": "updated_at"}, # Composite index for metrics uniqueness (same as MongoDB) {"key": [("date", "ASCENDING"), ("aggregation_period", "ASCENDING")], "collection_group": False, "unique": True}, ] CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "name"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "created_at"}, {"key": "updated_at"}, ] TRACE_COLLECTION_SCHEMA = [ {"key": "trace_id", "unique": True}, {"key": "name"}, {"key": "status"}, {"key": "run_id"}, {"key": "session_id"}, {"key": "user_id"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "start_time"}, {"key": "end_time"}, {"key": "created_at"}, # Composite indexes for common query patterns {"key": [("session_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("user_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("agent_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("team_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("workflow_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("run_id", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, {"key": [("status", "ASCENDING"), ("start_time", "DESCENDING")], "collection_group": False}, ] SPAN_COLLECTION_SCHEMA = [ {"key": "span_id", "unique": True}, {"key": "trace_id"}, {"key": "parent_span_id"}, {"key": "name"}, {"key": "span_kind"}, {"key": "status_code"}, {"key": "start_time"}, {"key": "end_time"}, {"key": "created_at"}, # Composite indexes for common query patterns {"key": [("trace_id", "ASCENDING"), ("start_time", "ASCENDING")], "collection_group": False}, {"key": [("parent_span_id", "ASCENDING"), ("start_time", "ASCENDING")], "collection_group": False}, ] def get_collection_indexes(collection_type: str) -> List[Dict[str, Any]]: """Get the index definitions for a specific collection type.""" index_definitions = { "sessions": SESSION_COLLECTION_SCHEMA, "memories": USER_MEMORY_COLLECTION_SCHEMA, "metrics": METRICS_COLLECTION_SCHEMA, "evals": EVAL_COLLECTION_SCHEMA, "knowledge": KNOWLEDGE_COLLECTION_SCHEMA, "culture": CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA, "traces": TRACE_COLLECTION_SCHEMA, "spans": SPAN_COLLECTION_SCHEMA, } indexes = index_definitions.get(collection_type) if not indexes: raise ValueError(f"Unknown collection type: {collection_type}") return indexes # type: ignore
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/firestore/schemas.py", "license": "Apache License 2.0", "lines": 168, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/firestore/utils.py
"""Utility functions for the Firestore database class.""" import json import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.firestore.schemas import get_collection_indexes from agno.db.schemas.culture import CulturalKnowledge from agno.db.utils import get_sort_value from agno.utils.log import log_debug, log_error, log_info, log_warning try: from google.cloud.firestore import Client # type: ignore[import-untyped] from google.cloud.firestore_admin_v1 import FirestoreAdminClient, Index # type: ignore[import-untyped] except ImportError: raise ImportError( "`google-cloud-firestore` not installed. Please install it using `pip install google-cloud-firestore`" ) # -- DB util methods -- def create_collection_indexes(client: Client, collection_name: str, collection_type: str) -> None: """Create all required indexes for a collection including composite indexes. This function automatically creates both single-field and composite indexes. """ try: indexes = get_collection_indexes(collection_type) composite_indexes = [] # Get all composite indexes for idx in indexes: if isinstance(idx["key"], list): composite_indexes.append(idx) # Create composite indexes programmatically if composite_indexes: _create_composite_indexes(client, collection_name, composite_indexes) log_debug(f"Collection '{collection_name}' initialized") except Exception as e: log_warning(f"Error processing indexes for {collection_type} collection: {e}") def _create_composite_indexes(client: Client, collection_name: str, composite_indexes: List[Dict[str, Any]]) -> None: """Create composite indexes using Firestore Admin API.""" try: project_id = client.project if not project_id: log_warning("Cannot create composite indexes: project_id not available from client") return admin_client = FirestoreAdminClient() created_count = 0 for idx_spec in composite_indexes: try: # Build index fields fields = [] for field_name, direction in idx_spec["key"]: field_direction = ( Index.IndexField.Order.ASCENDING if direction == "ASCENDING" else Index.IndexField.Order.DESCENDING ) fields.append(Index.IndexField(field_path=field_name, order=field_direction)) # Create index definition index = Index( query_scope=Index.QueryScope.COLLECTION if not idx_spec.get("collection_group", True) else Index.QueryScope.COLLECTION_GROUP, fields=fields, ) # Note: Firestore doesn't support unique constraints on composite indexes if idx_spec.get("unique", False): log_debug( f"Unique constraint on composite index ignored for {collection_name} - not supported by Firestore" ) # Create the index parent_path = f"projects/{project_id}/databases/(default)/collectionGroups/{collection_name}" admin_client.create_index(parent=parent_path, index=index) created_count += 1 except Exception as e: if "already exists" in str(e).lower(): continue else: log_error(f"Error creating composite index: {e}") except Exception as e: log_warning(f"Error initializing Firestore Admin client for composite indexes: {e}") log_info("Fallback: You can create composite indexes manually via Firebase Console or gcloud CLI") def apply_sorting(query, sort_by: Optional[str] = None, sort_order: Optional[str] = None): """Apply sorting to Firestore query.""" if sort_by is None: return query from google.cloud.firestore import Query if sort_order == "asc": return query.order_by(sort_by, direction=Query.ASCENDING) else: return query.order_by(sort_by, direction=Query.DESCENDING) def apply_pagination(query, limit: Optional[int] = None, page: Optional[int] = None): """Apply pagination to Firestore query.""" if limit is not None: query = query.limit(limit) if page is not None and page > 1: # Note: Firestore pagination typically uses cursor-based pagination # For offset-based pagination, we'd need to skip documents offset = (page - 1) * limit query = query.offset(offset) return query def apply_sorting_to_records( records: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to in-memory records (for cases where Firestore query sorting isn't possible). Args: records: The list of dictionaries to sort sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if sort_by is None or not records: return records try: is_descending = sort_order == "desc" # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( records, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records except Exception as e: log_warning(f"Error sorting Firestore records: {e}") return records def apply_pagination_to_records( records: List[Dict[str, Any]], limit: Optional[int] = None, page: Optional[int] = None ) -> List[Dict[str, Any]]: """Apply pagination to in-memory records (for cases where Firestore query pagination isn't possible).""" if limit is None: return records if page is not None and page > 0: start_idx = (page - 1) * limit end_idx = start_idx + limit return records[start_idx:end_idx] else: return records[:limit] # -- Metrics util methods -- def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date.""" metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) runs = session.get("runs", []) or [] if runs: if isinstance(runs, str): runs = json.loads(runs) metrics[runs_count_key] += len(runs) for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_data = session.get("session_data", {}) if isinstance(session_data, str): session_data = json.loads(session_data) session_metrics = session_data.get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types.""" if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for.""" today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] def bulk_upsert_metrics(collection_ref, metrics_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Bulk upsert metrics into the database. Args: collection_ref: The Firestore collection reference to upsert the metrics into. metrics_records (List[Dict[str, Any]]): The list of metrics records to upsert. Returns: The list of upserted metrics records. """ if not metrics_records: return [] results = [] batch = collection_ref._client.batch() for i, record in enumerate(metrics_records): record["date"] = record["date"].isoformat() if isinstance(record["date"], date) else record["date"] try: # Create a unique document ID based on date and aggregation period doc_id = f"{record['date']}_{record['aggregation_period']}" doc_ref = collection_ref.document(doc_id) batch.set(doc_ref, record, merge=True) results.append(record) # Firestore batch limit is 500 operations if (i + 1) % 500 == 0: batch.commit() batch = collection_ref._client.batch() except Exception as e: log_error(f"Error preparing metrics record for batch: {e}") continue # Commit remaining operations if len(metrics_records) % 500 != 0: try: batch.commit() except Exception as e: log_error(f"Error committing metrics batch: {e}") return results # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content field. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/firestore/utils.py", "license": "Apache License 2.0", "lines": 309, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/gcs_json/gcs_json_db.py
import json import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.gcs_json.utils import ( apply_sorting, calculate_date_metrics, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id try: from google.cloud import storage as gcs # type: ignore except ImportError: raise ImportError("`google-cloud-storage` not installed. Please install it with `pip install google-cloud-storage`") class GcsJsonDb(BaseDb): def __init__( self, bucket_name: str, prefix: Optional[str] = None, session_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, culture_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, project: Optional[str] = None, credentials: Optional[Any] = None, id: Optional[str] = None, ): """ Interface for interacting with JSON files stored in Google Cloud Storage as database. Args: bucket_name (str): Name of the GCS bucket where JSON files will be stored. prefix (Optional[str]): Path prefix for organizing files in the bucket. Defaults to "agno/". session_table (Optional[str]): Name of the JSON file to store sessions (without .json extension). memory_table (Optional[str]): Name of the JSON file to store user memories. metrics_table (Optional[str]): Name of the JSON file to store metrics. eval_table (Optional[str]): Name of the JSON file to store evaluation runs. knowledge_table (Optional[str]): Name of the JSON file to store knowledge content. culture_table (Optional[str]): Name of the JSON file to store cultural knowledge. traces_table (Optional[str]): Name of the JSON file to store traces. spans_table (Optional[str]): Name of the JSON file to store spans. project (Optional[str]): GCP project ID. If None, uses default project. location (Optional[str]): GCS bucket location. If None, uses default location. credentials (Optional[Any]): GCP credentials. If None, uses default credentials. id (Optional[str]): ID of the database. """ if id is None: prefix_suffix = prefix or "agno/" seed = f"{bucket_name}_{project}#{prefix_suffix}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, culture_table=culture_table, traces_table=traces_table, spans_table=spans_table, ) self.bucket_name = bucket_name self.prefix = prefix or "agno/" if self.prefix and not self.prefix.endswith("/"): self.prefix += "/" # Initialize GCS client and bucket self.client = gcs.Client(project=project, credentials=credentials) self.bucket = self.client.bucket(self.bucket_name) def table_exists(self, table_name: str) -> bool: """JSON implementation, always returns True.""" return True def _get_blob_name(self, filename: str) -> str: """Get the full blob name including prefix for a given filename.""" return f"{self.prefix}{filename}.json" def _read_json_file(self, filename: str, create_table_if_not_found: Optional[bool] = False) -> List[Dict[str, Any]]: """Read data from a JSON file in GCS, creating it if it doesn't exist. Args: filename (str): The name of the JSON file to read. Returns: List[Dict[str, Any]]: The data from the JSON file. Raises: json.JSONDecodeError: If the JSON file is not valid. """ blob_name = self._get_blob_name(filename) blob = self.bucket.blob(blob_name) try: data_str = blob.download_as_bytes().decode("utf-8") return json.loads(data_str) except Exception as e: # Check if it's a 404 (file not found) error if "404" in str(e) or "Not Found" in str(e): if create_table_if_not_found: log_debug(f"Creating new GCS JSON file: {blob_name}") blob.upload_from_string("[]", content_type="application/json") return [] else: log_error(f"Error reading the {blob_name} JSON file from GCS: {e}") raise json.JSONDecodeError(f"Error reading {blob_name}", "", 0) def _write_json_file(self, filename: str, data: List[Dict[str, Any]]) -> None: """Write data to a JSON file in GCS. Args: filename (str): The name of the JSON file to write. data (List[Dict[str, Any]]): The data to write to the JSON file. Raises: Exception: If an error occurs while writing to the JSON file. """ blob_name = self._get_blob_name(filename) blob = self.bucket.blob(blob_name) try: json_data = json.dumps(data, indent=2, default=str) blob.upload_from_string(json_data, content_type="application/json") except Exception as e: log_error(f"Error writing to the {blob_name} JSON file in GCS: {e}") return def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from the GCS JSON file. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: sessions = self._read_json_file(self.session_table_name) original_count = len(sessions) sessions = [ s for s in sessions if not (s.get("session_id") == session_id and (user_id is None or s.get("user_id") == user_id)) ] if len(sessions) < original_count: self._write_json_file(self.session_table_name, sessions) log_debug(f"Successfully deleted session with session_id: {session_id}") return True else: log_debug(f"No session found to delete with session_id: {session_id}") return False except Exception as e: log_warning(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from the GCS JSON file. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: sessions = self._read_json_file(self.session_table_name) sessions = [ s for s in sessions if not (s.get("session_id") in session_ids and (user_id is None or s.get("user_id") == user_id)) ] self._write_json_file(self.session_table_name, sessions) log_debug(f"Successfully deleted sessions with ids: {session_ids}") except Exception as e: log_warning(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[AgentSession, TeamSession, WorkflowSession, Dict[str, Any]]]: """Read a session from the GCS JSON file. Args: session_id (str): The ID of the session to read. session_type (SessionType): The type of the session to read. user_id (Optional[str]): The ID of the user to read the session for. deserialize (Optional[bool]): Whether to deserialize the session. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs while reading the session. """ try: sessions = self._read_json_file(self.session_table_name) for session_data in sessions: if session_data.get("session_id") == session_id: if user_id is not None and session_data.get("user_id") != user_id: continue if not deserialize: return session_data if session_type == SessionType.AGENT: return AgentSession.from_dict(session_data) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_data) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session_data) else: raise ValueError(f"Invalid session type: {session_type}") return None except Exception as e: log_warning(f"Exception reading from session file: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions from the GCS JSON file with filtering and pagination. Args: session_type (Optional[SessionType]): The type of the sessions to read. user_id (Optional[str]): The ID of the user to read the sessions for. component_id (Optional[str]): The ID of the component to read the sessions for. session_name (Optional[str]): The name of the session to read. start_timestamp (Optional[int]): The start timestamp of the sessions to read. end_timestamp (Optional[int]): The end timestamp of the sessions to read. limit (Optional[int]): The limit of the sessions to read. page (Optional[int]): The page of the sessions to read. sort_by (Optional[str]): The field to sort the sessions by. sort_order (Optional[str]): The order to sort the sessions by. deserialize (Optional[bool]): Whether to deserialize the sessions. create_table_if_not_found (Optional[bool]): Whether to create a file to track sessions if it doesn't exist. Returns: Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of sessions - When deserialize=False: Tuple with list of sessions and total count Raises: Exception: If an error occurs while reading the sessions. """ try: sessions = self._read_json_file(self.session_table_name) # Apply filters filtered_sessions = [] for session_data in sessions: if user_id is not None and session_data.get("user_id") != user_id: continue if component_id is not None: if session_type == SessionType.AGENT and session_data.get("agent_id") != component_id: continue elif session_type == SessionType.TEAM and session_data.get("team_id") != component_id: continue elif session_type == SessionType.WORKFLOW and session_data.get("workflow_id") != component_id: continue if start_timestamp is not None and session_data.get("created_at", 0) < start_timestamp: continue if end_timestamp is not None and session_data.get("created_at", 0) > end_timestamp: continue if session_name is not None: stored_name = session_data.get("session_data", {}).get("session_name", "") if session_name.lower() not in stored_name.lower(): continue session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type if session_data.get("session_type") != session_type_value: continue filtered_sessions.append(session_data) total_count = len(filtered_sessions) # Apply sorting filtered_sessions = apply_sorting(filtered_sessions, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_sessions = filtered_sessions[start_idx : start_idx + limit] if not deserialize: return filtered_sessions, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(session) for session in filtered_sessions] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_warning(f"Exception reading from session file: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Rename a session in the GCS JSON file.""" try: sessions = self._read_json_file(self.session_table_name) for i, session_data in enumerate(sessions): if ( session_data.get("session_id") == session_id and session_data.get("session_type") == session_type.value ): if user_id is not None and session_data.get("user_id") != user_id: continue # Update session name in session_data if "session_data" not in session_data: session_data["session_data"] = {} session_data["session_data"]["session_name"] = session_name sessions[i] = session_data self._write_json_file(self.session_table_name, sessions) if not deserialize: return session_data if session_type == SessionType.AGENT: return AgentSession.from_dict(session_data) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_data) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session_data) return None except Exception as e: log_warning(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """Insert or update a session in the GCS JSON file.""" try: sessions = self._read_json_file(self.session_table_name, create_table_if_not_found=True) session_dict = session.to_dict() # Add session_type based on session instance type if isinstance(session, AgentSession): session_dict["session_type"] = SessionType.AGENT.value elif isinstance(session, TeamSession): session_dict["session_type"] = SessionType.TEAM.value elif isinstance(session, WorkflowSession): session_dict["session_type"] = SessionType.WORKFLOW.value # Find existing session to update session_updated = False for i, existing_session in enumerate(sessions): if existing_session.get("session_id") == session_dict.get("session_id") and self._matches_session_key( existing_session, session ): existing_uid = existing_session.get("user_id") if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None # Update existing session session_dict["updated_at"] = int(time.time()) sessions[i] = session_dict session_updated = True break if not session_updated: # Add new session session_dict["created_at"] = session_dict.get("created_at", int(time.time())) session_dict["updated_at"] = session_dict.get("created_at") sessions.append(session_dict) self._write_json_file(self.session_table_name, sessions) if not deserialize: return session_dict return session except Exception as e: log_warning(f"Exception upserting session: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info( f"GcsJsonDb doesn't support efficient bulk operations, falling back to individual upserts for {len(sessions)} sessions" ) # Fall back to individual upserts results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] def _matches_session_key(self, existing_session: Dict[str, Any], session: Session) -> bool: """Check if existing session matches the key for the session type.""" if isinstance(session, AgentSession): return existing_session.get("agent_id") == session.agent_id elif isinstance(session, TeamSession): return existing_session.get("team_id") == session.team_id elif isinstance(session, WorkflowSession): return existing_session.get("workflow_id") == session.workflow_id return False # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None) -> None: """Delete a user memory from the GCS JSON file. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user. If provided, verifies ownership before deletion. """ try: memories = self._read_json_file(self.memory_table_name) original_count = len(memories) # Filter out the memory, with optional user_id verification memories = [ m for m in memories if not (m.get("memory_id") == memory_id and (user_id is None or m.get("user_id") == user_id)) ] if len(memories) < original_count: self._write_json_file(self.memory_table_name, memories) log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_warning(f"Error deleting user memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple user memories from the GCS JSON file. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user. If provided, verifies ownership before deletion. """ try: memories = self._read_json_file(self.memory_table_name) # Filter out memories, with optional user_id verification memories = [ m for m in memories if not (m.get("memory_id") in memory_ids and (user_id is None or m.get("user_id") == user_id)) ] self._write_json_file(self.memory_table_name, memories) log_debug(f"Successfully deleted user memories with ids: {memory_ids}") except Exception as e: log_warning(f"Error deleting user memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the GCS JSON file. Returns: List[str]: List of unique memory topics. """ try: memories = self._read_json_file(self.memory_table_name) topics = set() for memory in memories: memory_topics = memory.get("topics", []) if isinstance(memory_topics, list): topics.update(memory_topics) return list(topics) except Exception as e: log_warning(f"Exception reading from memory file: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a memory from the GCS JSON file. Args: memory_id (str): The ID of the memory to retrieve. deserialize (Optional[bool]): Whether to deserialize to UserMemory object. Defaults to True. user_id (Optional[str]): The ID of the user. If provided, verifies ownership before returning. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: The memory if found and ownership matches, None otherwise. """ try: memories = self._read_json_file(self.memory_table_name) for memory_data in memories: if memory_data.get("memory_id") == memory_id: # Verify user ownership if user_id is provided if user_id is not None and memory_data.get("user_id") != user_id: continue if not deserialize: return memory_data return UserMemory.from_dict(memory_data) return None except Exception as e: log_warning(f"Exception reading from memory file: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the GCS JSON file with filtering and pagination.""" try: memories = self._read_json_file(self.memory_table_name) # Apply filters filtered_memories = [] for memory_data in memories: if user_id is not None and memory_data.get("user_id") != user_id: continue if agent_id is not None and memory_data.get("agent_id") != agent_id: continue if team_id is not None and memory_data.get("team_id") != team_id: continue if topics is not None: memory_topics = memory_data.get("topics", []) if not any(topic in memory_topics for topic in topics): continue if search_content is not None: memory_content = str(memory_data.get("memory", "")) if search_content.lower() not in memory_content.lower(): continue filtered_memories.append(memory_data) total_count = len(filtered_memories) # Apply sorting filtered_memories = apply_sorting(filtered_memories, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_memories = filtered_memories[start_idx : start_idx + limit] if not deserialize: return filtered_memories, total_count return [UserMemory.from_dict(memory) for memory in filtered_memories] except Exception as e: log_warning(f"Exception reading from memory file: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memory statistics. Args: limit (Optional[int]): Maximum number of results to return. page (Optional[int]): Page number for pagination. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: List of user memory statistics and total count. """ try: memories = self._read_json_file(self.memory_table_name) user_stats = {} for memory in memories: memory_user_id = memory.get("user_id") # filter by user_id if provided if user_id is not None and memory_user_id != user_id: continue if memory_user_id: if memory_user_id not in user_stats: user_stats[memory_user_id] = { "user_id": memory_user_id, "total_memories": 0, "last_memory_updated_at": 0, } user_stats[memory_user_id]["total_memories"] += 1 updated_at = memory.get("updated_at", 0) if updated_at > user_stats[memory_user_id]["last_memory_updated_at"]: user_stats[memory_user_id]["last_memory_updated_at"] = updated_at stats_list = list(user_stats.values()) stats_list.sort(key=lambda x: x["last_memory_updated_at"], reverse=True) total_count = len(stats_list) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit stats_list = stats_list[start_idx : start_idx + limit] return stats_list, total_count except Exception as e: log_warning(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the GCS JSON file.""" try: memories = self._read_json_file(self.memory_table_name, create_table_if_not_found=True) if memory.memory_id is None: memory.memory_id = str(uuid4()) memory_dict = memory.to_dict() if hasattr(memory, "to_dict") else memory.__dict__ memory_dict["updated_at"] = int(time.time()) # Find existing memory to update memory_updated = False for i, existing_memory in enumerate(memories): if existing_memory.get("memory_id") == memory.memory_id: memories[i] = memory_dict memory_updated = True break if not memory_updated: memories.append(memory_dict) self._write_json_file(self.memory_table_name, memories) if not deserialize: return memory_dict return UserMemory.from_dict(memory_dict) except Exception as e: log_error(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info( f"GcsJsonDb doesn't support efficient bulk operations, falling back to individual upserts for {len(memories)} memories" ) # Fall back to individual upserts results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: # Simply write an empty list to the memory JSON file self._write_json_file(self.memory_table_name, []) except Exception as e: log_warning(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics.""" try: metrics = self._read_json_file(self.metrics_table_name, create_table_if_not_found=True) starting_date = self._get_metrics_calculation_starting_date(metrics) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation(start_timestamp, end_timestamp) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) # Upsert metrics record existing_record_idx = None for i, existing_metric in enumerate(metrics): if ( existing_metric.get("date") == str(date_to_process) and existing_metric.get("aggregation_period") == "daily" ): existing_record_idx = i break if existing_record_idx is not None: metrics[existing_record_idx] = metrics_record else: metrics.append(metrics_record) results.append(metrics_record) if results: self._write_json_file(self.metrics_table_name, metrics) return results except Exception as e: log_warning(f"Exception refreshing metrics: {e}") raise e def _get_metrics_calculation_starting_date(self, metrics: List[Dict[str, Any]]) -> Optional[date]: """Get the first date for which metrics calculation is needed.""" if metrics: # Sort by date in descending order sorted_metrics = sorted(metrics, key=lambda x: x.get("date", ""), reverse=True) latest_metric = sorted_metrics[0] if latest_metric.get("completed", False): latest_date = datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() return latest_date + timedelta(days=1) else: return datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() # No metrics records. Return the date of the first recorded session. # We need to get sessions of all types, so we'll read directly from the file all_sessions = self._read_json_file(self.session_table_name) if all_sessions: # Sort by created_at all_sessions.sort(key=lambda x: x.get("created_at", 0)) first_session_date = all_sessions[0]["created_at"] return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() return None def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions for metrics calculation.""" try: sessions = self._read_json_file(self.session_table_name) filtered_sessions = [] for session in sessions: created_at = session.get("created_at", 0) if start_timestamp is not None and created_at < start_timestamp: continue if end_timestamp is not None and created_at >= end_timestamp: continue # Only include necessary fields for metrics filtered_session = { "user_id": session.get("user_id"), "session_data": session.get("session_data"), "runs": session.get("runs"), "created_at": session.get("created_at"), "session_type": session.get("session_type"), } filtered_sessions.append(filtered_session) return filtered_sessions except Exception as e: log_warning(f"Exception reading sessions for metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range.""" try: metrics = self._read_json_file(self.metrics_table_name) filtered_metrics = [] latest_updated_at = None for metric in metrics: metric_date = datetime.strptime(metric.get("date", ""), "%Y-%m-%d").date() if starting_date and metric_date < starting_date: continue if ending_date and metric_date > ending_date: continue filtered_metrics.append(metric) updated_at = metric.get("updated_at") if updated_at and (latest_updated_at is None or updated_at > latest_updated_at): latest_updated_at = updated_at return filtered_metrics, latest_updated_at except Exception as e: log_warning(f"Exception getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete knowledge content by ID.""" try: knowledge_items = self._read_json_file(self.knowledge_table_name) knowledge_items = [item for item in knowledge_items if item.get("id") != id] self._write_json_file(self.knowledge_table_name, knowledge_items) except Exception as e: log_warning(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get knowledge content by ID.""" try: knowledge_items = self._read_json_file(self.knowledge_table_name) for item in knowledge_items: if item.get("id") == id: return KnowledgeRow.model_validate(item) return None except Exception as e: log_warning(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the GCS JSON file. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. """ try: knowledge_items = self._read_json_file(self.knowledge_table_name) # Apply linked_to filter if provided if linked_to is not None: knowledge_items = [item for item in knowledge_items if item.get("linked_to") == linked_to] total_count = len(knowledge_items) # Apply sorting knowledge_items = apply_sorting(knowledge_items, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit knowledge_items = knowledge_items[start_idx : start_idx + limit] return [KnowledgeRow.model_validate(item) for item in knowledge_items], total_count except Exception as e: log_warning(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the GCS JSON file.""" try: knowledge_items = self._read_json_file(self.knowledge_table_name, create_table_if_not_found=True) knowledge_dict = knowledge_row.model_dump() # Find existing item to update item_updated = False for i, existing_item in enumerate(knowledge_items): if existing_item.get("id") == knowledge_row.id: knowledge_items[i] = knowledge_dict item_updated = True break if not item_updated: knowledge_items.append(knowledge_dict) self._write_json_file(self.knowledge_table_name, knowledge_items) return knowledge_row except Exception as e: log_warning(f"Error upserting knowledge row: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the GCS JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name, create_table_if_not_found=True) current_time = int(time.time()) eval_dict = eval_run.model_dump() eval_dict["created_at"] = current_time eval_dict["updated_at"] = current_time eval_runs.append(eval_dict) self._write_json_file(self.eval_table_name, eval_runs) return eval_run except Exception as e: log_warning(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the GCS JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) original_count = len(eval_runs) eval_runs = [run for run in eval_runs if run.get("run_id") != eval_run_id] if len(eval_runs) < original_count: self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Deleted eval run with ID: {eval_run_id}") else: log_warning(f"No eval run found with ID: {eval_run_id}") except Exception as e: log_warning(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the GCS JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) original_count = len(eval_runs) eval_runs = [run for run in eval_runs if run.get("run_id") not in eval_run_ids] deleted_count = original_count - len(eval_runs) if deleted_count > 0: self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Deleted {deleted_count} eval runs") else: log_warning(f"No eval runs found with IDs: {eval_run_ids}") except Exception as e: log_warning(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the GCS JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) for run_data in eval_runs: if run_data.get("run_id") == eval_run_id: if not deserialize: return run_data return EvalRunRecord.model_validate(run_data) return None except Exception as e: log_warning(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the GCS JSON file with filtering and pagination.""" try: eval_runs = self._read_json_file(self.eval_table_name) # Apply filters filtered_runs = [] for run_data in eval_runs: if agent_id is not None and run_data.get("agent_id") != agent_id: continue if team_id is not None and run_data.get("team_id") != team_id: continue if workflow_id is not None and run_data.get("workflow_id") != workflow_id: continue if model_id is not None and run_data.get("model_id") != model_id: continue if eval_type is not None and len(eval_type) > 0: if run_data.get("eval_type") not in eval_type: continue if filter_type is not None: if filter_type == EvalFilterType.AGENT and run_data.get("agent_id") is None: continue elif filter_type == EvalFilterType.TEAM and run_data.get("team_id") is None: continue elif filter_type == EvalFilterType.WORKFLOW and run_data.get("workflow_id") is None: continue filtered_runs.append(run_data) total_count = len(filtered_runs) # Apply sorting (default by created_at desc) if sort_by is None: filtered_runs.sort(key=lambda x: x.get("created_at", 0), reverse=True) else: filtered_runs = apply_sorting(filtered_runs, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_runs = filtered_runs[start_idx : start_idx + limit] if not deserialize: return filtered_runs, total_count return [EvalRunRecord.model_validate(run) for run in filtered_runs] except Exception as e: log_warning(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Rename an eval run in the GCS JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) for i, run_data in enumerate(eval_runs): if run_data.get("run_id") == eval_run_id: run_data["name"] = name run_data["updated_at"] = int(time.time()) eval_runs[i] = run_data self._write_json_file(self.eval_table_name, eval_runs) if not deserialize: return run_data return EvalRunRecord.model_validate(run_data) return None except Exception as e: log_warning(f"Error renaming eval run {eval_run_id}: {e}") raise e # -- Cultural Knowledge methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: self._write_json_file(self.culture_table_name, []) except Exception as e: log_warning(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: cultural_knowledge = self._read_json_file(self.culture_table_name) cultural_knowledge = [item for item in cultural_knowledge if item.get("id") != id] self._write_json_file(self.culture_table_name, cultural_knowledge) log_debug(f"Deleted cultural knowledge with ID: {id}") except Exception as e: log_warning(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to retrieve. deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise. Raises: Exception: If an error occurs during retrieval. """ try: cultural_knowledge = self._read_json_file(self.culture_table_name) for item in cultural_knowledge: if item.get("id") == id: if not deserialize: return item return deserialize_cultural_knowledge_from_db(item) return None except Exception as e: log_warning(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, agent_id: Optional[str] = None, team_id: Optional[str] = None, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge with filtering and pagination. Args: agent_id (Optional[str]): Filter by agent ID. team_id (Optional[str]): Filter by team ID. name (Optional[str]): Filter by name (case-insensitive partial match). limit (Optional[int]): Maximum number of results to return. page (Optional[int]): Page number for pagination. sort_by (Optional[str]): Field to sort by. sort_order (Optional[str]): Sort order ('asc' or 'desc'). deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: Tuple with list of dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: cultural_knowledge = self._read_json_file(self.culture_table_name) # Apply filters filtered_items = [] for item in cultural_knowledge: if agent_id is not None and item.get("agent_id") != agent_id: continue if team_id is not None and item.get("team_id") != team_id: continue if name is not None and name.lower() not in item.get("name", "").lower(): continue filtered_items.append(item) total_count = len(filtered_items) # Apply sorting filtered_items = apply_sorting(filtered_items, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_items = filtered_items[start_idx : start_idx + limit] if not deserialize: return filtered_items, total_count return [deserialize_cultural_knowledge_from_db(item) for item in filtered_items] except Exception as e: log_warning(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert cultural knowledge in the GCS JSON file. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge. Raises: Exception: If an error occurs during upsert. """ try: cultural_knowledge_list = self._read_json_file(self.culture_table_name, create_table_if_not_found=True) # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the item dict with serialized content cultural_knowledge_dict = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } # Find existing item to update item_updated = False for i, existing_item in enumerate(cultural_knowledge_list): if existing_item.get("id") == cultural_knowledge.id: cultural_knowledge_list[i] = cultural_knowledge_dict item_updated = True break if not item_updated: cultural_knowledge_list.append(cultural_knowledge_dict) self._write_json_file(self.culture_table_name, cultural_knowledge_list) if not deserialize: return cultural_knowledge_dict return deserialize_cultural_knowledge_from_db(cultural_knowledge_dict) except Exception as e: log_warning(f"Error upserting cultural knowledge: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ try: traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=True) # Check if trace exists existing_idx = None for i, existing in enumerate(traces): if existing.get("trace_id") == trace.trace_id: existing_idx = i break if existing_idx is not None: existing = traces[existing_idx] # workflow (level 3) > team (level 2) > agent (level 1) > child/unknown (level 0) def get_component_level(workflow_id: Any, team_id: Any, agent_id: Any, name: str) -> int: is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 elif workflow_id: return 3 elif team_id: return 2 elif agent_id: return 1 else: return 0 existing_level = get_component_level( existing.get("workflow_id"), existing.get("team_id"), existing.get("agent_id"), existing.get("name", ""), ) new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) should_update_name = new_level > existing_level # Parse existing start_time to calculate correct duration existing_start_time_str = existing.get("start_time") if isinstance(existing_start_time_str, str): existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00")) else: existing_start_time = trace.start_time recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000) # Update existing trace existing["end_time"] = trace.end_time.isoformat() existing["duration_ms"] = recalculated_duration_ms existing["status"] = trace.status if should_update_name: existing["name"] = trace.name # Update context fields only if new value is not None if trace.run_id is not None: existing["run_id"] = trace.run_id if trace.session_id is not None: existing["session_id"] = trace.session_id if trace.user_id is not None: existing["user_id"] = trace.user_id if trace.agent_id is not None: existing["agent_id"] = trace.agent_id if trace.team_id is not None: existing["team_id"] = trace.team_id if trace.workflow_id is not None: existing["workflow_id"] = trace.workflow_id traces[existing_idx] = existing else: # Add new trace trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) traces.append(trace_dict) self._write_json_file(self.trace_table_name, traces) except Exception as e: log_error(f"Error creating trace: {e}") def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return None # Get spans for calculating total_spans and error_count spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) # Filter traces filtered = [] for t in traces: if trace_id and t.get("trace_id") == trace_id: filtered.append(t) break elif run_id and t.get("run_id") == run_id: filtered.append(t) if not filtered: return None # Sort by start_time desc and get first filtered.sort(key=lambda x: x.get("start_time", ""), reverse=True) trace_data = filtered[0] # Calculate total_spans and error_count trace_spans = [s for s in spans if s.get("trace_id") == trace_data.get("trace_id")] trace_data["total_spans"] = len(trace_spans) trace_data["error_count"] = sum(1 for s in trace_spans if s.get("status_code") == "ERROR") return Trace.from_dict(trace_data) except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return [], 0 # Get spans for calculating total_spans and error_count spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) # Apply filters filtered = [] for t in traces: if run_id and t.get("run_id") != run_id: continue if session_id and t.get("session_id") != session_id: continue if user_id and t.get("user_id") != user_id: continue if agent_id and t.get("agent_id") != agent_id: continue if team_id and t.get("team_id") != team_id: continue if workflow_id and t.get("workflow_id") != workflow_id: continue if status and t.get("status") != status: continue if start_time: trace_start = t.get("start_time", "") if trace_start < start_time.isoformat(): continue if end_time: trace_end = t.get("end_time", "") if trace_end > end_time.isoformat(): continue filtered.append(t) total_count = len(filtered) # Sort by start_time desc filtered.sort(key=lambda x: x.get("start_time", ""), reverse=True) # Apply pagination if limit and page: start_idx = (page - 1) * limit filtered = filtered[start_idx : start_idx + limit] # Add total_spans and error_count to each trace result_traces = [] for t in filtered: trace_spans = [s for s in spans if s.get("trace_id") == t.get("trace_id")] t["total_spans"] = len(trace_spans) t["error_count"] = sum(1 for s in trace_spans if s.get("status_code") == "ERROR") result_traces.append(Trace.from_dict(t)) return result_traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, workflow_id, total_traces, first_trace_at, last_trace_at. """ try: traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return [], 0 # Group by session_id session_stats: Dict[str, Dict[str, Any]] = {} for t in traces: trace_session_id = t.get("session_id") if not trace_session_id: continue # Apply filters if user_id and t.get("user_id") != user_id: continue if agent_id and t.get("agent_id") != agent_id: continue if team_id and t.get("team_id") != team_id: continue if workflow_id and t.get("workflow_id") != workflow_id: continue created_at = t.get("created_at", "") if start_time and created_at < start_time.isoformat(): continue if end_time and created_at > end_time.isoformat(): continue if trace_session_id not in session_stats: session_stats[trace_session_id] = { "session_id": trace_session_id, "user_id": t.get("user_id"), "agent_id": t.get("agent_id"), "team_id": t.get("team_id"), "workflow_id": t.get("workflow_id"), "total_traces": 0, "first_trace_at": created_at, "last_trace_at": created_at, } session_stats[trace_session_id]["total_traces"] += 1 if created_at and session_stats[trace_session_id]["first_trace_at"]: if created_at < session_stats[trace_session_id]["first_trace_at"]: session_stats[trace_session_id]["first_trace_at"] = created_at if created_at and session_stats[trace_session_id]["last_trace_at"]: if created_at > session_stats[trace_session_id]["last_trace_at"]: session_stats[trace_session_id]["last_trace_at"] = created_at stats_list = list(session_stats.values()) total_count = len(stats_list) # Sort by last_trace_at desc stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True) # Apply pagination if limit and page: start_idx = (page - 1) * limit stats_list = stats_list[start_idx : start_idx + limit] # Convert ISO strings to datetime objects for stat in stats_list: first_at = stat.get("first_trace_at", "") last_at = stat.get("last_trace_at", "") if first_at: stat["first_trace_at"] = datetime.fromisoformat(first_at.replace("Z", "+00:00")) if last_at: stat["last_trace_at"] = datetime.fromisoformat(last_at.replace("Z", "+00:00")) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: spans = self._read_json_file(self.span_table_name, create_table_if_not_found=True) spans.append(span.to_dict()) self._write_json_file(self.span_table_name, spans) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: existing_spans = self._read_json_file(self.span_table_name, create_table_if_not_found=True) for span in spans: existing_spans.append(span.to_dict()) self._write_json_file(self.span_table_name, existing_spans) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) for s in spans: if s.get("span_id") == span_id: return Span.from_dict(s) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) if not spans: return [] # Apply filters filtered = [] for s in spans: if trace_id and s.get("trace_id") != trace_id: continue if parent_span_id and s.get("parent_span_id") != parent_span_id: continue filtered.append(s) # Apply limit if limit: filtered = filtered[:limit] return [Span.from_dict(s) for s in filtered] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for GcsJsonDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for GcsJsonDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for GcsJsonDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for GcsJsonDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/gcs_json/gcs_json_db.py", "license": "Apache License 2.0", "lines": 1553, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/gcs_json/utils.py
"""Utility functions for the GCS JSON database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.schemas.culture import CulturalKnowledge from agno.db.utils import get_sort_value from agno.utils.log import log_debug def apply_sorting( data: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to the given data list. Args: data: The list of dictionaries to sort sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if sort_by is None or not data: return data # Check if the sort field exists in the first item if sort_by not in data[0]: log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return data try: is_descending = sort_order != "asc" if sort_order else True # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( data, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records except Exception as e: log_debug(f"Error sorting data by '{sort_by}': {e}") return data def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process.isoformat(), "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: sessions: List of session dictionaries dates_to_process (list[date]): The dates to fetch session data for. start_timestamp (int): The starting timestamp for filtering Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: dict[str, dict[str, list[dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = date.fromtimestamp(session.get("created_at", start_timestamp)).isoformat() if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/gcs_json/utils.py", "license": "Apache License 2.0", "lines": 194, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/in_memory/in_memory_db.py
import time from copy import deepcopy from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 from agno.db.base import BaseDb, SessionType from agno.db.in_memory.utils import ( apply_sorting, calculate_date_metrics, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace class InMemoryDb(BaseDb): def __init__(self): """Interface for in-memory storage.""" super().__init__() # Initialize in-memory storage dictionaries self._sessions: List[Dict[str, Any]] = [] self._memories: List[Dict[str, Any]] = [] self._metrics: List[Dict[str, Any]] = [] self._eval_runs: List[Dict[str, Any]] = [] self._knowledge: List[Dict[str, Any]] = [] self._cultural_knowledge: List[Dict[str, Any]] = [] def table_exists(self, table_name: str) -> bool: """In-memory implementation, always returns True.""" return True def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from in-memory storage. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: original_count = len(self._sessions) self._sessions = [ s for s in self._sessions if not (s.get("session_id") == session_id and (user_id is None or s.get("user_id") == user_id)) ] if len(self._sessions) < original_count: log_debug(f"Successfully deleted session with session_id: {session_id}") return True else: log_debug(f"No session found to delete with session_id: {session_id}") return False except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from in-memory storage. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: self._sessions = [ s for s in self._sessions if not (s.get("session_id") in session_ids and (user_id is None or s.get("user_id") == user_id)) ] log_debug(f"Successfully deleted sessions with ids: {session_ids}") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[AgentSession, TeamSession, WorkflowSession, Dict[str, Any]]]: """Read a session from in-memory storage. Args: session_id (str): The ID of the session to read. session_type (SessionType): The type of the session to read. user_id (Optional[str]): The ID of the user to read the session for. deserialize (Optional[bool]): Whether to deserialize the session. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs while reading the session. """ try: for session_data in self._sessions: if session_data.get("session_id") == session_id: if user_id is not None and session_data.get("user_id") != user_id: continue session_data_copy = deepcopy(session_data) if not deserialize: return session_data_copy if session_type == SessionType.AGENT: return AgentSession.from_dict(session_data_copy) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_data_copy) else: return WorkflowSession.from_dict(session_data_copy) return None except Exception as e: import traceback traceback.print_exc() log_error(f"Exception reading session: {e}") raise e def get_sessions( self, session_type: SessionType, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions from in-memory storage with filtering and pagination. Args: session_type (SessionType): The type of the sessions to read. user_id (Optional[str]): The ID of the user to read the sessions for. component_id (Optional[str]): The ID of the component to read the sessions for. session_name (Optional[str]): The name of the session to read. start_timestamp (Optional[int]): The start timestamp of the sessions to read. end_timestamp (Optional[int]): The end timestamp of the sessions to read. limit (Optional[int]): The limit of the sessions to read. page (Optional[int]): The page of the sessions to read. sort_by (Optional[str]): The field to sort the sessions by. sort_order (Optional[str]): The order to sort the sessions by. deserialize (Optional[bool]): Whether to deserialize the sessions. Returns: Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of sessions - When deserialize=False: Tuple with list of sessions and total count Raises: Exception: If an error occurs while reading the sessions. """ try: # Apply filters filtered_sessions = [] for session_data in self._sessions: if user_id is not None and session_data.get("user_id") != user_id: continue if component_id is not None: if session_type == SessionType.AGENT and session_data.get("agent_id") != component_id: continue elif session_type == SessionType.TEAM and session_data.get("team_id") != component_id: continue elif session_type == SessionType.WORKFLOW and session_data.get("workflow_id") != component_id: continue if start_timestamp is not None and session_data.get("created_at", 0) < start_timestamp: continue if end_timestamp is not None and session_data.get("created_at", 0) > end_timestamp: continue if session_name is not None: stored_name = session_data.get("session_data", {}).get("session_name", "") if session_name.lower() not in stored_name.lower(): continue session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type if session_data.get("session_type") != session_type_value: continue filtered_sessions.append(deepcopy(session_data)) total_count = len(filtered_sessions) # Apply sorting filtered_sessions = apply_sorting(filtered_sessions, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_sessions = filtered_sessions[start_idx : start_idx + limit] if not deserialize: return filtered_sessions, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(session) for session in filtered_sessions] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: try: for i, session in enumerate(self._sessions): if session.get("session_id") == session_id and session.get("session_type") == session_type.value: if user_id is not None and session.get("user_id") != user_id: continue # Update session name in session_data if "session_data" not in session: session["session_data"] = {} session["session_data"]["session_name"] = session_name self._sessions[i] = session log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") session_copy = deepcopy(session) if not deserialize: return session_copy if session_type == SessionType.AGENT: return AgentSession.from_dict(session_copy) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_copy) else: return WorkflowSession.from_dict(session_copy) return None except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: try: session_dict = session.to_dict() # Add session_type based on session instance type if isinstance(session, AgentSession): session_dict["session_type"] = SessionType.AGENT.value elif isinstance(session, TeamSession): session_dict["session_type"] = SessionType.TEAM.value elif isinstance(session, WorkflowSession): session_dict["session_type"] = SessionType.WORKFLOW.value # Find existing session to update session_updated = False for i, existing_session in enumerate(self._sessions): if existing_session.get("session_id") == session_dict.get("session_id") and self._matches_session_key( existing_session, session ): existing_uid = existing_session.get("user_id") if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None session_dict["updated_at"] = int(time.time()) self._sessions[i] = deepcopy(session_dict) session_updated = True break if not session_updated: session_dict["created_at"] = session_dict.get("created_at", int(time.time())) session_dict["updated_at"] = session_dict.get("created_at") self._sessions.append(deepcopy(session_dict)) session_dict_copy = deepcopy(session_dict) if not deserialize: return session_dict_copy if session_dict_copy["session_type"] == SessionType.AGENT: return AgentSession.from_dict(session_dict_copy) elif session_dict_copy["session_type"] == SessionType.TEAM: return TeamSession.from_dict(session_dict_copy) else: return WorkflowSession.from_dict(session_dict_copy) except Exception as e: log_error(f"Exception upserting session: {e}") raise e def _matches_session_key(self, existing_session: Dict[str, Any], session: Session) -> bool: """Check if existing session matches the key for the session type.""" if isinstance(session, AgentSession): return existing_session.get("agent_id") == session.agent_id elif isinstance(session, TeamSession): return existing_session.get("team_id") == session.team_id elif isinstance(session, WorkflowSession): return existing_session.get("workflow_id") == session.workflow_id return False def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info(f"In-memory database: processing {len(sessions)} sessions with individual upsert operations") results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from in-memory storage. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user. If provided, verifies the memory belongs to this user before deletion. Raises: Exception: If an error occurs during deletion. """ try: original_count = len(self._memories) # If user_id is provided, verify ownership before deleting if user_id is not None: self._memories = [ m for m in self._memories if not (m.get("memory_id") == memory_id and m.get("user_id") == user_id) ] else: self._memories = [m for m in self._memories if m.get("memory_id") != memory_id] if len(self._memories) < original_count: log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple user memories from in-memory storage. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user. If provided, only deletes memories belonging to this user. Raises: Exception: If an error occurs during deletion. """ try: # If user_id is provided, verify ownership before deleting if user_id is not None: self._memories = [ m for m in self._memories if not (m.get("memory_id") in memory_ids and m.get("user_id") == user_id) ] else: self._memories = [m for m in self._memories if m.get("memory_id") not in memory_ids] log_debug(f"Successfully deleted {len(memory_ids)} user memories") except Exception as e: log_error(f"Error deleting memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from in-memory storage. Returns: List[str]: List of unique topics. Raises: Exception: If an error occurs while reading topics. """ try: topics = set() for memory in self._memories: memory_topics = memory.get("topics", []) if isinstance(memory_topics, list): topics.update(memory_topics) return list(topics) except Exception as e: log_error(f"Exception reading from memory storage: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a user memory from in-memory storage. Args: memory_id (str): The ID of the memory to retrieve. deserialize (Optional[bool]): Whether to deserialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user. If provided, only returns the memory if it belongs to this user. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: The memory object or dictionary, or None if not found. Raises: Exception: If an error occurs while reading the memory. """ try: for memory_data in self._memories: if memory_data.get("memory_id") == memory_id: # Filter by user_id if provided if user_id is not None and memory_data.get("user_id") != user_id: continue memory_data_copy = deepcopy(memory_data) if not deserialize: return memory_data_copy return UserMemory.from_dict(memory_data_copy) return None except Exception as e: log_error(f"Exception reading from memory storage: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: try: # Apply filters filtered_memories = [] for memory_data in self._memories: if user_id is not None and memory_data.get("user_id") != user_id: continue if agent_id is not None and memory_data.get("agent_id") != agent_id: continue if team_id is not None and memory_data.get("team_id") != team_id: continue if topics is not None: memory_topics = memory_data.get("topics", []) if not any(topic in memory_topics for topic in topics): continue if search_content is not None: memory_content = str(memory_data.get("memory", "")) if search_content.lower() not in memory_content.lower(): continue filtered_memories.append(deepcopy(memory_data)) total_count = len(filtered_memories) # Apply sorting filtered_memories = apply_sorting(filtered_memories, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_memories = filtered_memories[start_idx : start_idx + limit] if not deserialize: return filtered_memories, total_count return [UserMemory.from_dict(memory) for memory in filtered_memories] except Exception as e: log_error(f"Exception reading from memory storage: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memory statistics. Args: limit (Optional[int]): Maximum number of stats to return. page (Optional[int]): Page number for pagination. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: List of user memory statistics and total count. Raises: Exception: If an error occurs while getting stats. """ try: user_stats = {} for memory in self._memories: memory_user_id = memory.get("user_id") # filter by user_id if provided if user_id is not None and memory_user_id != user_id: continue if memory_user_id: if memory_user_id not in user_stats: user_stats[memory_user_id] = { "user_id": memory_user_id, "total_memories": 0, "last_memory_updated_at": 0, } user_stats[memory_user_id]["total_memories"] += 1 updated_at = memory.get("updated_at", 0) if updated_at > user_stats[memory_user_id]["last_memory_updated_at"]: user_stats[memory_user_id]["last_memory_updated_at"] = updated_at stats_list = list(user_stats.values()) stats_list.sort(key=lambda x: x["last_memory_updated_at"], reverse=True) total_count = len(stats_list) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit stats_list = stats_list[start_idx : start_idx + limit] return stats_list, total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: try: if memory.memory_id is None: memory.memory_id = str(uuid4()) memory_dict = memory.to_dict() if hasattr(memory, "to_dict") else memory.__dict__ memory_dict["updated_at"] = int(time.time()) # Find existing memory to update memory_updated = False for i, existing_memory in enumerate(self._memories): if existing_memory.get("memory_id") == memory.memory_id: self._memories[i] = memory_dict memory_updated = True break if not memory_updated: self._memories.append(memory_dict) memory_dict_copy = deepcopy(memory_dict) if not deserialize: return memory_dict_copy return UserMemory.from_dict(memory_dict_copy) except Exception as e: log_warning(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info(f"In-memory database: processing {len(memories)} memories with individual upsert operations") # For in-memory database, individual upserts are actually efficient # since we're just manipulating Python lists and dictionaries results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories. Raises: Exception: If an error occurs during deletion. """ try: self._memories.clear() except Exception as e: log_warning(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics.""" try: starting_date = self._get_metrics_calculation_starting_date(self._metrics) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation(start_timestamp, end_timestamp) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) # Upsert metrics record existing_record_idx = None for i, existing_metric in enumerate(self._metrics): if ( existing_metric.get("date") == str(date_to_process) and existing_metric.get("aggregation_period") == "daily" ): existing_record_idx = i break if existing_record_idx is not None: self._metrics[existing_record_idx] = metrics_record else: self._metrics.append(metrics_record) results.append(metrics_record) log_debug("Updated metrics calculations") return results except Exception as e: log_warning(f"Exception refreshing metrics: {e}") raise e def _get_metrics_calculation_starting_date(self, metrics: List[Dict[str, Any]]) -> Optional[date]: """Get the first date for which metrics calculation is needed.""" if metrics: # Sort by date in descending order sorted_metrics = sorted(metrics, key=lambda x: x.get("date", ""), reverse=True) latest_metric = sorted_metrics[0] if latest_metric.get("completed", False): latest_date = datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() return latest_date + timedelta(days=1) else: return datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() # No metrics records. Return the date of the first recorded session. if self._sessions: # Sort by created_at sorted_sessions = sorted(self._sessions, key=lambda x: x.get("created_at", 0)) first_session_date = sorted_sessions[0]["created_at"] return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() return None def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions for metrics calculation.""" try: filtered_sessions = [] for session in self._sessions: created_at = session.get("created_at", 0) if start_timestamp is not None and created_at < start_timestamp: continue if end_timestamp is not None and created_at >= end_timestamp: continue # Only include necessary fields for metrics filtered_session = { "user_id": session.get("user_id"), "session_data": deepcopy(session.get("session_data")), "runs": deepcopy(session.get("runs")), "created_at": session.get("created_at"), "session_type": session.get("session_type"), } filtered_sessions.append(filtered_session) return filtered_sessions except Exception as e: log_error(f"Exception reading sessions for metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range.""" try: filtered_metrics = [] latest_updated_at = None for metric in self._metrics: metric_date = datetime.strptime(metric.get("date", ""), "%Y-%m-%d").date() if starting_date and metric_date < starting_date: continue if ending_date and metric_date > ending_date: continue filtered_metrics.append(deepcopy(metric)) updated_at = metric.get("updated_at") if updated_at and (latest_updated_at is None or updated_at > latest_updated_at): latest_updated_at = updated_at return filtered_metrics, latest_updated_at except Exception as e: log_error(f"Exception getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from in-memory storage. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ try: self._knowledge = [item for item in self._knowledge if item.get("id") != id] except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from in-memory storage. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: for item in self._knowledge: if item.get("id") == id: return KnowledgeRow.model_validate(item) return None except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from in-memory storage. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ try: knowledge_items = [deepcopy(item) for item in self._knowledge] # Apply linked_to filter if provided if linked_to is not None: knowledge_items = [item for item in knowledge_items if item.get("linked_to") == linked_to] total_count = len(knowledge_items) # Apply sorting knowledge_items = apply_sorting(knowledge_items, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit knowledge_items = knowledge_items[start_idx : start_idx + limit] return [KnowledgeRow.model_validate(item) for item in knowledge_items], total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. Raises: Exception: If an error occurs during upsert. """ try: knowledge_dict = knowledge_row.model_dump() # Find existing item to update item_updated = False for i, existing_item in enumerate(self._knowledge): if existing_item.get("id") == knowledge_row.id: self._knowledge[i] = knowledge_dict item_updated = True break if not item_updated: self._knowledge.append(knowledge_dict) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge row: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord""" try: current_time = int(time.time()) eval_dict = eval_run.model_dump() eval_dict["created_at"] = current_time eval_dict["updated_at"] = current_time self._eval_runs.append(eval_dict) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from in-memory storage.""" try: original_count = len(self._eval_runs) self._eval_runs = [run for run in self._eval_runs if run.get("run_id") not in eval_run_ids] deleted_count = original_count - len(self._eval_runs) if deleted_count > 0: log_debug(f"Deleted {deleted_count} eval runs") else: log_debug(f"No eval runs found with IDs: {eval_run_ids}") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from in-memory storage.""" try: for run_data in self._eval_runs: if run_data.get("run_id") == eval_run_id: run_data_copy = deepcopy(run_data) if not deserialize: return run_data_copy return EvalRunRecord.model_validate(run_data_copy) return None except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from in-memory storage with filtering and pagination.""" try: # Apply filters filtered_runs = [] for run_data in self._eval_runs: if agent_id is not None and run_data.get("agent_id") != agent_id: continue if team_id is not None and run_data.get("team_id") != team_id: continue if workflow_id is not None and run_data.get("workflow_id") != workflow_id: continue if model_id is not None and run_data.get("model_id") != model_id: continue if eval_type is not None and len(eval_type) > 0: if run_data.get("eval_type") not in eval_type: continue if filter_type is not None: if filter_type == EvalFilterType.AGENT and run_data.get("agent_id") is None: continue elif filter_type == EvalFilterType.TEAM and run_data.get("team_id") is None: continue elif filter_type == EvalFilterType.WORKFLOW and run_data.get("workflow_id") is None: continue filtered_runs.append(deepcopy(run_data)) total_count = len(filtered_runs) # Apply sorting (default by created_at desc) if sort_by is None: filtered_runs.sort(key=lambda x: x.get("created_at", 0), reverse=True) else: filtered_runs = apply_sorting(filtered_runs, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_runs = filtered_runs[start_idx : start_idx + limit] if not deserialize: return filtered_runs, total_count return [EvalRunRecord.model_validate(run) for run in filtered_runs] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Rename an eval run.""" try: for i, run_data in enumerate(self._eval_runs): if run_data.get("run_id") == eval_run_id: run_data["name"] = name run_data["updated_at"] = int(time.time()) self._eval_runs[i] = run_data log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") run_data_copy = deepcopy(run_data) if not deserialize: return run_data_copy return EvalRunRecord.model_validate(run_data_copy) return None except Exception as e: log_error(f"Error renaming eval run {eval_run_id}: {e}") raise e # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from in-memory storage.""" try: self._cultural_knowledge = [] except Exception as e: log_error(f"Error clearing cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from in-memory storage.""" try: self._cultural_knowledge = [ck for ck in self._cultural_knowledge if ck.get("id") != id] except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from in-memory storage.""" try: for ck_data in self._cultural_knowledge: if ck_data.get("id") == id: ck_data_copy = deepcopy(ck_data) if not deserialize: return ck_data_copy return deserialize_cultural_knowledge_from_db(ck_data_copy) return None except Exception as e: log_error(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from in-memory storage.""" try: filtered_ck = [] for ck_data in self._cultural_knowledge: if name and ck_data.get("name") != name: continue if agent_id and ck_data.get("agent_id") != agent_id: continue if team_id and ck_data.get("team_id") != team_id: continue filtered_ck.append(ck_data) # Apply sorting if sort_by: filtered_ck = apply_sorting(filtered_ck, sort_by, sort_order) total_count = len(filtered_ck) # Apply pagination if limit and page: start = (page - 1) * limit filtered_ck = filtered_ck[start : start + limit] elif limit: filtered_ck = filtered_ck[:limit] if not deserialize: return [deepcopy(ck) for ck in filtered_ck], total_count return [deserialize_cultural_knowledge_from_db(deepcopy(ck)) for ck in filtered_ck] except Exception as e: log_error(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into in-memory storage.""" try: if not cultural_knowledge.id: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the item dict with serialized content ck_dict = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } # Remove existing entry with same id self._cultural_knowledge = [ck for ck in self._cultural_knowledge if ck.get("id") != cultural_knowledge.id] # Add new entry self._cultural_knowledge.append(ck_dict) return self.get_cultural_knowledge(cultural_knowledge.id, deserialize=deserialize) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ raise NotImplementedError def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ raise NotImplementedError def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ raise NotImplementedError def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, workflow_id, total_traces, first_trace_at, last_trace_at. """ raise NotImplementedError # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ raise NotImplementedError def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ raise NotImplementedError def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ raise NotImplementedError def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ raise NotImplementedError # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for InMemoryDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for InMemoryDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for InMemoryDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for InMemoryDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/in_memory/in_memory_db.py", "license": "Apache License 2.0", "lines": 1143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/in_memory/utils.py
"""Utility functions for the in-memory database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.schemas.culture import CulturalKnowledge from agno.db.utils import get_sort_value from agno.utils.log import log_debug def apply_sorting( data: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to the given data list. Args: data: The list of dictionaries to sort sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if sort_by is None or not data: return data # Check if the sort field exists in the first item if sort_by not in data[0]: log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return data try: is_descending = sort_order != "asc" if sort_order else True # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( data, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records except Exception as e: log_debug(f"Error sorting data by '{sort_by}': {e}") return data def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process.isoformat(), "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: sessions: List of session dictionaries dates_to_process (list[date]): The dates to fetch session data for. start_timestamp (int): The starting timestamp for filtering Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/in_memory/utils.py", "license": "Apache License 2.0", "lines": 196, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/json/json_db.py
import json import os import time from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.json.utils import ( apply_sorting, calculate_date_metrics, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id class JsonDb(BaseDb): def __init__( self, db_path: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, id: Optional[str] = None, ): """ Interface for interacting with JSON files as database. Args: db_path (Optional[str]): Path to the directory where JSON files will be stored. session_table (Optional[str]): Name of the JSON file to store sessions (without .json extension). culture_table (Optional[str]): Name of the JSON file to store cultural knowledge. memory_table (Optional[str]): Name of the JSON file to store memories. metrics_table (Optional[str]): Name of the JSON file to store metrics. eval_table (Optional[str]): Name of the JSON file to store evaluation runs. knowledge_table (Optional[str]): Name of the JSON file to store knowledge content. traces_table (Optional[str]): Name of the JSON file to store run traces. spans_table (Optional[str]): Name of the JSON file to store span events. id (Optional[str]): ID of the database. """ if id is None: seed = db_path or "agno_json_db" id = generate_id(seed) super().__init__( id=id, session_table=session_table, culture_table=culture_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, traces_table=traces_table, spans_table=spans_table, ) # Create the directory where the JSON files will be stored, if it doesn't exist self.db_path = Path(db_path or os.path.join(os.getcwd(), "agno_json_db")) def table_exists(self, table_name: str) -> bool: """JSON implementation, always returns True.""" return True def _read_json_file(self, filename: str, create_table_if_not_found: Optional[bool] = True) -> List[Dict[str, Any]]: """Read data from a JSON file, creating it if it doesn't exist. Args: filename (str): The name of the JSON file to read. Returns: List[Dict[str, Any]]: The data from the JSON file. Raises: json.JSONDecodeError: If the JSON file is not valid. """ file_path = self.db_path / f"{filename}.json" # Create directory if it doesn't exist self.db_path.mkdir(parents=True, exist_ok=True) try: with open(file_path, "r") as f: return json.load(f) except FileNotFoundError: if create_table_if_not_found: with open(file_path, "w") as f: json.dump([], f) return [] except json.JSONDecodeError as e: log_error(f"Error reading the {file_path} JSON file") raise e def _write_json_file(self, filename: str, data: List[Dict[str, Any]]) -> None: """Write data to a JSON file. Args: filename (str): The name of the JSON file to write. data (List[Dict[str, Any]]): The data to write to the JSON file. Raises: Exception: If an error occurs while writing to the JSON file. """ file_path = self.db_path / f"{filename}.json" # Create directory if it doesn't exist self.db_path.mkdir(parents=True, exist_ok=True) try: with open(file_path, "w") as f: json.dump(data, f, indent=2, default=str) except Exception as e: log_error(f"Error writing to the {file_path} JSON file: {e}") raise e def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from the JSON file. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: sessions = self._read_json_file(self.session_table_name) original_count = len(sessions) sessions = [ s for s in sessions if not (s.get("session_id") == session_id and (user_id is None or s.get("user_id") == user_id)) ] if len(sessions) < original_count: self._write_json_file(self.session_table_name, sessions) log_debug(f"Successfully deleted session with session_id: {session_id}") return True else: log_debug(f"No session found to delete with session_id: {session_id}") return False except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from the JSON file. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: sessions = self._read_json_file(self.session_table_name) sessions = [ s for s in sessions if not (s.get("session_id") in session_ids and (user_id is None or s.get("user_id") == user_id)) ] self._write_json_file(self.session_table_name, sessions) log_debug(f"Successfully deleted sessions with ids: {session_ids}") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[AgentSession, TeamSession, WorkflowSession, Dict[str, Any]]]: """Read a session from the JSON file. Args: session_id (str): The ID of the session to read. session_type (SessionType): The type of the session to read. user_id (Optional[str]): The ID of the user to read the session for. deserialize (Optional[bool]): Whether to deserialize the session. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs while reading the session. """ try: sessions = self._read_json_file(self.session_table_name) for session_data in sessions: if session_data.get("session_id") == session_id: if user_id is not None and session_data.get("user_id") != user_id: continue if not deserialize: return session_data if session_type == SessionType.AGENT: return AgentSession.from_dict(session_data) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_data) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session_data) else: raise ValueError(f"Invalid session type: {session_type}") return None except Exception as e: log_error(f"Exception reading from session file: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions from the JSON file with filtering and pagination. Args: session_type (Optional[SessionType]): The type of the sessions to read. user_id (Optional[str]): The ID of the user to read the sessions for. component_id (Optional[str]): The ID of the component to read the sessions for. session_name (Optional[str]): The name of the session to read. start_timestamp (Optional[int]): The start timestamp of the sessions to read. end_timestamp (Optional[int]): The end timestamp of the sessions to read. limit (Optional[int]): The limit of the sessions to read. page (Optional[int]): The page of the sessions to read. sort_by (Optional[str]): The field to sort the sessions by. sort_order (Optional[str]): The order to sort the sessions by. deserialize (Optional[bool]): Whether to deserialize the sessions. create_table_if_not_found (Optional[bool]): Whether to create a json file to track sessions if it doesn't exist. Returns: Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of sessions - When deserialize=False: Tuple with list of sessions and total count Raises: Exception: If an error occurs while reading the sessions. """ try: sessions = self._read_json_file(self.session_table_name) # Apply filters filtered_sessions = [] for session_data in sessions: if user_id is not None and session_data.get("user_id") != user_id: continue if component_id is not None: if session_type == SessionType.AGENT and session_data.get("agent_id") != component_id: continue elif session_type == SessionType.TEAM and session_data.get("team_id") != component_id: continue elif session_type == SessionType.WORKFLOW and session_data.get("workflow_id") != component_id: continue if start_timestamp is not None and session_data.get("created_at", 0) < start_timestamp: continue if end_timestamp is not None and session_data.get("created_at", 0) > end_timestamp: continue if session_name is not None: stored_name = session_data.get("session_data", {}).get("session_name", "") if session_name.lower() not in stored_name.lower(): continue session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type if session_data.get("session_type") != session_type_value: continue filtered_sessions.append(session_data) total_count = len(filtered_sessions) # Apply sorting filtered_sessions = apply_sorting(filtered_sessions, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_sessions = filtered_sessions[start_idx : start_idx + limit] if not deserialize: return filtered_sessions, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(session) for session in filtered_sessions] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(session) for session in filtered_sessions] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session file: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Rename a session in the JSON file.""" try: sessions = self._read_json_file(self.session_table_name) for i, session in enumerate(sessions): if session.get("session_id") == session_id and session.get("session_type") == session_type.value: if user_id is not None and session.get("user_id") != user_id: continue # Update session name in session_data if "session_data" not in session: session["session_data"] = {} session["session_data"]["session_name"] = session_name sessions[i] = session self._write_json_file(self.session_table_name, sessions) log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") return None except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """Insert or update a session in the JSON file.""" try: sessions = self._read_json_file(self.session_table_name, create_table_if_not_found=True) session_dict = session.to_dict() # Add session_type based on session instance type if isinstance(session, AgentSession): session_dict["session_type"] = SessionType.AGENT.value elif isinstance(session, TeamSession): session_dict["session_type"] = SessionType.TEAM.value elif isinstance(session, WorkflowSession): session_dict["session_type"] = SessionType.WORKFLOW.value # Find existing session to update session_updated = False for i, existing_session in enumerate(sessions): if existing_session.get("session_id") == session_dict.get("session_id") and self._matches_session_key( existing_session, session ): existing_uid = existing_session.get("user_id") if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None # Update existing session session_dict["updated_at"] = int(time.time()) sessions[i] = session_dict session_updated = True break if not session_updated: # Add new session session_dict["created_at"] = session_dict.get("created_at", int(time.time())) session_dict["updated_at"] = session_dict.get("created_at") sessions.append(session_dict) self._write_json_file(self.session_table_name, sessions) if not deserialize: return session_dict return session except Exception as e: log_error(f"Exception upserting session: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info( f"JsonDb doesn't support efficient bulk operations, falling back to individual upserts for {len(sessions)} sessions" ) # Fall back to individual upserts results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] def _matches_session_key(self, existing_session: Dict[str, Any], session: Session) -> bool: """Check if existing session matches the key for the session type.""" if isinstance(session, AgentSession): return existing_session.get("agent_id") == session.agent_id elif isinstance(session, TeamSession): return existing_session.get("team_id") == session.team_id elif isinstance(session, WorkflowSession): return existing_session.get("workflow_id") == session.workflow_id return False # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the JSON file. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user (optional, for filtering). """ try: memories = self._read_json_file(self.memory_table_name) original_count = len(memories) # If user_id is provided, verify the memory belongs to the user before deleting if user_id is not None: memory_to_delete = None for m in memories: if m.get("memory_id") == memory_id: memory_to_delete = m break if memory_to_delete and memory_to_delete.get("user_id") != user_id: log_debug(f"Memory {memory_id} does not belong to user {user_id}") return memories = [m for m in memories if m.get("memory_id") != memory_id] if len(memories) < original_count: self._write_json_file(self.memory_table_name, memories) log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple user memories from the JSON file. Args: memory_ids (List[str]): List of memory IDs to delete. user_id (Optional[str]): The ID of the user (optional, for filtering). """ try: memories = self._read_json_file(self.memory_table_name) # If user_id is provided, filter memory_ids to only those belonging to the user if user_id is not None: filtered_memory_ids: List[str] = [] for memory in memories: if memory.get("memory_id") in memory_ids and memory.get("user_id") == user_id: filtered_memory_ids.append(memory.get("memory_id")) # type: ignore memory_ids = filtered_memory_ids memories = [m for m in memories if m.get("memory_id") not in memory_ids] self._write_json_file(self.memory_table_name, memories) log_debug(f"Successfully deleted {len(memory_ids)} user memories") except Exception as e: log_error(f"Error deleting memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the JSON file. Returns: List[str]: List of unique memory topics. """ try: memories = self._read_json_file(self.memory_table_name) topics = set() for memory in memories: memory_topics = memory.get("topics", []) if isinstance(memory_topics, list): topics.update(memory_topics) return list(topics) except Exception as e: log_error(f"Exception reading from memory file: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None, ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a memory from the JSON file. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to deserialize the memory. user_id (Optional[str]): The ID of the user (optional, for filtering). Returns: Optional[Union[UserMemory, Dict[str, Any]]]: The user memory data if found, None otherwise. """ try: memories = self._read_json_file(self.memory_table_name) for memory_data in memories: if memory_data.get("memory_id") == memory_id: # Filter by user_id if provided if user_id and memory_data.get("user_id") != user_id: return None if not deserialize: return memory_data return UserMemory.from_dict(memory_data) return None except Exception as e: log_error(f"Exception reading from memory file: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the JSON file with filtering and pagination.""" try: memories = self._read_json_file(self.memory_table_name) # Apply filters filtered_memories = [] for memory_data in memories: if user_id is not None and memory_data.get("user_id") != user_id: continue if agent_id is not None and memory_data.get("agent_id") != agent_id: continue if team_id is not None and memory_data.get("team_id") != team_id: continue if topics is not None: memory_topics = memory_data.get("topics", []) if not any(topic in memory_topics for topic in topics): continue if search_content is not None: memory_content = str(memory_data.get("memory", "")) if search_content.lower() not in memory_content.lower(): continue filtered_memories.append(memory_data) total_count = len(filtered_memories) # Apply sorting filtered_memories = apply_sorting(filtered_memories, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_memories = filtered_memories[start_idx : start_idx + limit] if not deserialize: return filtered_memories, total_count return [UserMemory.from_dict(memory) for memory in filtered_memories] except Exception as e: log_error(f"Exception reading from memory file: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memory statistics. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. """ try: memories = self._read_json_file(self.memory_table_name) user_stats = {} for memory in memories: memory_user_id = memory.get("user_id") # filter by user_id if provided if user_id is not None and memory_user_id != user_id: continue if memory_user_id: if memory_user_id not in user_stats: user_stats[memory_user_id] = { "user_id": memory_user_id, "total_memories": 0, "last_memory_updated_at": 0, } user_stats[memory_user_id]["total_memories"] += 1 updated_at = memory.get("updated_at", 0) if updated_at > user_stats[memory_user_id]["last_memory_updated_at"]: user_stats[memory_user_id]["last_memory_updated_at"] = updated_at stats_list = list(user_stats.values()) stats_list.sort(key=lambda x: x["last_memory_updated_at"], reverse=True) total_count = len(stats_list) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit stats_list = stats_list[start_idx : start_idx + limit] return stats_list, total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the JSON file.""" try: memories = self._read_json_file(self.memory_table_name, create_table_if_not_found=True) if memory.memory_id is None: memory.memory_id = str(uuid4()) memory_dict = memory.to_dict() if hasattr(memory, "to_dict") else memory.__dict__ memory_dict["updated_at"] = int(time.time()) # Find existing memory to update memory_updated = False for i, existing_memory in enumerate(memories): if existing_memory.get("memory_id") == memory.memory_id: memories[i] = memory_dict memory_updated = True break if not memory_updated: memories.append(memory_dict) self._write_json_file(self.memory_table_name, memories) if not deserialize: return memory_dict return UserMemory.from_dict(memory_dict) except Exception as e: log_warning(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info( f"JsonDb doesn't support efficient bulk operations, falling back to individual upserts for {len(memories)} memories" ) # Fall back to individual upserts results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: # Simply write an empty list to the memory JSON file self._write_json_file(self.memory_table_name, []) except Exception as e: log_warning(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics.""" try: metrics = self._read_json_file(self.metrics_table_name, create_table_if_not_found=True) starting_date = self._get_metrics_calculation_starting_date(metrics) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation(start_timestamp, end_timestamp) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) # Upsert metrics record existing_record_idx = None for i, existing_metric in enumerate(metrics): if ( existing_metric.get("date") == str(date_to_process) and existing_metric.get("aggregation_period") == "daily" ): existing_record_idx = i break if existing_record_idx is not None: metrics[existing_record_idx] = metrics_record else: metrics.append(metrics_record) results.append(metrics_record) if results: self._write_json_file(self.metrics_table_name, metrics) log_debug("Updated metrics calculations") return results except Exception as e: log_warning(f"Exception refreshing metrics: {e}") raise e def _get_metrics_calculation_starting_date(self, metrics: List[Dict[str, Any]]) -> Optional[date]: """Get the first date for which metrics calculation is needed.""" if metrics: # Sort by date in descending order sorted_metrics = sorted(metrics, key=lambda x: x.get("date", ""), reverse=True) latest_metric = sorted_metrics[0] if latest_metric.get("completed", False): latest_date = datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() return latest_date + timedelta(days=1) else: return datetime.strptime(latest_metric["date"], "%Y-%m-%d").date() # No metrics records. Return the date of the first recorded session. # We need to get sessions of all types, so we'll read directly from the file all_sessions = self._read_json_file(self.session_table_name) if all_sessions: # Sort by created_at all_sessions.sort(key=lambda x: x.get("created_at", 0)) first_session_date = all_sessions[0]["created_at"] return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() return None def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions for metrics calculation.""" try: sessions = self._read_json_file(self.session_table_name) filtered_sessions = [] for session in sessions: created_at = session.get("created_at", 0) if start_timestamp is not None and created_at < start_timestamp: continue if end_timestamp is not None and created_at >= end_timestamp: continue # Only include necessary fields for metrics filtered_session = { "user_id": session.get("user_id"), "session_data": session.get("session_data"), "runs": session.get("runs"), "created_at": session.get("created_at"), "session_type": session.get("session_type"), } filtered_sessions.append(filtered_session) return filtered_sessions except Exception as e: log_error(f"Exception reading sessions for metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range.""" try: metrics = self._read_json_file(self.metrics_table_name) filtered_metrics = [] latest_updated_at = None for metric in metrics: metric_date = datetime.strptime(metric.get("date", ""), "%Y-%m-%d").date() if starting_date and metric_date < starting_date: continue if ending_date and metric_date > ending_date: continue filtered_metrics.append(metric) updated_at = metric.get("updated_at") if updated_at and (latest_updated_at is None or updated_at > latest_updated_at): latest_updated_at = updated_at return filtered_metrics, latest_updated_at except Exception as e: log_error(f"Exception getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ try: knowledge_items = self._read_json_file(self.knowledge_table_name) knowledge_items = [item for item in knowledge_items if item.get("id") != id] self._write_json_file(self.knowledge_table_name, knowledge_items) except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: knowledge_items = self._read_json_file(self.knowledge_table_name) for item in knowledge_items: if item.get("id") == id: return KnowledgeRow.model_validate(item) return None except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ try: knowledge_items = self._read_json_file(self.knowledge_table_name) # Apply linked_to filter if provided if linked_to is not None: knowledge_items = [item for item in knowledge_items if item.get("linked_to") == linked_to] total_count = len(knowledge_items) # Apply sorting knowledge_items = apply_sorting(knowledge_items, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit knowledge_items = knowledge_items[start_idx : start_idx + limit] return [KnowledgeRow.model_validate(item) for item in knowledge_items], total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. Raises: Exception: If an error occurs during upsert. """ try: knowledge_items = self._read_json_file(self.knowledge_table_name, create_table_if_not_found=True) knowledge_dict = knowledge_row.model_dump() # Find existing item to update item_updated = False for i, existing_item in enumerate(knowledge_items): if existing_item.get("id") == knowledge_row.id: knowledge_items[i] = knowledge_dict item_updated = True break if not item_updated: knowledge_items.append(knowledge_dict) self._write_json_file(self.knowledge_table_name, knowledge_items) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge row: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name, create_table_if_not_found=True) current_time = int(time.time()) eval_dict = eval_run.model_dump() eval_dict["created_at"] = current_time eval_dict["updated_at"] = current_time eval_runs.append(eval_dict) self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) original_count = len(eval_runs) eval_runs = [run for run in eval_runs if run.get("run_id") != eval_run_id] if len(eval_runs) < original_count: self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Deleted eval run with ID: {eval_run_id}") else: log_debug(f"No eval run found with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) original_count = len(eval_runs) eval_runs = [run for run in eval_runs if run.get("run_id") not in eval_run_ids] deleted_count = original_count - len(eval_runs) if deleted_count > 0: self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Deleted {deleted_count} eval runs") else: log_debug(f"No eval runs found with IDs: {eval_run_ids}") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) for run_data in eval_runs: if run_data.get("run_id") == eval_run_id: if not deserialize: return run_data return EvalRunRecord.model_validate(run_data) return None except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the JSON file with filtering and pagination.""" try: eval_runs = self._read_json_file(self.eval_table_name) # Apply filters filtered_runs = [] for run_data in eval_runs: if agent_id is not None and run_data.get("agent_id") != agent_id: continue if team_id is not None and run_data.get("team_id") != team_id: continue if workflow_id is not None and run_data.get("workflow_id") != workflow_id: continue if model_id is not None and run_data.get("model_id") != model_id: continue if eval_type is not None and len(eval_type) > 0: if run_data.get("eval_type") not in eval_type: continue if filter_type is not None: if filter_type == EvalFilterType.AGENT and run_data.get("agent_id") is None: continue elif filter_type == EvalFilterType.TEAM and run_data.get("team_id") is None: continue elif filter_type == EvalFilterType.WORKFLOW and run_data.get("workflow_id") is None: continue filtered_runs.append(run_data) total_count = len(filtered_runs) # Apply sorting (default by created_at desc) if sort_by is None: filtered_runs.sort(key=lambda x: x.get("created_at", 0), reverse=True) else: filtered_runs = apply_sorting(filtered_runs, sort_by, sort_order) # Apply pagination if limit is not None: start_idx = 0 if page is not None: start_idx = (page - 1) * limit filtered_runs = filtered_runs[start_idx : start_idx + limit] if not deserialize: return filtered_runs, total_count return [EvalRunRecord.model_validate(run) for run in filtered_runs] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Rename an eval run in the JSON file.""" try: eval_runs = self._read_json_file(self.eval_table_name) for i, run_data in enumerate(eval_runs): if run_data.get("run_id") == eval_run_id: run_data["name"] = name run_data["updated_at"] = int(time.time()) eval_runs[i] = run_data self._write_json_file(self.eval_table_name, eval_runs) log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not deserialize: return run_data return EvalRunRecord.model_validate(run_data) return None except Exception as e: log_error(f"Error renaming eval run {eval_run_id}: {e}") raise e # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from JSON file.""" try: self._write_json_file(self.culture_table_name, []) except Exception as e: log_error(f"Error clearing cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from JSON file.""" try: cultural_knowledge = self._read_json_file(self.culture_table_name) cultural_knowledge = [ck for ck in cultural_knowledge if ck.get("id") != id] self._write_json_file(self.culture_table_name, cultural_knowledge) except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from JSON file.""" try: cultural_knowledge = self._read_json_file(self.culture_table_name) for ck in cultural_knowledge: if ck.get("id") == id: if not deserialize: return ck return deserialize_cultural_knowledge_from_db(ck) return None except Exception as e: log_error(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from JSON file.""" try: cultural_knowledge = self._read_json_file(self.culture_table_name) # Filter filtered = [] for ck in cultural_knowledge: if name and ck.get("name") != name: continue if agent_id and ck.get("agent_id") != agent_id: continue if team_id and ck.get("team_id") != team_id: continue filtered.append(ck) # Sort if sort_by: filtered = apply_sorting(filtered, sort_by, sort_order) total_count = len(filtered) # Paginate if limit and page: start = (page - 1) * limit filtered = filtered[start : start + limit] elif limit: filtered = filtered[:limit] if not deserialize: return filtered, total_count return [deserialize_cultural_knowledge_from_db(ck) for ck in filtered] except Exception as e: log_error(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into JSON file.""" try: if not cultural_knowledge.id: cultural_knowledge.id = str(uuid4()) all_cultural_knowledge = self._read_json_file(self.culture_table_name, create_table_if_not_found=True) # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the item dict with serialized content ck_dict = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } # Remove existing entry all_cultural_knowledge = [ck for ck in all_cultural_knowledge if ck.get("id") != cultural_knowledge.id] # Add new entry all_cultural_knowledge.append(ck_dict) self._write_json_file(self.culture_table_name, all_cultural_knowledge) return self.get_cultural_knowledge(cultural_knowledge.id, deserialize=deserialize) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ try: traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=True) # Check if trace exists existing_idx = None for i, existing in enumerate(traces): if existing.get("trace_id") == trace.trace_id: existing_idx = i break if existing_idx is not None: existing = traces[existing_idx] # workflow (level 3) > team (level 2) > agent (level 1) > child/unknown (level 0) def get_component_level(workflow_id, team_id, agent_id, name): is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 elif workflow_id: return 3 elif team_id: return 2 elif agent_id: return 1 else: return 0 existing_level = get_component_level( existing.get("workflow_id"), existing.get("team_id"), existing.get("agent_id"), existing.get("name", ""), ) new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) should_update_name = new_level > existing_level # Parse existing start_time to calculate correct duration existing_start_time_str = existing.get("start_time") if isinstance(existing_start_time_str, str): existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00")) else: existing_start_time = trace.start_time recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000) # Update existing trace existing["end_time"] = trace.end_time.isoformat() existing["duration_ms"] = recalculated_duration_ms existing["status"] = trace.status if should_update_name: existing["name"] = trace.name # Update context fields only if new value is not None if trace.run_id is not None: existing["run_id"] = trace.run_id if trace.session_id is not None: existing["session_id"] = trace.session_id if trace.user_id is not None: existing["user_id"] = trace.user_id if trace.agent_id is not None: existing["agent_id"] = trace.agent_id if trace.team_id is not None: existing["team_id"] = trace.team_id if trace.workflow_id is not None: existing["workflow_id"] = trace.workflow_id traces[existing_idx] = existing else: # Add new trace trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) traces.append(trace_dict) self._write_json_file(self.trace_table_name, traces) except Exception as e: log_error(f"Error creating trace: {e}") def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. """ try: from agno.tracing.schemas import Trace traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return None # Get spans for calculating total_spans and error_count spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) # Filter traces filtered = [] for t in traces: if trace_id and t.get("trace_id") == trace_id: filtered.append(t) break elif run_id and t.get("run_id") == run_id: filtered.append(t) if not filtered: return None # Sort by start_time desc and get first filtered.sort(key=lambda x: x.get("start_time", ""), reverse=True) trace_data = filtered[0] # Calculate total_spans and error_count trace_spans = [s for s in spans if s.get("trace_id") == trace_data.get("trace_id")] trace_data["total_spans"] = len(trace_spans) trace_data["error_count"] = sum(1 for s in trace_spans if s.get("status_code") == "ERROR") return Trace.from_dict(trace_data) except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return [], 0 # Get spans for calculating total_spans and error_count spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) # Apply filters filtered = [] for t in traces: if run_id and t.get("run_id") != run_id: continue if session_id and t.get("session_id") != session_id: continue if user_id and t.get("user_id") != user_id: continue if agent_id and t.get("agent_id") != agent_id: continue if team_id and t.get("team_id") != team_id: continue if workflow_id and t.get("workflow_id") != workflow_id: continue if status and t.get("status") != status: continue if start_time: trace_start = t.get("start_time", "") if trace_start < start_time.isoformat(): continue if end_time: trace_end = t.get("end_time", "") if trace_end > end_time.isoformat(): continue filtered.append(t) total_count = len(filtered) # Sort by start_time desc filtered.sort(key=lambda x: x.get("start_time", ""), reverse=True) # Apply pagination if limit and page: start_idx = (page - 1) * limit filtered = filtered[start_idx : start_idx + limit] # Add total_spans and error_count to each trace result_traces = [] for t in filtered: trace_spans = [s for s in spans if s.get("trace_id") == t.get("trace_id")] t["total_spans"] = len(trace_spans) t["error_count"] = sum(1 for s in trace_spans if s.get("status_code") == "ERROR") result_traces.append(Trace.from_dict(t)) return result_traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). """ try: traces = self._read_json_file(self.trace_table_name, create_table_if_not_found=False) if not traces: return [], 0 # Group by session_id session_stats: Dict[str, Dict[str, Any]] = {} for t in traces: session_id = t.get("session_id") if not session_id: continue # Apply filters if user_id and t.get("user_id") != user_id: continue if agent_id and t.get("agent_id") != agent_id: continue if team_id and t.get("team_id") != team_id: continue if workflow_id and t.get("workflow_id") != workflow_id: continue created_at = t.get("created_at", "") if start_time and created_at < start_time.isoformat(): continue if end_time and created_at > end_time.isoformat(): continue if session_id not in session_stats: session_stats[session_id] = { "session_id": session_id, "user_id": t.get("user_id"), "agent_id": t.get("agent_id"), "team_id": t.get("team_id"), "workflow_id": t.get("workflow_id"), "total_traces": 0, "first_trace_at": created_at, "last_trace_at": created_at, } session_stats[session_id]["total_traces"] += 1 if created_at < session_stats[session_id]["first_trace_at"]: session_stats[session_id]["first_trace_at"] = created_at if created_at > session_stats[session_id]["last_trace_at"]: session_stats[session_id]["last_trace_at"] = created_at stats_list = list(session_stats.values()) total_count = len(stats_list) # Sort by last_trace_at desc stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True) # Apply pagination if limit and page: start_idx = (page - 1) * limit stats_list = stats_list[start_idx : start_idx + limit] # Convert ISO strings to datetime objects for stat in stats_list: first_at = stat.get("first_trace_at", "") last_at = stat.get("last_trace_at", "") if first_at: stat["first_trace_at"] = datetime.fromisoformat(first_at.replace("Z", "+00:00")) if last_at: stat["last_trace_at"] = datetime.fromisoformat(last_at.replace("Z", "+00:00")) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: spans = self._read_json_file(self.span_table_name, create_table_if_not_found=True) spans.append(span.to_dict()) self._write_json_file(self.span_table_name, spans) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: existing_spans = self._read_json_file(self.span_table_name, create_table_if_not_found=True) for span in spans: existing_spans.append(span.to_dict()) self._write_json_file(self.span_table_name, existing_spans) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) for s in spans: if s.get("span_id") == span_id: return Span.from_dict(s) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span spans = self._read_json_file(self.span_table_name, create_table_if_not_found=False) if not spans: return [] # Apply filters filtered = [] for s in spans: if trace_id and s.get("trace_id") != trace_id: continue if parent_span_id and s.get("parent_span_id") != parent_span_id: continue filtered.append(s) # Apply limit if limit: filtered = filtered[:limit] return [Span.from_dict(s) for s in filtered] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for JsonDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for JsonDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for JsonDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for JsonDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/json/json_db.py", "license": "Apache License 2.0", "lines": 1517, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/json/utils.py
"""Utility functions for the JSON database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.schemas.culture import CulturalKnowledge from agno.db.utils import get_sort_value from agno.utils.log import log_debug def apply_sorting( data: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to the given data list. Args: data: The list of dictionaries to sort sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if sort_by is None or not data: return data # Check if the sort field exists in the first item if sort_by not in data[0]: log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return data try: is_descending = sort_order != "asc" if sort_order else True # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( data, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records except Exception as e: log_debug(f"Error sorting data by '{sort_by}': {e}") return data def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process.isoformat(), "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: sessions: List of session dictionaries dates_to_process (list[date]): The dates to fetch session data for. start_timestamp (int): The starting timestamp for filtering Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/json/utils.py", "license": "Apache License 2.0", "lines": 196, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/mongo/mongo.py
import time from datetime import date, datetime, timedelta, timezone from importlib import metadata from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 try: from pymongo.errors import DuplicateKeyError except ImportError: DuplicateKeyError = Exception # type: ignore[assignment,misc] if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.mongo.utils import ( apply_pagination, apply_sorting, bulk_upsert_metrics, calculate_date_metrics, create_collection_indexes, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.db.utils import deserialize_session_json_fields from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info from agno.utils.string import generate_id try: from pymongo import MongoClient, ReturnDocument from pymongo.collection import Collection from pymongo.database import Database from pymongo.driver_info import DriverInfo from pymongo.errors import OperationFailure except ImportError: raise ImportError("`pymongo` not installed. Please install it using `pip install pymongo`") DRIVER_METADATA = DriverInfo(name="Agno", version=metadata.version("agno")) class MongoDb(BaseDb): def __init__( self, db_client: Optional[MongoClient] = None, db_name: Optional[str] = None, db_url: Optional[str] = None, session_collection: Optional[str] = None, memory_collection: Optional[str] = None, metrics_collection: Optional[str] = None, eval_collection: Optional[str] = None, knowledge_collection: Optional[str] = None, culture_collection: Optional[str] = None, traces_collection: Optional[str] = None, spans_collection: Optional[str] = None, id: Optional[str] = None, ): """ Interface for interacting with a MongoDB database. Args: db_client (Optional[MongoClient]): The MongoDB client to use. db_name (Optional[str]): The name of the database to use. db_url (Optional[str]): The database URL to connect to. session_collection (Optional[str]): Name of the collection to store sessions. memory_collection (Optional[str]): Name of the collection to store memories. metrics_collection (Optional[str]): Name of the collection to store metrics. eval_collection (Optional[str]): Name of the collection to store evaluation runs. knowledge_collection (Optional[str]): Name of the collection to store knowledge documents. culture_collection (Optional[str]): Name of the collection to store cultural knowledge. traces_collection (Optional[str]): Name of the collection to store traces. spans_collection (Optional[str]): Name of the collection to store spans. id (Optional[str]): ID of the database. Raises: ValueError: If neither db_url nor db_client is provided. """ if id is None: base_seed = db_url or str(db_client) db_name_suffix = db_name if db_name is not None else "agno" seed = f"{base_seed}#{db_name_suffix}" id = generate_id(seed) super().__init__( id=id, session_table=session_collection, memory_table=memory_collection, metrics_table=metrics_collection, eval_table=eval_collection, knowledge_table=knowledge_collection, culture_table=culture_collection, traces_table=traces_collection, spans_table=spans_collection, ) _client: Optional[MongoClient] = db_client if _client is None and db_url is not None: _client = MongoClient(db_url, driver=DRIVER_METADATA) if _client is None: raise ValueError("One of db_url or db_client must be provided") # append_metadata was added in PyMongo 4.14.0, but is a valid database name on earlier versions if callable(_client.append_metadata): _client.append_metadata(DRIVER_METADATA) self.db_url: Optional[str] = db_url self.db_client: MongoClient = _client self.db_name: str = db_name if db_name is not None else "agno" self._database: Optional[Database] = None def close(self) -> None: """Close the MongoDB client connection. Should be called during application shutdown to properly release all database connections. """ if self.db_client is not None: self.db_client.close() @property def database(self) -> Database: if self._database is None: self._database = self.db_client[self.db_name] return self._database # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a collection with the given name exists in the MongoDB database. Args: table_name: Name of the collection to check Returns: bool: True if the collection exists in the database, False otherwise """ return table_name in self.database.list_collection_names() def _create_all_tables(self): """Create all configured MongoDB collections if they don't exist.""" collections_to_create = [ ("sessions", self.session_table_name), ("memories", self.memory_table_name), ("metrics", self.metrics_table_name), ("evals", self.eval_table_name), ("knowledge", self.knowledge_table_name), ("culture", self.culture_table_name), ] for collection_type, collection_name in collections_to_create: if collection_name and not self.table_exists(collection_name): self._get_collection(collection_type, create_collection_if_not_found=True) def _get_collection( self, table_type: str, create_collection_if_not_found: Optional[bool] = True ) -> Optional[Collection]: """Get or create a collection based on table type. Args: table_type (str): The type of table to get or create. Returns: Collection: The collection object. """ if table_type == "sessions": if not hasattr(self, "session_collection"): if self.session_table_name is None: raise ValueError("Session collection was not provided on initialization") self.session_collection = self._get_or_create_collection( collection_name=self.session_table_name, collection_type="sessions", create_collection_if_not_found=create_collection_if_not_found, ) return self.session_collection if table_type == "memories": if not hasattr(self, "memory_collection"): if self.memory_table_name is None: raise ValueError("Memory collection was not provided on initialization") self.memory_collection = self._get_or_create_collection( collection_name=self.memory_table_name, collection_type="memories", create_collection_if_not_found=create_collection_if_not_found, ) return self.memory_collection if table_type == "metrics": if not hasattr(self, "metrics_collection"): if self.metrics_table_name is None: raise ValueError("Metrics collection was not provided on initialization") self.metrics_collection = self._get_or_create_collection( collection_name=self.metrics_table_name, collection_type="metrics", create_collection_if_not_found=create_collection_if_not_found, ) return self.metrics_collection if table_type == "evals": if not hasattr(self, "eval_collection"): if self.eval_table_name is None: raise ValueError("Eval collection was not provided on initialization") self.eval_collection = self._get_or_create_collection( collection_name=self.eval_table_name, collection_type="evals", create_collection_if_not_found=create_collection_if_not_found, ) return self.eval_collection if table_type == "knowledge": if not hasattr(self, "knowledge_collection"): if self.knowledge_table_name is None: raise ValueError("Knowledge collection was not provided on initialization") self.knowledge_collection = self._get_or_create_collection( collection_name=self.knowledge_table_name, collection_type="knowledge", create_collection_if_not_found=create_collection_if_not_found, ) return self.knowledge_collection if table_type == "culture": if not hasattr(self, "culture_collection"): if self.culture_table_name is None: raise ValueError("Culture collection was not provided on initialization") self.culture_collection = self._get_or_create_collection( collection_name=self.culture_table_name, collection_type="culture", create_collection_if_not_found=create_collection_if_not_found, ) return self.culture_collection if table_type == "traces": if not hasattr(self, "traces_collection"): if self.trace_table_name is None: raise ValueError("Traces collection was not provided on initialization") self.traces_collection = self._get_or_create_collection( collection_name=self.trace_table_name, collection_type="traces", create_collection_if_not_found=create_collection_if_not_found, ) return self.traces_collection if table_type == "spans": if not hasattr(self, "spans_collection"): if self.span_table_name is None: raise ValueError("Spans collection was not provided on initialization") self.spans_collection = self._get_or_create_collection( collection_name=self.span_table_name, collection_type="spans", create_collection_if_not_found=create_collection_if_not_found, ) return self.spans_collection raise ValueError(f"Unknown table type: {table_type}") def _get_or_create_collection( self, collection_name: str, collection_type: str, create_collection_if_not_found: Optional[bool] = True ) -> Optional[Collection]: """Get or create a collection with proper indexes. Args: collection_name (str): The name of the collection to get or create. collection_type (str): The type of collection to get or create. create_collection_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist. Returns: Optional[Collection]: The collection object. """ try: collection = self.database[collection_name] if not hasattr(self, f"_{collection_name}_initialized"): if not create_collection_if_not_found: return None create_collection_indexes(collection, collection_type) setattr(self, f"_{collection_name}_initialized", True) log_debug(f"Initialized collection '{collection_name}'") else: log_debug(f"Collection '{collection_name}' already initialized") return collection except Exception as e: log_error(f"Error getting collection {collection_name}: {e}") raise def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from the database. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If there is an error deleting the session. """ try: collection = self._get_collection(table_type="sessions") if collection is None: return False query: Dict[str, Any] = {"session_id": session_id} if user_id is not None: query["user_id"] = user_id result = collection.delete_one(query) if result.deleted_count == 0: log_debug(f"No session found to delete with session_id: {session_id}") return False else: log_debug(f"Successfully deleted session with session_id: {session_id}") return True except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from the database. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. """ try: collection = self._get_collection(table_type="sessions") if collection is None: return query: Dict[str, Any] = {"session_id": {"$in": session_ids}} if user_id is not None: query["user_id"] = user_id result = collection.delete_many(query) log_debug(f"Successfully deleted {result.deleted_count} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Read a session from the database. Args: session_id (str): The ID of the session to get. session_type (SessionType): The type of session to get. user_id (Optional[str]): The ID of the user to get the session for. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If there is an error reading the session. """ try: collection = self._get_collection(table_type="sessions") if collection is None: return None query = {"session_id": session_id} if user_id is not None: query["user_id"] = user_id result = collection.find_one(query) if result is None: return None session = deserialize_session_json_fields(result) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading session: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions. Args: session_type (Optional[SessionType]): The type of session to get. user_id (Optional[str]): The ID of the user to get the session for. component_id (Optional[str]): The ID of the component to get the session for. session_name (Optional[str]): The name of the session to filter by. start_timestamp (Optional[int]): The start timestamp to filter sessions by. end_timestamp (Optional[int]): The end timestamp to filter sessions by. limit (Optional[int]): The limit of the sessions to get. page (Optional[int]): The page number to get. sort_by (Optional[str]): The field to sort the sessions by. sort_order (Optional[str]): The order to sort the sessions by. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist. Returns: Union[List[AgentSession], List[TeamSession], List[WorkflowSession], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of Session objects - When deserialize=False: List of session dictionaries and the total count Raises: Exception: If there is an error reading the sessions. """ try: collection = self._get_collection(table_type="sessions") if collection is None: return [] if deserialize else ([], 0) # Filtering query: Dict[str, Any] = {} if user_id is not None: query["user_id"] = user_id if session_type is not None: query["session_type"] = session_type if component_id is not None: if session_type == SessionType.AGENT: query["agent_id"] = component_id elif session_type == SessionType.TEAM: query["team_id"] = component_id elif session_type == SessionType.WORKFLOW: query["workflow_id"] = component_id if start_timestamp is not None: query["created_at"] = {"$gte": start_timestamp} if end_timestamp is not None: if "created_at" in query: query["created_at"]["$lte"] = end_timestamp else: query["created_at"] = {"$lte": end_timestamp} if session_name is not None: query["session_data.session_name"] = {"$regex": session_name, "$options": "i"} # Get total count total_count = collection.count_documents(query) cursor = collection.find(query) # Sorting sort_criteria = apply_sorting({}, sort_by, sort_order) if sort_criteria: cursor = cursor.sort(sort_criteria) # Pagination query_args = apply_pagination({}, limit, page) if query_args.get("skip"): cursor = cursor.skip(query_args["skip"]) if query_args.get("limit"): cursor = cursor.limit(query_args["limit"]) records = list(cursor) if records is None: return [] if deserialize else ([], 0) sessions_raw = [deserialize_session_json_fields(record) for record in records] if not deserialize: return sessions_raw, total_count sessions: List[Union[AgentSession, TeamSession, WorkflowSession]] = [] for record in sessions_raw: if session_type == SessionType.AGENT.value: agent_session = AgentSession.from_dict(record) if agent_session is not None: sessions.append(agent_session) elif session_type == SessionType.TEAM.value: team_session = TeamSession.from_dict(record) if team_session is not None: sessions.append(team_session) elif session_type == SessionType.WORKFLOW.value: workflow_session = WorkflowSession.from_dict(record) if workflow_session is not None: sessions.append(workflow_session) return sessions except Exception as e: log_error(f"Exception reading sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name of the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If there is an error renaming the session. """ try: collection = self._get_collection(table_type="sessions") if collection is None: return None query: Dict[str, Any] = {"session_id": session_id} if user_id is not None: query["user_id"] = user_id try: result = collection.find_one_and_update( query, {"$set": {"session_data.session_name": session_name, "updated_at": int(time.time())}}, return_document=ReturnDocument.AFTER, upsert=False, ) except OperationFailure: # If the update fails because session_data doesn't contain a session_name yet, we initialize session_data result = collection.find_one_and_update( query, {"$set": {"session_data": {"session_name": session_name}, "updated_at": int(time.time())}}, return_document=ReturnDocument.AFTER, upsert=False, ) if not result: return None deserialized_session = deserialize_session_json_fields(result) if not deserialize: return deserialized_session if session_type == SessionType.AGENT.value: return AgentSession.from_dict(deserialized_session) elif session_type == SessionType.TEAM.value: return TeamSession.from_dict(deserialized_session) else: return WorkflowSession.from_dict(deserialized_session) except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """Insert or update a session in the database. Args: session (Session): The session to upsert. Returns: Optional[Session]: The upserted session. Raises: Exception: If there is an error upserting the session. """ try: collection = self._get_collection(table_type="sessions", create_collection_if_not_found=True) if collection is None: return None session_dict = session.to_dict() existing = collection.find_one({"session_id": session_dict.get("session_id")}, {"user_id": 1}) if existing: existing_uid = existing.get("user_id") if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None incoming_uid = session_dict.get("user_id") upsert_filter: Dict[str, Any] = {"session_id": session_dict.get("session_id")} if incoming_uid is not None: upsert_filter["$or"] = [{"user_id": incoming_uid}, {"user_id": None}, {"user_id": {"$exists": False}}] else: upsert_filter["$or"] = [{"user_id": None}, {"user_id": {"$exists": False}}] if isinstance(session, AgentSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } try: result = collection.find_one_and_replace( filter=upsert_filter, replacement=record, upsert=True, return_document=ReturnDocument.AFTER, ) except DuplicateKeyError: return None if not result: return None session = result # type: ignore if not deserialize: return session return AgentSession.from_dict(session) # type: ignore elif isinstance(session, TeamSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } try: result = collection.find_one_and_replace( filter=upsert_filter, replacement=record, upsert=True, return_document=ReturnDocument.AFTER, ) except DuplicateKeyError: return None if not result: return None # MongoDB stores native objects, no deserialization needed for document fields session = result # type: ignore if not deserialize: return session return TeamSession.from_dict(session) # type: ignore else: record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": int(time.time()), } try: result = collection.find_one_and_replace( filter=upsert_filter, replacement=record, upsert=True, return_document=ReturnDocument.AFTER, ) except DuplicateKeyError: return None if not result: return None session = result # type: ignore if not deserialize: return session return WorkflowSession.from_dict(session) # type: ignore except Exception as e: log_error(f"Exception upserting session: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. preserve_updated_at (bool): If True, preserve the updated_at from the session object. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: collection = self._get_collection(table_type="sessions", create_collection_if_not_found=True) if collection is None: log_info("Sessions collection not available, falling back to individual upserts") return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] from pymongo import ReplaceOne operations = [] results: List[Union[Session, Dict[str, Any]]] = [] for session in sessions: if session is None: continue session_dict = session.to_dict() # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) if isinstance(session, AgentSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } elif isinstance(session, TeamSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } elif isinstance(session, WorkflowSession): record = { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } else: continue operations.append( ReplaceOne(filter={"session_id": record["session_id"]}, replacement=record, upsert=True) ) if operations: # Execute bulk write collection.bulk_write(operations) # Fetch the results session_ids = [session.session_id for session in sessions if session and session.session_id] cursor = collection.find({"session_id": {"$in": session_ids}}) for doc in cursor: session_dict = doc if deserialize: session_type = doc.get("session_type") if session_type == SessionType.AGENT.value: deserialized_agent_session = AgentSession.from_dict(session_dict) if deserialized_agent_session is None: continue results.append(deserialized_agent_session) elif session_type == SessionType.TEAM.value: deserialized_team_session = TeamSession.from_dict(session_dict) if deserialized_team_session is None: continue results.append(deserialized_team_session) elif session_type == SessionType.WORKFLOW.value: deserialized_workflow_session = WorkflowSession.from_dict(session_dict) if deserialized_workflow_session is None: continue results.append(deserialized_workflow_session) else: results.append(session_dict) return results except Exception as e: log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user to verify ownership. If provided, only delete if the memory belongs to this user. Returns: bool: True if the memory was deleted, False otherwise. Raises: Exception: If there is an error deleting the memory. """ try: collection = self._get_collection(table_type="memories") if collection is None: return query = {"memory_id": memory_id} if user_id is not None: query["user_id"] = user_id result = collection.delete_one(query) success = result.deleted_count > 0 if success: log_debug(f"Successfully deleted memory id: {memory_id}") else: log_debug(f"No memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user to verify ownership. If provided, only delete memories that belong to this user. Raises: Exception: If there is an error deleting the memories. """ try: collection = self._get_collection(table_type="memories") if collection is None: return query: Dict[str, Any] = {"memory_id": {"$in": memory_ids}} if user_id is not None: query["user_id"] = user_id result = collection.delete_many(query) if result.deleted_count == 0: log_debug(f"No memories found with ids: {memory_ids}") except Exception as e: log_error(f"Error deleting memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the database. Returns: List[str]: The topics. Raises: Exception: If there is an error getting the topics. """ try: collection = self._get_collection(table_type="memories") if collection is None: return [] topics = collection.distinct("topics", {}) return [topic for topic in topics if topic] except Exception as e: log_error(f"Exception reading from collection: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[UserMemory]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user to verify ownership. If provided, only return the memory if it belongs to this user. Returns: Optional[UserMemory]: - When deserialize=True: UserMemory object - When deserialize=False: Memory dictionary Raises: Exception: If there is an error getting the memory. """ try: collection = self._get_collection(table_type="memories") if collection is None: return None query = {"memory_id": memory_id} if user_id is not None: query["user_id"] = user_id result = collection.find_one(query) if result is None or not deserialize: return result # Remove MongoDB's _id field before creating UserMemory object result_filtered = {k: v for k, v in result.items() if k != "_id"} return UserMemory.from_dict(result_filtered) except Exception as e: log_error(f"Exception reading from collection: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to get the memories for. agent_id (Optional[str]): The ID of the agent to get the memories for. team_id (Optional[str]): The ID of the team to get the memories for. topics (Optional[List[str]]): The topics to filter the memories by. search_content (Optional[str]): The content to filter the memories by. limit (Optional[int]): The limit of the memories to get. page (Optional[int]): The page number to get. sort_by (Optional[str]): The field to sort the memories by. sort_order (Optional[str]): The order to sort the memories by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. create_table_if_not_found: Whether to create the collection if it doesn't exist. Returns: Tuple[List[Dict[str, Any]], int]: A tuple containing the memories and the total count. Raises: Exception: If there is an error getting the memories. """ try: collection = self._get_collection(table_type="memories") if collection is None: return [] if deserialize else ([], 0) query: Dict[str, Any] = {} if user_id is not None: query["user_id"] = user_id if agent_id is not None: query["agent_id"] = agent_id if team_id is not None: query["team_id"] = team_id if topics is not None: query["topics"] = {"$in": topics} if search_content is not None: query["memory"] = {"$regex": search_content, "$options": "i"} # Get total count total_count = collection.count_documents(query) # Apply sorting sort_criteria = apply_sorting({}, sort_by, sort_order) # Apply pagination query_args = apply_pagination({}, limit, page) cursor = collection.find(query) if sort_criteria: cursor = cursor.sort(sort_criteria) if query_args.get("skip"): cursor = cursor.skip(query_args["skip"]) if query_args.get("limit"): cursor = cursor.limit(query_args["limit"]) records = list(cursor) if not deserialize: return records, total_count # Remove MongoDB's _id field before creating UserMemory objects return [UserMemory.from_dict({k: v for k, v in record.items() if k != "_id"}) for record in records] except Exception as e: log_error(f"Exception reading from collection: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The limit of the memories to get. page (Optional[int]): The page number to get. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A tuple containing the memories stats and the total count. Raises: Exception: If there is an error getting the memories stats. """ try: collection = self._get_collection(table_type="memories") if collection is None: return [], 0 match_stage: Dict[str, Any] = {"user_id": {"$ne": None}} if user_id is not None: match_stage["user_id"] = user_id pipeline: List[Dict[str, Any]] = [ {"$match": match_stage}, { "$group": { "_id": "$user_id", "total_memories": {"$sum": 1}, "last_memory_updated_at": {"$max": "$updated_at"}, } }, {"$sort": {"last_memory_updated_at": -1}}, ] # Get total count count_pipeline = pipeline + [{"$count": "total"}] count_result = list(collection.aggregate(count_pipeline)) # type: ignore total_count = count_result[0]["total"] if count_result else 0 # Apply pagination if limit is not None: if page is not None: pipeline.append({"$skip": (page - 1) * limit}) pipeline.append({"$limit": limit}) results = list(collection.aggregate(pipeline)) # type: ignore formatted_results = [ { "user_id": result["_id"], "total_memories": result["total_memories"], "last_memory_updated_at": result["last_memory_updated_at"], } for result in results ] return formatted_results, total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: Memory dictionary Raises: Exception: If there is an error upserting the memory. """ try: collection = self._get_collection(table_type="memories", create_collection_if_not_found=True) if collection is None: return None if memory.memory_id is None: memory.memory_id = str(uuid4()) update_doc = { "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "memory_id": memory.memory_id, "memory": memory.memory, "topics": memory.topics, "updated_at": int(time.time()), } result = collection.replace_one({"memory_id": memory.memory_id}, update_doc, upsert=True) if result.upserted_id: update_doc["_id"] = result.upserted_id if not deserialize: return update_doc # Remove MongoDB's _id field before creating UserMemory object update_doc_filtered = {k: v for k, v in update_doc.items() if k != "_id"} return UserMemory.from_dict(update_doc_filtered) except Exception as e: log_error(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: collection = self._get_collection(table_type="memories", create_collection_if_not_found=True) if collection is None: log_info("Memories collection not available, falling back to individual upserts") return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] from pymongo import ReplaceOne operations = [] results: List[Union[UserMemory, Dict[str, Any]]] = [] current_time = int(time.time()) for memory in memories: if memory is None: continue if memory.memory_id is None: memory.memory_id = str(uuid4()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = memory.updated_at if preserve_updated_at else current_time record = { "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "memory_id": memory.memory_id, "memory": memory.memory, "input": memory.input, "feedback": memory.feedback, "topics": memory.topics, "created_at": memory.created_at, "updated_at": updated_at, } operations.append(ReplaceOne(filter={"memory_id": memory.memory_id}, replacement=record, upsert=True)) if operations: # Execute bulk write collection.bulk_write(operations) # Fetch the results memory_ids = [memory.memory_id for memory in memories if memory and memory.memory_id] cursor = collection.find({"memory_id": {"$in": memory_ids}}) for doc in cursor: if deserialize: # Remove MongoDB's _id field before creating UserMemory object doc_filtered = {k: v for k, v in doc.items() if k != "_id"} results.append(UserMemory.from_dict(doc_filtered)) else: results.append(doc) return results except Exception as e: log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: collection = self._get_collection(table_type="memories") if collection is None: return collection.delete_many({}) except Exception as e: log_error(f"Exception deleting all memories: {e}") raise e # -- Cultural Knowledge methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: collection = self._get_collection(table_type="culture") if collection is None: return collection.delete_many({}) except Exception as e: log_error(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: collection = self._get_collection(table_type="culture") if collection is None: return collection.delete_one({"id": id}) log_debug(f"Deleted cultural knowledge with ID: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to retrieve. deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise. Raises: Exception: If an error occurs during retrieval. """ try: collection = self._get_collection(table_type="culture") if collection is None: return None result = collection.find_one({"id": id}) if result is None: return None # Remove MongoDB's _id field result_filtered = {k: v for k, v in result.items() if k != "_id"} if not deserialize: return result_filtered return deserialize_cultural_knowledge_from_db(result_filtered) except Exception as e: log_error(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, agent_id: Optional[str] = None, team_id: Optional[str] = None, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge with filtering and pagination. Args: agent_id (Optional[str]): Filter by agent ID. team_id (Optional[str]): Filter by team ID. name (Optional[str]): Filter by name (case-insensitive partial match). limit (Optional[int]): Maximum number of results to return. page (Optional[int]): Page number for pagination. sort_by (Optional[str]): Field to sort by. sort_order (Optional[str]): Sort order ('asc' or 'desc'). deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: Tuple with list of dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: collection = self._get_collection(table_type="culture") if collection is None: if not deserialize: return [], 0 return [] # Build query query: Dict[str, Any] = {} if agent_id is not None: query["agent_id"] = agent_id if team_id is not None: query["team_id"] = team_id if name is not None: query["name"] = {"$regex": name, "$options": "i"} # Get total count for pagination total_count = collection.count_documents(query) # Apply sorting sort_criteria = apply_sorting({}, sort_by, sort_order) # Apply pagination query_args = apply_pagination({}, limit, page) cursor = collection.find(query) if sort_criteria: cursor = cursor.sort(sort_criteria) if query_args.get("skip"): cursor = cursor.skip(query_args["skip"]) if query_args.get("limit"): cursor = cursor.limit(query_args["limit"]) # Remove MongoDB's _id field from all results results_filtered = [{k: v for k, v in item.items() if k != "_id"} for item in cursor] if not deserialize: return results_filtered, total_count return [deserialize_cultural_knowledge_from_db(item) for item in results_filtered] except Exception as e: log_error(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert cultural knowledge in MongoDB. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge. Raises: Exception: If an error occurs during upsert. """ try: collection = self._get_collection(table_type="culture", create_collection_if_not_found=True) if collection is None: return None # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) # Create the document with serialized content update_doc = { "id": cultural_knowledge.id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } result = collection.replace_one({"id": cultural_knowledge.id}, update_doc, upsert=True) if result.upserted_id: update_doc["_id"] = result.upserted_id # Remove MongoDB's _id field doc_filtered = {k: v for k, v in update_doc.items() if k != "_id"} if not deserialize: return doc_filtered return deserialize_cultural_knowledge_from_db(doc_filtered) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions of all types for metrics calculation.""" try: collection = self._get_collection(table_type="sessions") if collection is None: return [] query = {} if start_timestamp is not None: query["created_at"] = {"$gte": start_timestamp} if end_timestamp is not None: if "created_at" in query: query["created_at"]["$lte"] = end_timestamp else: query["created_at"] = {"$lte": end_timestamp} projection = { "user_id": 1, "session_data": 1, "runs": 1, "created_at": 1, "session_type": 1, } results = list(collection.find(query, projection)) return results except Exception as e: log_error(f"Exception reading from sessions collection: {e}") return [] def _get_metrics_calculation_starting_date(self, collection: Collection) -> Optional[date]: """Get the first date for which metrics calculation is needed.""" try: result = collection.find_one({}, sort=[("date", -1)], limit=1) if result is not None: result_date = datetime.strptime(result["date"], "%Y-%m-%d").date() if result.get("completed"): return result_date + timedelta(days=1) else: return result_date # No metrics records. Return the date of the first recorded session. first_session_result = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) first_session_date = first_session_result[0][0]["created_at"] if first_session_result[0] else None # type: ignore if first_session_date is None: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() except Exception as e: log_error(f"Exception getting metrics calculation starting date: {e}") return None def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics.""" try: collection = self._get_collection(table_type="metrics", create_collection_if_not_found=True) if collection is None: return None starting_date = self._get_metrics_calculation_starting_date(collection) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int( datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp() ) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()) .replace(tzinfo=timezone.utc) .timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: results = bulk_upsert_metrics(collection, metrics_records) return results except Exception as e: log_error(f"Error calculating metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range.""" try: collection = self._get_collection(table_type="metrics") if collection is None: return [], None query = {} if starting_date: query["date"] = {"$gte": starting_date.isoformat()} if ending_date: if "date" in query: query["date"]["$lte"] = ending_date.isoformat() else: query["date"] = {"$lte": ending_date.isoformat()} records = list(collection.find(query)) if not records: return [], None # Get the latest updated_at latest_updated_at = max(record.get("updated_at", 0) for record in records) return records, latest_updated_at except Exception as e: log_error(f"Error getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ try: collection = self._get_collection(table_type="knowledge") if collection is None: return collection.delete_one({"id": id}) log_debug(f"Deleted knowledge content with id '{id}'") except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: collection = self._get_collection(table_type="knowledge") if collection is None: return None result = collection.find_one({"id": id}) if result is None: return None return KnowledgeRow.model_validate(result) except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ try: collection = self._get_collection(table_type="knowledge") if collection is None: return [], 0 query: Dict[str, Any] = {} # Apply linked_to filter if provided if linked_to is not None: query["linked_to"] = linked_to # Get total count total_count = collection.count_documents(query) # Apply sorting sort_criteria = apply_sorting({}, sort_by, sort_order) # Apply pagination query_args = apply_pagination({}, limit, page) cursor = collection.find(query) if sort_criteria: cursor = cursor.sort(sort_criteria) if query_args.get("skip"): cursor = cursor.skip(query_args["skip"]) if query_args.get("limit"): cursor = cursor.limit(query_args["limit"]) records = list(cursor) knowledge_rows = [KnowledgeRow.model_validate(record) for record in records] return knowledge_rows, total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. Raises: Exception: If an error occurs during upsert. """ try: collection = self._get_collection(table_type="knowledge", create_collection_if_not_found=True) if collection is None: return None update_doc = knowledge_row.model_dump() collection.replace_one({"id": knowledge_row.id}, update_doc, upsert=True) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge content: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database.""" try: collection = self._get_collection(table_type="evals", create_collection_if_not_found=True) if collection is None: return None current_time = int(time.time()) eval_dict = eval_run.model_dump() eval_dict["created_at"] = current_time eval_dict["updated_at"] = current_time collection.insert_one(eval_dict) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database.""" try: collection = self._get_collection(table_type="evals") if collection is None: return result = collection.delete_one({"run_id": eval_run_id}) if result.deleted_count == 0: log_debug(f"No eval run found with ID: {eval_run_id}") else: log_debug(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database.""" try: collection = self._get_collection(table_type="evals") if collection is None: return result = collection.delete_many({"run_id": {"$in": eval_run_ids}}) if result.deleted_count == 0: log_debug(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {result.deleted_count} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run_raw(self, eval_run_id: str) -> Optional[Dict[str, Any]]: """Get an eval run from the database as a raw dictionary.""" try: collection = self._get_collection(table_type="evals") if collection is None: return None result = collection.find_one({"run_id": eval_run_id}) return result except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_run(self, eval_run_id: str, deserialize: Optional[bool] = True) -> Optional[EvalRunRecord]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[EvalRunRecord]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If there is an error getting the eval run. """ try: collection = self._get_collection(table_type="evals") if collection is None: return None eval_run_raw = collection.find_one({"run_id": eval_run_id}) if not eval_run_raw: return None if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number to return. sort_by (Optional[str]): The field to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type of eval to filter by. filter_type (Optional[EvalFilterType]): The type of filter to apply. deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the collection if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of eval run dictionaries and the total count Raises: Exception: If there is an error getting the eval runs. """ try: collection = self._get_collection(table_type="evals") if collection is None: return [] if deserialize else ([], 0) query: Dict[str, Any] = {} if agent_id is not None: query["agent_id"] = agent_id if team_id is not None: query["team_id"] = team_id if workflow_id is not None: query["workflow_id"] = workflow_id if model_id is not None: query["model_id"] = model_id if eval_type is not None and len(eval_type) > 0: query["eval_type"] = {"$in": eval_type} if filter_type is not None: if filter_type == EvalFilterType.AGENT: query["agent_id"] = {"$ne": None} elif filter_type == EvalFilterType.TEAM: query["team_id"] = {"$ne": None} elif filter_type == EvalFilterType.WORKFLOW: query["workflow_id"] = {"$ne": None} # Get total count total_count = collection.count_documents(query) # Apply default sorting by created_at desc if no sort parameters provided if sort_by is None: sort_criteria = [("created_at", -1)] else: sort_criteria = apply_sorting({}, sort_by, sort_order) # Apply pagination query_args = apply_pagination({}, limit, page) cursor = collection.find(query) if sort_criteria: cursor = cursor.sort(sort_criteria) if query_args.get("skip"): cursor = cursor.skip(query_args["skip"]) if query_args.get("limit"): cursor = cursor.limit(query_args["limit"]) records = list(cursor) if not records: return [] if deserialize else ([], 0) if not deserialize: return records, total_count return [EvalRunRecord.model_validate(row) for row in records] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Update the name of an eval run in the database. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If there is an error updating the eval run. """ try: collection = self._get_collection(table_type="evals") if collection is None: return None result = collection.find_one_and_update( {"run_id": eval_run_id}, {"$set": {"name": name, "updated_at": int(time.time())}} ) log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not result or not deserialize: return result return EvalRunRecord.model_validate(result) except Exception as e: log_error(f"Error updating eval run name {eval_run_id}: {e}") raise e def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str): """Migrate all content in the given collection to the right v2 collection""" from typing import List, Sequence, Union from agno.db.migrations.v1_to_v2 import ( get_all_table_content, parse_agent_sessions, parse_memories, parse_team_sessions, parse_workflow_sessions, ) # Get all content from the old collection old_content: list[dict[str, Any]] = get_all_table_content( db=self, db_schema=v1_db_schema, table_name=v1_table_name, ) if not old_content: log_info(f"No content to migrate from collection {v1_table_name}") return # Parse the content into the new format memories: List[UserMemory] = [] sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = [] if v1_table_type == "agent_sessions": sessions = parse_agent_sessions(old_content) elif v1_table_type == "team_sessions": sessions = parse_team_sessions(old_content) elif v1_table_type == "workflow_sessions": sessions = parse_workflow_sessions(old_content) elif v1_table_type == "memories": memories = parse_memories(old_content) else: raise ValueError(f"Invalid table type: {v1_table_type}") # Insert the new content into the new collection if v1_table_type == "agent_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Agent sessions to collection: {self.session_table_name}") elif v1_table_type == "team_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Team sessions to collection: {self.session_table_name}") elif v1_table_type == "workflow_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Workflow sessions to collection: {self.session_table_name}") elif v1_table_type == "memories": for memory in memories: self.upsert_user_memory(memory) log_info(f"Migrated {len(memories)} memories to collection: {self.memory_table_name}") # --- Traces --- def _get_component_level( self, workflow_id: Optional[str], team_id: Optional[str], agent_id: Optional[str], name: str ) -> int: """Get the component level for a trace based on its context. Component levels (higher = more important): - 3: Workflow root (.run or .arun with workflow_id) - 2: Team root (.run or .arun with team_id) - 1: Agent root (.run or .arun with agent_id) - 0: Child span (not a root) Args: workflow_id: The workflow ID of the trace. team_id: The team ID of the trace. agent_id: The agent ID of the trace. name: The name of the trace. Returns: int: The component level (0-3). """ # Check if name indicates a root span is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 # Child span (not a root) elif workflow_id: return 3 # Workflow root elif team_id: return 2 # Team root elif agent_id: return 1 # Agent root else: return 0 # Unknown def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Uses MongoDB's update_one with upsert=True and aggregation pipeline to handle concurrent inserts atomically and avoid race conditions. Args: trace: The Trace object to store (one per trace_id). """ try: collection = self._get_collection(table_type="traces", create_collection_if_not_found=True) if collection is None: return trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) # Calculate the component level for the new trace new_level = self._get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) # Use MongoDB aggregation pipeline update for atomic upsert # This allows conditional logic within a single atomic operation pipeline: List[Dict[str, Any]] = [ { "$set": { # Always update these fields "status": trace.status, "created_at": {"$ifNull": ["$created_at", trace_dict.get("created_at")]}, # Use $min for start_time (keep earliest) "start_time": { "$cond": { "if": {"$eq": [{"$type": "$start_time"}, "missing"]}, "then": trace_dict.get("start_time"), "else": {"$min": ["$start_time", trace_dict.get("start_time")]}, } }, # Use $max for end_time (keep latest) "end_time": { "$cond": { "if": {"$eq": [{"$type": "$end_time"}, "missing"]}, "then": trace_dict.get("end_time"), "else": {"$max": ["$end_time", trace_dict.get("end_time")]}, } }, # Preserve existing non-null context values using $ifNull "run_id": {"$ifNull": [trace.run_id, "$run_id"]}, "session_id": {"$ifNull": [trace.session_id, "$session_id"]}, "user_id": {"$ifNull": [trace.user_id, "$user_id"]}, "agent_id": {"$ifNull": [trace.agent_id, "$agent_id"]}, "team_id": {"$ifNull": [trace.team_id, "$team_id"]}, "workflow_id": {"$ifNull": [trace.workflow_id, "$workflow_id"]}, } }, { "$set": { # Calculate duration_ms from the (potentially updated) start_time and end_time # MongoDB stores dates as strings in ISO format, so we need to parse them "duration_ms": { "$cond": { "if": { "$and": [ {"$ne": [{"$type": "$start_time"}, "missing"]}, {"$ne": [{"$type": "$end_time"}, "missing"]}, ] }, "then": { "$subtract": [ {"$toLong": {"$toDate": "$end_time"}}, {"$toLong": {"$toDate": "$start_time"}}, ] }, "else": trace_dict.get("duration_ms", 0), } }, # Update name based on component level priority # Only update if new trace is from a higher-level component "name": { "$cond": { "if": {"$eq": [{"$type": "$name"}, "missing"]}, "then": trace.name, "else": { "$cond": { "if": { "$gt": [ new_level, { "$switch": { "branches": [ # Check if existing name is a root span { "case": { "$not": { "$or": [ { "$regexMatch": { "input": {"$ifNull": ["$name", ""]}, "regex": "\\.run", } }, { "$regexMatch": { "input": {"$ifNull": ["$name", ""]}, "regex": "\\.arun", } }, ] } }, "then": 0, }, # Workflow root (level 3) { "case": {"$ne": ["$workflow_id", None]}, "then": 3, }, # Team root (level 2) { "case": {"$ne": ["$team_id", None]}, "then": 2, }, # Agent root (level 1) { "case": {"$ne": ["$agent_id", None]}, "then": 1, }, ], "default": 0, } }, ] }, "then": trace.name, "else": "$name", } }, } }, } }, ] # Perform atomic upsert using aggregation pipeline collection.update_one( {"trace_id": trace.trace_id}, pipeline, upsert=True, ) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace as TraceSchema collection = self._get_collection(table_type="traces") if collection is None: return None # Get spans collection for aggregation spans_collection = self._get_collection(table_type="spans") query: Dict[str, Any] = {} if trace_id: query["trace_id"] = trace_id elif run_id: query["run_id"] = run_id else: log_debug("get_trace called without any filter parameters") return None # Find trace with sorting by most recent result = collection.find_one(query, sort=[("start_time", -1)]) if result: # Calculate total_spans and error_count from spans collection total_spans = 0 error_count = 0 if spans_collection is not None: total_spans = spans_collection.count_documents({"trace_id": result["trace_id"]}) error_count = spans_collection.count_documents( {"trace_id": result["trace_id"], "status_code": "ERROR"} ) result["total_spans"] = total_spans result["error_count"] = error_count # Remove MongoDB's _id field result.pop("_id", None) return TraceSchema.from_dict(result) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace as TraceSchema collection = self._get_collection(table_type="traces") if collection is None: log_debug("Traces collection not found") return [], 0 # Get spans collection for aggregation spans_collection = self._get_collection(table_type="spans") # Build query query: Dict[str, Any] = {} if run_id: query["run_id"] = run_id if session_id: query["session_id"] = session_id if user_id is not None: query["user_id"] = user_id if agent_id: query["agent_id"] = agent_id if team_id: query["team_id"] = team_id if workflow_id: query["workflow_id"] = workflow_id if status: query["status"] = status if start_time: query["start_time"] = {"$gte": start_time.isoformat()} if end_time: if "end_time" in query: query["end_time"]["$lte"] = end_time.isoformat() else: query["end_time"] = {"$lte": end_time.isoformat()} # Get total count total_count = collection.count_documents(query) # Apply pagination skip = ((page or 1) - 1) * (limit or 20) cursor = collection.find(query).sort("start_time", -1).skip(skip).limit(limit or 20) results = list(cursor) traces = [] for row in results: # Calculate total_spans and error_count from spans collection total_spans = 0 error_count = 0 if spans_collection is not None: total_spans = spans_collection.count_documents({"trace_id": row["trace_id"]}) error_count = spans_collection.count_documents( {"trace_id": row["trace_id"], "status_code": "ERROR"} ) row["total_spans"] = total_spans row["error_count"] = error_count # Remove MongoDB's _id field row.pop("_id", None) traces.append(TraceSchema.from_dict(row)) return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, workflow_id, first_trace_at, last_trace_at. """ try: collection = self._get_collection(table_type="traces") if collection is None: log_debug("Traces collection not found") return [], 0 # Build match stage match_stage: Dict[str, Any] = {"session_id": {"$ne": None}} if user_id is not None: match_stage["user_id"] = user_id if agent_id: match_stage["agent_id"] = agent_id if team_id: match_stage["team_id"] = team_id if workflow_id: match_stage["workflow_id"] = workflow_id if start_time: match_stage["created_at"] = {"$gte": start_time.isoformat()} if end_time: if "created_at" in match_stage: match_stage["created_at"]["$lte"] = end_time.isoformat() else: match_stage["created_at"] = {"$lte": end_time.isoformat()} # Build aggregation pipeline pipeline: List[Dict[str, Any]] = [ {"$match": match_stage}, { "$group": { "_id": "$session_id", "user_id": {"$first": "$user_id"}, "agent_id": {"$first": "$agent_id"}, "team_id": {"$first": "$team_id"}, "workflow_id": {"$first": "$workflow_id"}, "total_traces": {"$sum": 1}, "first_trace_at": {"$min": "$created_at"}, "last_trace_at": {"$max": "$created_at"}, } }, {"$sort": {"last_trace_at": -1}}, ] # Get total count count_pipeline = pipeline + [{"$count": "total"}] count_result = list(collection.aggregate(count_pipeline)) total_count = count_result[0]["total"] if count_result else 0 # Apply pagination skip = ((page or 1) - 1) * (limit or 20) pipeline.append({"$skip": skip}) pipeline.append({"$limit": limit or 20}) results = list(collection.aggregate(pipeline)) # Convert to list of dicts with datetime objects stats_list = [] for row in results: # Convert ISO strings to datetime objects first_trace_at_str = row["first_trace_at"] last_trace_at_str = row["last_trace_at"] # Parse ISO format strings to datetime objects first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) stats_list.append( { "session_id": row["_id"], "user_id": row["user_id"], "agent_id": row["agent_id"], "team_id": row["team_id"], "workflow_id": row["workflow_id"], "total_traces": row["total_traces"], "first_trace_at": first_trace_at, "last_trace_at": last_trace_at, } ) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: collection = self._get_collection(table_type="spans", create_collection_if_not_found=True) if collection is None: return collection.insert_one(span.to_dict()) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: collection = self._get_collection(table_type="spans", create_collection_if_not_found=True) if collection is None: return span_dicts = [span.to_dict() for span in spans] collection.insert_many(span_dicts) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span as SpanSchema collection = self._get_collection(table_type="spans") if collection is None: return None result = collection.find_one({"span_id": span_id}) if result: # Remove MongoDB's _id field result.pop("_id", None) return SpanSchema.from_dict(result) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span as SpanSchema collection = self._get_collection(table_type="spans") if collection is None: return [] # Build query query: Dict[str, Any] = {} if trace_id: query["trace_id"] = trace_id if parent_span_id: query["parent_span_id"] = parent_span_id cursor = collection.find(query).limit(limit or 1000) results = list(cursor) spans = [] for row in results: # Remove MongoDB's _id field row.pop("_id", None) spans.append(SpanSchema.from_dict(row)) return spans except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for MongoDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for MongoDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for MongoDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for MongoDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mongo/mongo.py", "license": "Apache License 2.0", "lines": 2253, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/mongo/schemas.py
"""MongoDB collection schemas and related utilities""" from typing import Any, Dict, List SESSION_COLLECTION_SCHEMA = [ {"key": "session_id", "unique": True}, {"key": "user_id"}, {"key": "session_type"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "created_at"}, {"key": "updated_at"}, ] MEMORY_COLLECTION_SCHEMA = [ {"key": "memory_id", "unique": True}, {"key": "user_id"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "topics"}, {"key": "input"}, {"key": "feedback"}, {"key": "created_at"}, {"key": "updated_at"}, ] EVAL_COLLECTION_SCHEMA = [ {"key": "run_id", "unique": True}, {"key": "eval_type"}, {"key": "eval_input"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "model_id"}, {"key": "created_at"}, {"key": "updated_at"}, ] KNOWLEDGE_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "name"}, {"key": "description"}, {"key": "type"}, {"key": "status"}, {"key": "status_message"}, {"key": "metadata"}, {"key": "size"}, {"key": "linked_to"}, {"key": "access_count"}, {"key": "created_at"}, {"key": "updated_at"}, {"key": "external_id"}, ] METRICS_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "date"}, {"key": "aggregation_period"}, {"key": "created_at"}, {"key": "updated_at"}, {"key": [("date", 1), ("aggregation_period", 1)], "unique": True}, ] CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA = [ {"key": "id", "unique": True}, {"key": "name"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "created_at"}, {"key": "updated_at"}, ] TRACE_COLLECTION_SCHEMA = [ {"key": "trace_id", "unique": True}, {"key": "name"}, {"key": "status"}, {"key": "run_id"}, {"key": "session_id"}, {"key": "user_id"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "start_time"}, {"key": "end_time"}, {"key": "created_at"}, ] SPAN_COLLECTION_SCHEMA = [ {"key": "span_id", "unique": True}, {"key": "trace_id"}, {"key": "parent_span_id"}, {"key": "name"}, {"key": "span_kind"}, {"key": "status_code"}, {"key": "start_time"}, {"key": "end_time"}, {"key": "created_at"}, ] LEARNINGS_COLLECTION_SCHEMA = [ {"key": "learning_id", "unique": True}, {"key": "learning_type"}, {"key": "namespace"}, {"key": "user_id"}, {"key": "agent_id"}, {"key": "team_id"}, {"key": "workflow_id"}, {"key": "session_id"}, {"key": "entity_id"}, {"key": "entity_type"}, {"key": "created_at"}, {"key": "updated_at"}, ] def get_collection_indexes(collection_type: str) -> List[Dict[str, Any]]: """Get the index definitions for a specific collection type.""" index_definitions = { "sessions": SESSION_COLLECTION_SCHEMA, "memories": MEMORY_COLLECTION_SCHEMA, "metrics": METRICS_COLLECTION_SCHEMA, "evals": EVAL_COLLECTION_SCHEMA, "knowledge": KNOWLEDGE_COLLECTION_SCHEMA, "culture": CULTURAL_KNOWLEDGE_COLLECTION_SCHEMA, "traces": TRACE_COLLECTION_SCHEMA, "spans": SPAN_COLLECTION_SCHEMA, "learnings": LEARNINGS_COLLECTION_SCHEMA, } indexes = index_definitions.get(collection_type) if not indexes: raise ValueError(f"Unknown collection type: {collection_type}") return indexes # type: ignore[return-value]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mongo/schemas.py", "license": "Apache License 2.0", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/mongo/utils.py
"""Utility functions for the MongoDB database class.""" import json import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.mongo.schemas import get_collection_indexes from agno.db.schemas.culture import CulturalKnowledge from agno.utils.log import log_error, log_warning try: from pymongo.collection import Collection except ImportError: raise ImportError("`pymongo` not installed. Please install it using `pip install pymongo`") # -- DB util methods -- def create_collection_indexes(collection: Collection, collection_type: str) -> None: """Create all required indexes for a collection""" try: indexes = get_collection_indexes(collection_type) for index_spec in indexes: key = index_spec["key"] unique = index_spec.get("unique", False) if isinstance(key, list): collection.create_index(key, unique=unique) else: collection.create_index([(key, 1)], unique=unique) except Exception as e: log_warning(f"Error creating indexes for {collection_type} collection: {e}") async def create_collection_indexes_async(collection: Any, collection_type: str) -> None: """Create all required indexes for a collection (async version for Motor)""" try: indexes = get_collection_indexes(collection_type) for index_spec in indexes: key = index_spec["key"] unique = index_spec.get("unique", False) if isinstance(key, list): await collection.create_index(key, unique=unique) else: await collection.create_index([(key, 1)], unique=unique) except Exception as e: log_warning(f"Error creating indexes for {collection_type} collection: {e}") def apply_sorting( query_args: Dict[str, Any], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[tuple]: """Apply sorting to MongoDB query.""" if sort_by is None: return [] sort_direction = 1 if sort_order == "asc" else -1 return [(sort_by, sort_direction)] def apply_pagination( query_args: Dict[str, Any], limit: Optional[int] = None, page: Optional[int] = None ) -> Dict[str, Any]: """Apply pagination to MongoDB query.""" if limit is not None: query_args["limit"] = limit if page is not None: query_args["skip"] = (page - 1) * limit return query_args # -- Metrics util methods -- def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date.""" metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) runs = session.get("runs", []) metrics[runs_count_key] += len(runs) if runs := session.get("runs", []): if isinstance(runs, str): runs = json.loads(runs) for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_data = session.get("session_data", {}) if isinstance(session_data, str): session_data = json.loads(session_data) session_metrics = session_data.get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types.""" if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for.""" today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] def bulk_upsert_metrics(collection: Collection, metrics_records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Bulk upsert metrics into the database. Args: collection (Collection): The collection to upsert the metrics into. metrics_records (List[Dict[str, Any]]): The list of metrics records to upsert. Returns: The list of upserted metrics records. """ if not metrics_records: return [] results = [] for record in metrics_records: record["date"] = record["date"].isoformat() if isinstance(record["date"], date) else record["date"] try: collection.replace_one( { "date": record["date"], "aggregation_period": record["aggregation_period"], }, record, upsert=True, ) results.append(record) except Exception as e: log_error(f"Error upserting metrics record: {e}") continue return results # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content column. MongoDB stores as BSON which natively supports nested documents. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mongo/utils.py", "license": "Apache License 2.0", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/mysql/mysql.py
import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.migrations.manager import MigrationManager from agno.db.mysql.schemas import get_table_schema_definition from agno.db.mysql.utils import ( apply_sorting, bulk_upsert_metrics, calculate_date_metrics, create_schema, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, is_table_available, is_valid_table, serialize_cultural_knowledge_for_db, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id try: from sqlalchemy import TEXT, ForeignKey, Index, UniqueConstraint, and_, cast, func, update from sqlalchemy.dialects import mysql from sqlalchemy.engine import Engine, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.schema import Column, MetaData, Table from sqlalchemy.sql.expression import select, text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") class MySQLDb(BaseDb): def __init__( self, id: Optional[str] = None, db_engine: Optional[Engine] = None, db_schema: Optional[str] = None, db_url: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, versions_table: Optional[str] = None, create_schema: bool = True, ): """ Interface for interacting with a MySQL database. The following order is used to determine the database connection: 1. Use the db_engine if provided 2. Use the db_url 3. Raise an error if neither is provided Args: id (Optional[str]): ID of the database. db_url (Optional[str]): The database URL to connect to. db_engine (Optional[Engine]): The SQLAlchemy database engine to use. db_schema (Optional[str]): The database schema to use. session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions. culture_table (Optional[str]): Name of the table to store cultural knowledge. memory_table (Optional[str]): Name of the table to store memories. metrics_table (Optional[str]): Name of the table to store metrics. eval_table (Optional[str]): Name of the table to store evaluation runs data. knowledge_table (Optional[str]): Name of the table to store knowledge content. traces_table (Optional[str]): Name of the table to store run traces. spans_table (Optional[str]): Name of the table to store span events. versions_table (Optional[str]): Name of the table to store schema versions. create_schema (bool): Whether to automatically create the database schema if it doesn't exist. Set to False if schema is managed externally (e.g., via migrations). Defaults to True. Raises: ValueError: If neither db_url nor db_engine is provided. ValueError: If none of the tables are provided. """ if id is None: base_seed = db_url or str(db_engine.url) # type: ignore schema_suffix = db_schema if db_schema is not None else "ai" seed = f"{base_seed}#{schema_suffix}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, culture_table=culture_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, traces_table=traces_table, spans_table=spans_table, versions_table=versions_table, ) _engine: Optional[Engine] = db_engine if _engine is None and db_url is not None: _engine = create_engine(db_url) if _engine is None: raise ValueError("One of db_url or db_engine must be provided") self.db_url: Optional[str] = db_url self.db_engine: Engine = _engine self.db_schema: str = db_schema if db_schema is not None else "ai" self.metadata: MetaData = MetaData(schema=self.db_schema) self.create_schema: bool = create_schema # Initialize database session self.Session: scoped_session = scoped_session(sessionmaker(bind=self.db_engine)) def close(self) -> None: """Close database connections and dispose of the connection pool. Should be called during application shutdown to properly release all database connections. """ if self.db_engine is not None: self.db_engine.dispose() # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a table with the given name exists in the MySQL database. Args: table_name: Name of the table to check Returns: bool: True if the table exists in the database, False otherwise """ with self.Session() as sess: return is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) def _create_table(self, table_name: str, table_type: str) -> Table: """ Create a table with the appropriate schema based on the table type. Args: table_name (str): Name of the table to create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object """ try: # Pass traces_table_name and db_schema for spans table foreign key resolution table_schema = get_table_schema_definition( table_type, traces_table_name=self.trace_table_name, db_schema=self.db_schema ).copy() columns: List[Column] = [] indexes: List[str] = [] unique_constraints: List[str] = [] schema_unique_constraints = table_schema.pop("_unique_constraints", []) # Get the columns, indexes, and unique constraints from the table schema for col_name, col_config in table_schema.items(): column_args = [col_name, col_config["type"]()] column_kwargs = {} if col_config.get("primary_key", False): column_kwargs["primary_key"] = True if "nullable" in col_config: column_kwargs["nullable"] = col_config["nullable"] if col_config.get("index", False): indexes.append(col_name) if col_config.get("unique", False): column_kwargs["unique"] = True unique_constraints.append(col_name) # Handle foreign key constraint if "foreign_key" in col_config: column_args.append(ForeignKey(col_config["foreign_key"])) columns.append(Column(*column_args, **column_kwargs)) # type: ignore # Create the table object table = Table(table_name, self.metadata, *columns, schema=self.db_schema) # Add multi-column unique constraints with table-specific names for constraint in schema_unique_constraints: constraint_name = f"{table_name}_{constraint['name']}" constraint_columns = constraint["columns"] table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name)) # Add indexes to the table definition for idx_col in indexes: idx_name = f"idx_{table_name}_{idx_col}" table.append_constraint(Index(idx_name, idx_col)) if self.create_schema: with self.Session() as sess, sess.begin(): create_schema(session=sess, db_schema=self.db_schema) # Create table table_created = False if not self.table_exists(table_name): table.create(self.db_engine, checkfirst=True) log_debug(f"Successfully created table '{table_name}'") table_created = True else: log_debug(f"Table {self.db_schema}.{table_name} already exists, skipping creation") # Create indexes for idx in table.indexes: try: # Check if index already exists with self.Session() as sess: exists_query = text( "SELECT 1 FROM information_schema.statistics WHERE table_schema = :schema " "AND table_name = :table_name AND index_name = :index_name" ) exists = ( sess.execute( exists_query, {"schema": self.db_schema, "table_name": table_name, "index_name": idx.name}, ).scalar() is not None ) if exists: log_debug( f"Index {idx.name} already exists in {self.db_schema}.{table_name}, skipping creation" ) continue idx.create(self.db_engine) log_debug(f"Created index: {idx.name} for table {self.db_schema}.{table_name}") except Exception as e: log_error(f"Error creating index {idx.name}: {e}") # Store the schema version for the created table if table_name != self.versions_table_name and table_created: latest_schema_version = MigrationManager(self).latest_schema_version self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public) log_info( f"Successfully stored version {latest_schema_version.public} in database for table {table_name}" ) return table except Exception as e: log_error(f"Could not create table {self.db_schema}.{table_name}: {e}") raise def _create_all_tables(self): """Create all tables for the database.""" tables_to_create = [ (self.session_table_name, "sessions"), (self.memory_table_name, "memories"), (self.metrics_table_name, "metrics"), (self.eval_table_name, "evals"), (self.knowledge_table_name, "knowledge"), (self.culture_table_name, "culture"), (self.trace_table_name, "traces"), (self.span_table_name, "spans"), (self.versions_table_name, "versions"), ] for table_name, table_type in tables_to_create: self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True) def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Optional[Table]: if table_type == "sessions": self.session_table = self._get_or_create_table( table_name=self.session_table_name, table_type="sessions", create_table_if_not_found=create_table_if_not_found, ) return self.session_table if table_type == "memories": self.memory_table = self._get_or_create_table( table_name=self.memory_table_name, table_type="memories", create_table_if_not_found=create_table_if_not_found, ) return self.memory_table if table_type == "metrics": self.metrics_table = self._get_or_create_table( table_name=self.metrics_table_name, table_type="metrics", create_table_if_not_found=create_table_if_not_found, ) return self.metrics_table if table_type == "evals": self.eval_table = self._get_or_create_table( table_name=self.eval_table_name, table_type="evals", create_table_if_not_found=create_table_if_not_found, ) return self.eval_table if table_type == "knowledge": self.knowledge_table = self._get_or_create_table( table_name=self.knowledge_table_name, table_type="knowledge", create_table_if_not_found=create_table_if_not_found, ) return self.knowledge_table if table_type == "culture": self.culture_table = self._get_or_create_table( table_name=self.culture_table_name, table_type="culture", create_table_if_not_found=create_table_if_not_found, ) return self.culture_table if table_type == "versions": self.versions_table = self._get_or_create_table( table_name=self.versions_table_name, table_type="versions", create_table_if_not_found=create_table_if_not_found, ) return self.versions_table if table_type == "traces": self.traces_table = self._get_or_create_table( table_name=self.trace_table_name, table_type="traces", create_table_if_not_found=create_table_if_not_found, ) return self.traces_table if table_type == "spans": # Ensure traces table exists first (spans has FK to traces) if create_table_if_not_found: self._get_table(table_type="traces", create_table_if_not_found=True) self.spans_table = self._get_or_create_table( table_name=self.span_table_name, table_type="spans", create_table_if_not_found=create_table_if_not_found, ) return self.spans_table raise ValueError(f"Unknown table type: {table_type}") def _get_or_create_table( self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False ) -> Optional[Table]: """ Check if the table exists and is valid, else create it. Args: table_name (str): Name of the table to get or create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object representing the schema. """ with self.Session() as sess, sess.begin(): table_is_available = is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) if not table_is_available: if not create_table_if_not_found: return None created_table = self._create_table(table_name=table_name, table_type=table_type) return created_table if not is_valid_table( db_engine=self.db_engine, table_name=table_name, table_type=table_type, db_schema=self.db_schema, ): raise ValueError(f"Table {self.db_schema}.{table_name} has an invalid schema") try: table = Table(table_name, self.metadata, schema=self.db_schema, autoload_with=self.db_engine) return table except Exception as e: log_error(f"Error loading existing table {self.db_schema}.{table_name}: {e}") raise def get_latest_schema_version(self, table_name: str) -> str: """Get the latest version of the database schema.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) with self.Session() as sess: # Latest version for the given table stmt = select(table).where(table.c.table_name == table_name).order_by(table.c.version.desc()).limit(1) # type: ignore result = sess.execute(stmt).fetchone() if result is None: return "2.0.0" version_dict = dict(result._mapping) return version_dict.get("version") or "2.0.0" def upsert_schema_version(self, table_name: str, version: str) -> None: """Upsert the schema version into the database.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return current_datetime = datetime.now().isoformat() with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values( # type: ignore table_name=table_name, version=version, created_at=current_datetime, # Store as ISO format string updated_at=current_datetime, ) # Update version if table_name already exists stmt = stmt.on_duplicate_key_update( version=version, created_at=current_datetime, updated_at=current_datetime, ) sess.execute(stmt) # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """ Delete a session from the database. Args: session_id (str): ID of the session to delete user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return False with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id == session_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No session found to delete with session_id: {session_id} in table {table.name}") return False else: log_debug(f"Successfully deleted session with session_id: {session_id} in table {table.name}") return True except Exception as e: log_error(f"Error deleting session: {e}") return False def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete all given sessions from the database. Can handle multiple session types in the same run. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id.in_(session_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) log_debug(f"Successfully deleted {result.rowcount} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Read a session from the database. Args: session_id (str): ID of the session to read. session_type (SessionType): Type of session to get. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.session_id == session_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if result is None: return None session = dict(result._mapping) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session table: {e}") return None def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """ Get all sessions in the given table. Can filter by user_id and entity_id. Args: session_type (Optional[SessionType]): The type of sessions to get. user_id (Optional[str]): The ID of the user to filter by. component_id (Optional[str]): The ID of the agent / workflow to filter by. start_timestamp (Optional[int]): The start timestamp to filter by. end_timestamp (Optional[int]): The end timestamp to filter by. session_name (Optional[str]): The name of the session to filter by. limit (Optional[int]): The maximum number of sessions to return. Defaults to None. page (Optional[int]): The page number to return. Defaults to None. sort_by (Optional[str]): The field to sort by. Defaults to None. sort_order (Optional[str]): The sort order. Defaults to None. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. Returns: Union[List[Session], Tuple[List[Dict], int]]: - When deserialize=True: List of Session objects - When deserialize=False: Tuple of (session dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if component_id is not None: if session_type == SessionType.AGENT: stmt = stmt.where(table.c.agent_id == component_id) elif session_type == SessionType.TEAM: stmt = stmt.where(table.c.team_id == component_id) elif session_type == SessionType.WORKFLOW: stmt = stmt.where(table.c.workflow_id == component_id) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) if session_name is not None: # MySQL JSON extraction syntax stmt = stmt.where( func.coalesce( func.json_unquote(func.json_extract(table.c.session_data, "$.session_name")), "" ).ilike(f"%{session_name}%") ) if session_type is not None: session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type stmt = stmt.where(table.c.session_type == session_type_value) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) session_dicts = [dict(row._mapping) for row in result] if not deserialize: return session_dicts, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(record) for record in session_dicts] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(record) for record in session_dicts] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(record) for record in session_dicts] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception getting sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name for the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during renaming. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess, sess.begin(): # MySQL JSON_SET syntax stmt = ( update(table) .where(table.c.session_id == session_id) .where(table.c.session_type == session_type.value) .values(session_data=func.json_set(table.c.session_data, "$.session_name", session_name)) ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) sess.execute(stmt) # Fetch the updated row select_stmt = select(table).where(table.c.session_id == session_id) if user_id is not None: select_stmt = select_stmt.where(table.c.user_id == user_id) result = sess.execute(select_stmt) row = result.fetchone() if not row: return None session = dict(row._mapping) if not deserialize: return session # Return the appropriate session type if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception renaming session: {e}") return None def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """ Insert or update a session in the database. Args: session (Session): The session data to upsert. deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return None session_dict = session.to_dict() if isinstance(session, AgentSession): with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.AGENT.value, agent_id=session_dict.get("agent_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), agent_data=session_dict.get("agent_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( agent_id=session_dict.get("agent_id"), user_id=session_dict.get("user_id"), agent_data=session_dict.get("agent_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the row select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id")) result = sess.execute(select_stmt) row = result.fetchone() if not row: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return AgentSession.from_dict(session_dict) elif isinstance(session, TeamSession): with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.TEAM.value, team_id=session_dict.get("team_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), team_data=session_dict.get("team_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( team_id=session_dict.get("team_id"), user_id=session_dict.get("user_id"), team_data=session_dict.get("team_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the row select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id")) result = sess.execute(select_stmt) row = result.fetchone() if not row: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return TeamSession.from_dict(session_dict) else: with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.WORKFLOW.value, workflow_id=session_dict.get("workflow_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), workflow_data=session_dict.get("workflow_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( workflow_id=session_dict.get("workflow_id"), user_id=session_dict.get("user_id"), workflow_data=session_dict.get("workflow_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the row select_stmt = select(table).where(table.c.session_id == session_dict.get("session_id")) result = sess.execute(select_stmt) row = result.fetchone() if not row: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return WorkflowSession.from_dict(session_dict) except Exception as e: log_error(f"Exception upserting into sessions table: {e}") return None def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. preserve_updated_at (bool): If True, preserve the updated_at from the session object. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: log_info("Sessions table not available, falling back to individual upserts") return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] # Group sessions by type for batch processing agent_sessions = [] team_sessions = [] workflow_sessions = [] for session in sessions: if isinstance(session, AgentSession): agent_sessions.append(session) elif isinstance(session, TeamSession): team_sessions.append(session) elif isinstance(session, WorkflowSession): workflow_sessions.append(session) results: List[Union[Session, Dict[str, Any]]] = [] # Process each session type in bulk with self.Session() as sess, sess.begin(): # Bulk upsert agent sessions if agent_sessions: agent_data = [] for session in agent_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) agent_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if agent_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( agent_id=stmt.inserted.agent_id, user_id=stmt.inserted.user_id, agent_data=stmt.inserted.agent_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, agent_data) # Fetch the results for agent sessions agent_ids = [session.session_id for session in agent_sessions] select_stmt = select(table).where(table.c.session_id.in_(agent_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = dict(row._mapping) if deserialize: deserialized_agent_session = AgentSession.from_dict(session_dict) if deserialized_agent_session is None: continue results.append(deserialized_agent_session) else: results.append(session_dict) # Bulk upsert team sessions if team_sessions: team_data = [] for session in team_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) team_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if team_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( team_id=stmt.inserted.team_id, user_id=stmt.inserted.user_id, team_data=stmt.inserted.team_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, team_data) # Fetch the results for team sessions team_ids = [session.session_id for session in team_sessions] select_stmt = select(table).where(table.c.session_id.in_(team_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = dict(row._mapping) if deserialize: deserialized_team_session = TeamSession.from_dict(session_dict) if deserialized_team_session is None: continue results.append(deserialized_team_session) else: results.append(session_dict) # Bulk upsert workflow sessions if workflow_sessions: workflow_data = [] for session in workflow_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) workflow_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if workflow_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( workflow_id=stmt.inserted.workflow_id, user_id=stmt.inserted.user_id, workflow_data=stmt.inserted.workflow_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, workflow_data) # Fetch the results for workflow sessions workflow_ids = [session.session_id for session in workflow_sessions] select_stmt = select(table).where(table.c.session_id.in_(workflow_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = dict(row._mapping) if deserialize: deserialized_workflow_session = WorkflowSession.from_dict(session_dict) if deserialized_workflow_session is None: continue results.append(deserialized_workflow_session) else: results.append(session_dict) return results except Exception as e: log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The user ID to filter by. Defaults to None. Returns: bool: True if deletion was successful, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id == memory_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting user memory: {e}") def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The user ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No user memories found with ids: {memory_ids}") except Exception as e: log_error(f"Error deleting user memories: {e}") def get_all_memory_topics(self, user_id: Optional[str] = None) -> List[str]: """Get all memory topics from the database. Args: user_id (Optional[str]): Optional user ID to filter topics. Returns: List[str]: List of memory topics. """ try: table = self._get_table(table_type="memories") if table is None: return [] with self.Session() as sess, sess.begin(): # MySQL approach: extract JSON array elements differently stmt = select(table.c.topics) result = sess.execute(stmt).fetchall() topics_set = set() for row in result: if row[0]: # Parse JSON array and add topics to set import json try: topics = json.loads(row[0]) if isinstance(row[0], str) else row[0] if isinstance(topics, list): topics_set.update(topics) except Exception: pass return list(topics_set) except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[UserMemory]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The user ID to filter by. Defaults to None. Returns: Union[UserMemory, Dict[str, Any], None]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.memory_id == memory_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if not result: return None memory_raw = result._mapping if not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception reading from memory table: {e}") return None def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as MemoryRow objects. Args: user_id (Optional[str]): The ID of the user to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. topics (Optional[List[str]]): The topics to filter by. search_content (Optional[str]): The content to search for. limit (Optional[int]): The maximum number of memories to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. Returns: Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of UserMemory objects - When deserialize=False: Tuple of (memory dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if topics is not None: # MySQL JSON contains syntax topic_conditions = [] for topic in topics: topic_conditions.append(func.json_contains(table.c.topics, f'"{topic}"')) stmt = stmt.where(and_(*topic_conditions)) if search_content is not None: stmt = stmt.where(cast(table.c.memory, TEXT).ilike(f"%{search_content}%")) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) memories_raw = [record._mapping for record in result] if not deserialize: return memories_raw, total_count return [UserMemory.from_dict(record) for record in memories_raw] except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def clear_memories(self) -> None: """Clear all user memories from the database.""" try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_error(f"Exception clearing user memories: {e}") def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. Example: ( [ { "user_id": "123", "total_memories": 10, "last_memory_updated_at": 1714560000, }, ], total_count: 1, ) """ try: table = self._get_table(table_type="memories") if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select( table.c.user_id, func.count(table.c.memory_id).label("total_memories"), func.max(table.c.updated_at).label("last_memory_updated_at"), ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) else: stmt = stmt.where(table.c.user_id.is_not(None)) stmt = stmt.group_by(table.c.user_id) stmt = stmt.order_by(func.max(table.c.updated_at).desc()) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Pagination if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [], 0 return [ { "user_id": record.user_id, # type: ignore "total_memories": record.total_memories, "last_memory_updated_at": record.last_memory_updated_at, } for record in result ], total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") return [], 0 def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The user memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): if memory.memory_id is None: memory.memory_id = str(uuid4()) current_time = int(time.time()) stmt = mysql.insert(table).values( memory_id=memory.memory_id, memory=memory.memory, input=memory.input, user_id=memory.user_id, agent_id=memory.agent_id, team_id=memory.team_id, topics=memory.topics, feedback=memory.feedback, created_at=memory.created_at, updated_at=memory.created_at, ) stmt = stmt.on_duplicate_key_update( memory=memory.memory, topics=memory.topics, input=memory.input, agent_id=memory.agent_id, team_id=memory.team_id, feedback=memory.feedback, updated_at=current_time, # Preserve created_at on update - don't overwrite existing value created_at=table.c.created_at, ) sess.execute(stmt) # Fetch the row select_stmt = select(table).where(table.c.memory_id == memory.memory_id) result = sess.execute(select_stmt) row = result.fetchone() if not row: return None memory_raw = row._mapping if not memory_raw or not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception upserting user memory: {e}") return None def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: log_info("Memories table not available, falling back to individual upserts") return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] # Prepare bulk data bulk_data = [] current_time = int(time.time()) for memory in memories: if memory.memory_id is None: memory.memory_id = str(uuid4()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = memory.updated_at if preserve_updated_at else current_time bulk_data.append( { "memory_id": memory.memory_id, "memory": memory.memory, "input": memory.input, "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "topics": memory.topics, "feedback": memory.feedback, "created_at": memory.created_at, "updated_at": updated_at, } ) results: List[Union[UserMemory, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): # Bulk upsert memories using MySQL ON DUPLICATE KEY UPDATE stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( memory=stmt.inserted.memory, topics=stmt.inserted.topics, input=stmt.inserted.input, agent_id=stmt.inserted.agent_id, team_id=stmt.inserted.team_id, feedback=stmt.inserted.feedback, updated_at=stmt.inserted.updated_at, # Preserve created_at on update created_at=table.c.created_at, ) sess.execute(stmt, bulk_data) # Fetch results memory_ids = [memory.memory_id for memory in memories if memory.memory_id] select_stmt = select(table).where(table.c.memory_id.in_(memory_ids)) result = sess.execute(select_stmt).fetchall() for row in result: memory_dict = dict(row._mapping) if deserialize: results.append(UserMemory.from_dict(memory_dict)) else: results.append(memory_dict) return results except Exception as e: log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """ Get all sessions of all types (agent, team, workflow) as raw dictionaries. Args: start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None. end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None. Returns: List[Dict[str, Any]]: List of session dictionaries with session_type field. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] stmt = select( table.c.user_id, table.c.session_data, table.c.runs, table.c.created_at, table.c.session_type, ) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) with self.Session() as sess: result = sess.execute(stmt).fetchall() return [record._mapping for record in result] except Exception as e: log_error(f"Exception reading from sessions table: {e}") raise e def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]: """Get the first date for which metrics calculation is needed: 1. If there are metrics records, return the date of the first day without a complete metrics record. 2. If there are no metrics records, return the date of the first recorded session. 3. If there are no metrics records and no sessions records, return None. Args: table (Table): The table to get the starting date for. Returns: Optional[date]: The starting date for which metrics calculation is needed. """ with self.Session() as sess: stmt = select(table).order_by(table.c.date.desc()).limit(1) result = sess.execute(stmt).fetchone() # 1. Return the date of the first day without a complete metrics record. if result is not None: if result.completed: return result._mapping["date"] + timedelta(days=1) else: return result._mapping["date"] # 2. No metrics records. Return the date of the first recorded session. first_session, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) if not isinstance(first_session, list): raise ValueError("Error obtaining session list to calculate metrics") first_session_date = first_session[0]["created_at"] if first_session else None # 3. No metrics records and no sessions records. Return None. if first_session_date is None: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics. Returns: Optional[list[dict]]: The calculated metrics. Raises: Exception: If an error occurs during metrics calculation. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return None starting_date = self._get_metrics_calculation_starting_date(table) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int( datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp() ) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()) .replace(tzinfo=timezone.utc) .timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: with self.Session() as sess, sess.begin(): results = bulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records) return results except Exception as e: log_error(f"Exception refreshing metrics: {e}") return None def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range. Args: starting_date (Optional[date]): The starting date to filter metrics by. ending_date (Optional[date]): The ending date to filter metrics by. Returns: Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select(table) if starting_date: stmt = stmt.where(table.c.date >= starting_date) if ending_date: stmt = stmt.where(table.c.date <= ending_date) result = sess.execute(stmt).fetchall() if not result: return [], None # Get the latest updated_at latest_stmt = select(func.max(table.c.updated_at)) latest_updated_at = sess.execute(latest_stmt).scalar() return [row._mapping for row in result], latest_updated_at except Exception as e: log_error(f"Exception getting metrics: {e}") return [], None # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ table = self._get_table(table_type="knowledge") if table is None: return None try: with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.id == id) sess.execute(stmt) except Exception as e: log_error(f"Exception deleting knowledge content: {e}") def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ table = self._get_table(table_type="knowledge") if table is None: return None try: with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None return KnowledgeRow.model_validate(result._mapping) except Exception as e: log_error(f"Exception getting knowledge content: {e}") return None def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ table = self._get_table(table_type="knowledge") if table is None: return [], 0 try: with self.Session() as sess, sess.begin(): stmt = select(table) # Apply linked_to filter if provided if linked_to is not None: stmt = stmt.where(table.c.linked_to == linked_to) # Apply sorting if sort_by is not None: stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1)) # Get total count before applying limit and pagination count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Apply pagination after count if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [], 0 return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count except Exception as e: log_error(f"Exception getting knowledge contents: {e}") return [], 0 def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="knowledge", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): # Get the actual table columns to avoid "unconsumed column names" error table_columns = set(table.columns.keys()) # Only include fields that exist in the table and are not None insert_data = {} update_fields = {} # Map of KnowledgeRow fields to table columns field_mapping = { "id": "id", "name": "name", "description": "description", "metadata": "metadata", "type": "type", "size": "size", "linked_to": "linked_to", "access_count": "access_count", "status": "status", "status_message": "status_message", "created_at": "created_at", "updated_at": "updated_at", "external_id": "external_id", } # Build insert and update data only for fields that exist in the table for model_field, table_column in field_mapping.items(): if table_column in table_columns: value = getattr(knowledge_row, model_field, None) if value is not None: insert_data[table_column] = value # Don't include ID in update_fields since it's the primary key if table_column != "id": update_fields[table_column] = value # Ensure id is always included for the insert if "id" in table_columns and knowledge_row.id: insert_data["id"] = knowledge_row.id # Handle case where update_fields is empty (all fields are None or don't exist in table) if not update_fields: # If we have insert_data, just do an insert without conflict resolution if insert_data: stmt = mysql.insert(table).values(insert_data) sess.execute(stmt) else: # If we have no data at all, this is an error log_error("No valid fields found for knowledge row upsert") return None else: # Normal upsert with conflict resolution stmt = mysql.insert(table).values(insert_data).on_duplicate_key_update(**update_fields) sess.execute(stmt) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge row: {e}") return None # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run, or None if the operation fails. Raises: Exception: If an error occurs during creation. """ try: table = self._get_table(table_type="evals", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): current_time = int(time.time()) stmt = mysql.insert(table).values( {"created_at": current_time, "updated_at": current_time, **eval_run.model_dump()} ) sess.execute(stmt) return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") return None def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database. Args: eval_run_id (str): The ID of the eval run to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id == eval_run_id) result = sess.execute(stmt) if result.rowcount == 0: log_error(f"No eval run found with ID: {eval_run_id}") else: log_debug(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database. Args: eval_run_ids (List[str]): List of eval run IDs to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id.in_(eval_run_ids)) result = sess.execute(stmt) if result.rowcount == 0: log_error(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {result.rowcount} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.run_id == eval_run_id) result = sess.execute(stmt).fetchone() if result is None: return None eval_run_raw = result._mapping if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") return None def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by. filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow). deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of dictionaries Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if model_id is not None: stmt = stmt.where(table.c.model_id == model_id) if eval_type is not None and len(eval_type) > 0: stmt = stmt.where(table.c.eval_type.in_(eval_type)) if filter_type is not None: if filter_type == EvalFilterType.AGENT: stmt = stmt.where(table.c.agent_id.is_not(None)) elif filter_type == EvalFilterType.TEAM: stmt = stmt.where(table.c.team_id.is_not(None)) elif filter_type == EvalFilterType.WORKFLOW: stmt = stmt.where(table.c.workflow_id.is_not(None)) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting if sort_by is None: stmt = stmt.order_by(table.c.created_at.desc()) else: stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) eval_runs_raw = [row._mapping for row in result] if not deserialize: return eval_runs_raw, total_count return [EvalRunRecord.model_validate(row) for row in eval_runs_raw] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Upsert the name of an eval run in the database, returning raw dictionary. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. Returns: Optional[Dict[str, Any]]: The updated eval run, or None if the operation fails. Raises: Exception: If an error occurs during update. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = ( table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time())) ) sess.execute(stmt) eval_run_raw = self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize) if not eval_run_raw or not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Error upserting eval run name {eval_run_id}: {e}") return None # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_warning(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.id == id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted cultural knowledge id: {id}") else: log_debug(f"No cultural knowledge found with id: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to get. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge entry, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None db_row = dict(result._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge_from_db(db_row) except Exception as e: log_error(f"Exception reading from cultural knowledge table: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from the database as CulturalKnowledge objects. Args: name (Optional[str]): The name of the cultural knowledge to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. limit (Optional[int]): The maximum number of cultural knowledge entries to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: List of CulturalKnowledge dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if name is not None: stmt = stmt.where(table.c.name == name) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) db_rows = [dict(record._mapping) for record in result] if not deserialize: return db_rows, total_count return [deserialize_cultural_knowledge_from_db(row) for row in db_rows] except Exception as e: log_error(f"Error reading from cultural knowledge table: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into the database. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[CulturalKnowledge]: The upserted cultural knowledge entry. Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="culture", create_table_if_not_found=True) if table is None: return None if cultural_knowledge.id is None: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a JSON dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values( id=cultural_knowledge.id, name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_dict if content_dict else None, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, created_at=cultural_knowledge.created_at, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) stmt = stmt.on_duplicate_key_update( name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_dict if content_dict else None, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) sess.execute(stmt) # Fetch the inserted/updated row return self.get_cultural_knowledge(id=cultural_knowledge.id, deserialize=deserialize) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # -- Migrations -- def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str): """Migrate all content in the given table to the right v2 table""" from agno.db.migrations.v1_to_v2 import ( get_all_table_content, parse_agent_sessions, parse_memories, parse_team_sessions, parse_workflow_sessions, ) # Get all content from the old table old_content: list[dict[str, Any]] = get_all_table_content( db=self, db_schema=v1_db_schema, table_name=v1_table_name, ) if not old_content: log_info(f"No content to migrate from table {v1_table_name}") return # Parse the content into the new format memories: List[UserMemory] = [] sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = [] if v1_table_type == "agent_sessions": sessions = parse_agent_sessions(old_content) elif v1_table_type == "team_sessions": sessions = parse_team_sessions(old_content) elif v1_table_type == "workflow_sessions": sessions = parse_workflow_sessions(old_content) elif v1_table_type == "memories": memories = parse_memories(old_content) else: raise ValueError(f"Invalid table type: {v1_table_type}") # Insert the new content into the new table if v1_table_type == "agent_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table_name}") elif v1_table_type == "team_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table_name}") elif v1_table_type == "workflow_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table_name}") elif v1_table_type == "memories": for memory in memories: self.upsert_user_memory(memory) log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}") # --- Traces --- def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None): """Build base query for traces with aggregated span counts. Args: table: The traces table. spans_table: The spans table (optional). Returns: SQLAlchemy select statement with total_spans and error_count calculated dynamically. """ from sqlalchemy import case, literal if spans_table is not None: # JOIN with spans table to calculate total_spans and error_count return ( select( table, func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"), func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label( "error_count" ), ) .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id)) .group_by(table.c.trace_id) ) else: # Fallback if spans table doesn't exist return select(table, literal(0).label("total_spans"), literal(0).label("error_count")) def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col): """Build a SQL CASE expression that returns the component level for a trace. Component levels (higher = more important): - 3: Workflow root (.run or .arun with workflow_id) - 2: Team root (.run or .arun with team_id) - 1: Agent root (.run or .arun with agent_id) - 0: Child span (not a root) Args: workflow_id_col: SQL column/expression for workflow_id team_id_col: SQL column/expression for team_id agent_id_col: SQL column/expression for agent_id name_col: SQL column/expression for name Returns: SQLAlchemy CASE expression returning the component level as an integer. """ from sqlalchemy import and_, case, or_ is_root_name = or_(name_col.like("%.run%"), name_col.like("%.arun%")) return case( # Workflow root (level 3) (and_(workflow_id_col.isnot(None), is_root_name), 3), # Team root (level 2) (and_(team_id_col.isnot(None), is_root_name), 2), # Agent root (level 1) (and_(agent_id_col.isnot(None), is_root_name), 1), # Child span or unknown (level 0) else_=0, ) def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Uses INSERT ... ON DUPLICATE KEY UPDATE (upsert) to handle concurrent inserts atomically and avoid race conditions. Args: trace: The Trace object to store (one per trace_id). """ from sqlalchemy import case try: table = self._get_table(table_type="traces", create_table_if_not_found=True) if table is None: return trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) with self.Session() as sess, sess.begin(): # Use upsert to handle concurrent inserts atomically # On conflict, update fields while preserving existing non-null context values # and keeping the earliest start_time insert_stmt = mysql.insert(table).values(trace_dict) # Build component level expressions for comparing trace priority new_level = self._get_trace_component_level_expr( insert_stmt.inserted.workflow_id, insert_stmt.inserted.team_id, insert_stmt.inserted.agent_id, insert_stmt.inserted.name, ) existing_level = self._get_trace_component_level_expr( table.c.workflow_id, table.c.team_id, table.c.agent_id, table.c.name, ) # Build the ON DUPLICATE KEY UPDATE clause # Use LEAST for start_time, GREATEST for end_time to capture full trace duration # MySQL stores timestamps as ISO strings, so string comparison works for ISO format # Duration is calculated using TIMESTAMPDIFF in microseconds then converted to ms upsert_stmt = insert_stmt.on_duplicate_key_update( end_time=func.greatest(table.c.end_time, insert_stmt.inserted.end_time), start_time=func.least(table.c.start_time, insert_stmt.inserted.start_time), # Calculate duration in milliseconds using TIMESTAMPDIFF # TIMESTAMPDIFF(MICROSECOND, start, end) / 1000 gives milliseconds duration_ms=func.timestampdiff( text("MICROSECOND"), func.least(table.c.start_time, insert_stmt.inserted.start_time), func.greatest(table.c.end_time, insert_stmt.inserted.end_time), ) / 1000, status=insert_stmt.inserted.status, # Update name only if new trace is from a higher-level component # Priority: workflow (3) > team (2) > agent (1) > child spans (0) name=case( (new_level > existing_level, insert_stmt.inserted.name), else_=table.c.name, ), # Preserve existing non-null context values using COALESCE run_id=func.coalesce(insert_stmt.inserted.run_id, table.c.run_id), session_id=func.coalesce(insert_stmt.inserted.session_id, table.c.session_id), user_id=func.coalesce(insert_stmt.inserted.user_id, table.c.user_id), agent_id=func.coalesce(insert_stmt.inserted.agent_id, table.c.agent_id), team_id=func.coalesce(insert_stmt.inserted.team_id, table.c.team_id), workflow_id=func.coalesce(insert_stmt.inserted.workflow_id, table.c.workflow_id), ) sess.execute(upsert_stmt) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace table = self._get_table(table_type="traces") if table is None: return None # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build query with aggregated span counts stmt = self._get_traces_base_query(table, spans_table) if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) elif run_id: stmt = stmt.where(table.c.run_id == run_id) else: log_debug("get_trace called without any filter parameters") return None # Order by most recent and get first result stmt = stmt.order_by(table.c.start_time.desc()).limit(1) result = sess.execute(stmt).fetchone() if result: return Trace.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace log_debug( 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}" ) table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build base query with aggregated span counts base_stmt = self._get_traces_base_query(table, spans_table) # Apply filters if run_id: base_stmt = base_stmt.where(table.c.run_id == run_id) if session_id: base_stmt = base_stmt.where(table.c.session_id == session_id) if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if status: base_stmt = base_stmt.where(table.c.status == status) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat()) # Get total count count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() traces = [Trace.from_dict(dict(row._mapping)) for row in results] return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, workflow_id, first_trace_at, last_trace_at. """ try: table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 with self.Session() as sess: # Build base query grouped by session_id base_stmt = ( select( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id, func.count(table.c.trace_id).label("total_traces"), func.min(table.c.created_at).label("first_trace_at"), func.max(table.c.created_at).label("last_trace_at"), ) .where(table.c.session_id.isnot(None)) # Only sessions with session_id .group_by( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id ) ) # Apply filters if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat()) # Get total count of sessions count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination and ordering offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() # Convert to list of dicts with datetime objects stats_list = [] for row in results: # Convert ISO strings to datetime objects first_trace_at_str = row.first_trace_at last_trace_at_str = row.last_trace_at # Parse ISO format strings to datetime objects first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) stats_list.append( { "session_id": row.session_id, "user_id": row.user_id, "agent_id": row.agent_id, "team_id": row.team_id, "workflow_id": row.workflow_id, "total_traces": row.total_traces, "first_trace_at": first_trace_at, "last_trace_at": last_trace_at, } ) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): for span in spans: stmt = mysql.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.span_id == span_id) result = sess.execute(stmt).fetchone() if result: return Span.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return [] with self.Session() as sess: stmt = select(table) # Apply filters if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) if parent_span_id: stmt = stmt.where(table.c.parent_span_id == parent_span_id) if limit: stmt = stmt.limit(limit) results = sess.execute(stmt).fetchall() return [Span.from_dict(dict(row._mapping)) for row in results] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for MySQLDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for MySQLDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for MySQLDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for MySQLDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mysql/mysql.py", "license": "Apache License 2.0", "lines": 2552, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/mysql/schemas.py
"""Table schemas and related utils used by the MySQLDb class""" from typing import Any try: from sqlalchemy.types import JSON, BigInteger, Boolean, Date, String, Text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") SESSION_TABLE_SCHEMA = { "session_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "session_type": {"type": lambda: String(20), "nullable": False, "index": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "workflow_id": {"type": lambda: String(128), "nullable": True}, "user_id": {"type": lambda: String(128), "nullable": True}, "session_data": {"type": JSON, "nullable": True}, "agent_data": {"type": JSON, "nullable": True}, "team_data": {"type": JSON, "nullable": True}, "workflow_data": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "runs": {"type": JSON, "nullable": True}, "summary": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } USER_MEMORY_TABLE_SCHEMA = { "memory_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "memory": {"type": JSON, "nullable": False}, "input": {"type": Text, "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "user_id": {"type": lambda: String(128), "nullable": True, "index": True}, "topics": {"type": JSON, "nullable": True}, "feedback": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True, "index": True}, } EVAL_TABLE_SCHEMA = { "run_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "eval_type": {"type": lambda: String(50), "nullable": False}, "eval_data": {"type": JSON, "nullable": False}, "eval_input": {"type": JSON, "nullable": False}, "name": {"type": lambda: String(255), "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "workflow_id": {"type": lambda: String(128), "nullable": True}, "model_id": {"type": lambda: String(128), "nullable": True}, "model_provider": {"type": lambda: String(128), "nullable": True}, "evaluated_component_name": {"type": lambda: String(255), "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(255), "nullable": False}, "description": {"type": Text, "nullable": False}, "metadata": {"type": JSON, "nullable": True}, "type": {"type": lambda: String(50), "nullable": True}, "size": {"type": BigInteger, "nullable": True}, "linked_to": {"type": lambda: String(128), "nullable": True}, "access_count": {"type": BigInteger, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "status": {"type": lambda: String(50), "nullable": True}, "status_message": {"type": Text, "nullable": True}, "external_id": {"type": lambda: String(128), "nullable": True}, } METRICS_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "agent_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "agent_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "users_count": {"type": BigInteger, "nullable": False, "default": 0}, "token_metrics": {"type": JSON, "nullable": False, "default": {}}, "model_metrics": {"type": JSON, "nullable": False, "default": {}}, "date": {"type": Date, "nullable": False, "index": True}, "aggregation_period": {"type": lambda: String(20), "nullable": False}, "created_at": {"type": BigInteger, "nullable": False}, "updated_at": {"type": BigInteger, "nullable": True}, "completed": {"type": Boolean, "nullable": False, "default": False}, "_unique_constraints": [ { "name": "uq_metrics_date_period", "columns": ["date", "aggregation_period"], } ], } CULTURAL_KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(255), "nullable": False, "index": True}, "summary": {"type": Text, "nullable": True}, "content": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "input": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, } VERSIONS_TABLE_SCHEMA = { "table_name": {"type": lambda: String(128), "nullable": False, "primary_key": True}, "version": {"type": lambda: String(10), "nullable": False}, "created_at": {"type": lambda: String(128), "nullable": False, "index": True}, "updated_at": {"type": lambda: String(128), "nullable": True}, } TRACE_TABLE_SCHEMA = { "trace_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(255), "nullable": False}, "status": {"type": lambda: String(50), "nullable": False, "index": True}, "start_time": {"type": lambda: String(128), "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": lambda: String(128), "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "run_id": {"type": lambda: String(128), "nullable": True, "index": True}, "session_id": {"type": lambda: String(128), "nullable": True, "index": True}, "user_id": {"type": lambda: String(128), "nullable": True, "index": True}, "agent_id": {"type": lambda: String(128), "nullable": True, "index": True}, "team_id": {"type": lambda: String(128), "nullable": True, "index": True}, "workflow_id": {"type": lambda: String(128), "nullable": True, "index": True}, "created_at": {"type": lambda: String(128), "nullable": False, "index": True}, # ISO 8601 datetime string } def _get_span_table_schema(traces_table_name: str = "agno_traces", db_schema: str = "agno") -> dict[str, Any]: """Get the span table schema with the correct foreign key reference. Args: traces_table_name: The name of the traces table to reference in the foreign key. db_schema: The database schema name. Returns: The span table schema dictionary. """ return { "span_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "trace_id": { "type": lambda: String(128), "nullable": False, "index": True, "foreign_key": f"{db_schema}.{traces_table_name}.trace_id", }, "parent_span_id": {"type": lambda: String(128), "nullable": True, "index": True}, "name": {"type": lambda: String(255), "nullable": False}, "span_kind": {"type": lambda: String(50), "nullable": False}, "status_code": {"type": lambda: String(50), "nullable": False}, "status_message": {"type": Text, "nullable": True}, "start_time": {"type": lambda: String(128), "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": lambda: String(128), "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "attributes": {"type": JSON, "nullable": True}, "created_at": {"type": lambda: String(128), "nullable": False, "index": True}, # ISO 8601 datetime string } def get_table_schema_definition( table_type: str, traces_table_name: str = "agno_traces", db_schema: str = "agno" ) -> dict[str, Any]: """ Get the expected schema definition for the given table. Args: table_type (str): The type of table to get the schema for. traces_table_name (str): The name of the traces table (used for spans foreign key). db_schema (str): The database schema name (used for spans foreign key). Returns: Dict[str, Any]: Dictionary containing column definitions for the table """ # Handle spans table specially to resolve the foreign key reference if table_type == "spans": return _get_span_table_schema(traces_table_name, db_schema) schemas = { "sessions": SESSION_TABLE_SCHEMA, "evals": EVAL_TABLE_SCHEMA, "metrics": METRICS_TABLE_SCHEMA, "memories": USER_MEMORY_TABLE_SCHEMA, "knowledge": KNOWLEDGE_TABLE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA, "versions": VERSIONS_TABLE_SCHEMA, "traces": TRACE_TABLE_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema # type: ignore[return-value]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mysql/schemas.py", "license": "Apache License 2.0", "lines": 177, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/mysql/utils.py
"""Utility functions for the MySQL database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from agno.db.mysql.schemas import get_table_schema_definition from agno.db.schemas.culture import CulturalKnowledge from agno.utils.log import log_debug, log_error, log_warning try: from sqlalchemy import Engine, Table, func from sqlalchemy.dialects import mysql from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession from sqlalchemy.inspection import inspect from sqlalchemy.orm import Session from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") # -- DB util methods -- def apply_sorting(stmt, table: Table, sort_by: Optional[str] = None, sort_order: Optional[str] = None): """Apply sorting to the given SQLAlchemy statement. Args: stmt: The SQLAlchemy statement to modify table: The table being queried sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The modified statement with sorting applied Note: For 'updated_at' sorting, uses COALESCE(updated_at, created_at) to fall back to created_at when updated_at is NULL. This ensures pre-2.0 records (which may have NULL updated_at) are sorted correctly by their creation time. """ if sort_by is None: return stmt if not hasattr(table.c, sort_by): log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return stmt # For updated_at, use COALESCE to fall back to created_at if updated_at is NULL # This handles pre-2.0 records that may have NULL updated_at values if sort_by == "updated_at" and hasattr(table.c, "created_at"): sort_column = func.coalesce(table.c.updated_at, table.c.created_at) else: sort_column = getattr(table.c, sort_by) if sort_order and sort_order == "asc": return stmt.order_by(sort_column.asc()) else: return stmt.order_by(sort_column.desc()) def create_schema(session: Session, db_schema: str) -> None: """Create the database schema if it doesn't exist. Args: session: The SQLAlchemy session to use db_schema (str): The definition of the database schema to create """ try: log_debug(f"Creating database if not exists: {db_schema}") # MySQL uses CREATE DATABASE instead of CREATE SCHEMA session.execute(text(f"CREATE DATABASE IF NOT EXISTS {db_schema};")) except Exception as e: log_warning(f"Could not create database {db_schema}: {e}") def is_table_available(session: Session, table_name: str, db_schema: str) -> bool: """ Check if a table with the given name exists in the given schema. Returns: bool: True if the table exists, False otherwise. """ try: exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_schema = :schema AND table_name = :table" ) exists = session.execute(exists_query, {"schema": db_schema, "table": table_name}).scalar() is not None if not exists: log_debug(f"Table {db_schema}.{table_name} {'exists' if exists else 'does not exist'}") return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False def is_valid_table(db_engine: Engine, table_name: str, table_type: str, db_schema: str) -> bool: """ Check if the existing table has the expected column names. Args: db_engine: Database engine table_name (str): Name of the table to validate table_type (str): Type of table (for schema lookup) db_schema (str): Database schema name Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns inspector = inspect(db_engine) existing_columns_info = inspector.get_columns(table_name, schema=db_schema) existing_columns = set(col["name"] for col in existing_columns_info) # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {db_schema}.{table_name}") return False return True except Exception as e: log_error(f"Error validating table schema for {db_schema}.{table_name}: {e}") return False # -- Metrics util methods -- def bulk_upsert_metrics(session: Session, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database. Args: session (Session): The SQLAlchemy session table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] # MySQL doesn't support returning in the same way as PostgreSQL # We'll need to insert/update and then fetch the records for record in metrics_records: stmt = mysql.insert(table).values(record) # Columns to update in case of conflict update_dict = { col.name: record.get(col.name) for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] and col.name in record } stmt = stmt.on_duplicate_key_update(**update_dict) session.execute(stmt) session.commit() # Fetch the updated records from sqlalchemy import and_, select for record in metrics_records: select_stmt = select(table).where( and_( table.c.date == record["date"], table.c.aggregation_period == record["aggregation_period"], ) ) result = session.execute(select_stmt).fetchone() if result: results.append(result._mapping) return results # type: ignore async def abulk_upsert_metrics(session: AsyncSession, table: Table, metrics_records: list[dict]) -> list[dict]: """Async bulk upsert metrics into the database. Args: session (AsyncSession): The async SQLAlchemy session table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] # MySQL doesn't support returning in the same way as PostgreSQL # We'll need to insert/update and then fetch the records for record in metrics_records: stmt = mysql.insert(table).values(record) # Columns to update in case of conflict update_dict = { col.name: record.get(col.name) for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] and col.name in record } stmt = stmt.on_duplicate_key_update(**update_dict) await session.execute(stmt) # Fetch the updated records from sqlalchemy import and_, select for record in metrics_records: select_stmt = select(table).where( and_( table.c.date == record["date"], table.c.aggregation_period == record["aggregation_period"], ) ) result = await session.execute(select_stmt) fetched_row = result.fetchone() if fetched_row: results.append(dict(fetched_row._mapping)) return results def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: dates_to_process (list[date]): The dates to fetch session data for. Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db( cultural_knowledge: CulturalKnowledge, ) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single JSON dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as JSON containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a JSON dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the JSON content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } ) # -- Async DB util methods -- async def acreate_schema(session: AsyncSession, db_schema: str) -> None: """Async version: Create the database schema if it doesn't exist. Args: session: The async SQLAlchemy session to use db_schema (str): The definition of the database schema to create """ try: log_debug(f"Creating database if not exists: {db_schema}") # MySQL uses CREATE DATABASE instead of CREATE SCHEMA await session.execute(text(f"CREATE DATABASE IF NOT EXISTS `{db_schema}`;")) except Exception as e: log_warning(f"Could not create database {db_schema}: {e}") async def ais_table_available(session: AsyncSession, table_name: str, db_schema: str) -> bool: """Async version: Check if a table with the given name exists in the given schema. Returns: bool: True if the table exists, False otherwise. """ try: exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_schema = :schema AND table_name = :table" ) result = await session.execute(exists_query, {"schema": db_schema, "table": table_name}) exists = result.scalar() is not None if not exists: log_debug(f"Table {db_schema}.{table_name} {'exists' if exists else 'does not exist'}") return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False async def ais_valid_table(db_engine: AsyncEngine, table_name: str, table_type: str, db_schema: str) -> bool: """Async version: Check if the existing table has the expected column names. Args: db_engine: Async database engine table_name (str): Name of the table to validate table_type (str): Type of table (for schema lookup) db_schema (str): Database schema name Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns from the async engine async with db_engine.connect() as conn: existing_columns = await conn.run_sync(_get_table_columns, table_name, db_schema) # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {db_schema}.{table_name}") return False return True except Exception as e: log_error(f"Error validating table schema for {db_schema}.{table_name}: {e}") return False def _get_table_columns(connection, table_name: str, db_schema: str) -> set[str]: """Helper function to get table columns using sync inspector.""" inspector = inspect(connection) columns_info = inspector.get_columns(table_name, schema=db_schema) return {col["name"] for col in columns_info}
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/mysql/utils.py", "license": "Apache License 2.0", "lines": 397, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/postgres/postgres.py
import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Set, Tuple, Union, cast from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, ComponentType, SessionType from agno.db.migrations.manager import MigrationManager from agno.db.postgres.schemas import get_table_schema_definition from agno.db.postgres.utils import ( apply_sorting, bulk_upsert_metrics, calculate_date_metrics, create_schema, deserialize_cultural_knowledge, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, is_table_available, is_valid_table, serialize_cultural_knowledge, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.db.utils import json_serializer from agno.run.base import RunStatus from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id, sanitize_postgres_string, sanitize_postgres_strings try: from sqlalchemy import ( ForeignKey, ForeignKeyConstraint, Index, PrimaryKeyConstraint, String, UniqueConstraint, and_, case, func, or_, select, update, ) from sqlalchemy.dialects import postgresql from sqlalchemy.dialects.postgresql import TIMESTAMP from sqlalchemy.engine import Engine, create_engine from sqlalchemy.exc import ProgrammingError from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.schema import Column, MetaData, Table from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") class PostgresDb(BaseDb): def __init__( self, db_url: Optional[str] = None, db_engine: Optional[Engine] = None, db_schema: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, versions_table: Optional[str] = None, components_table: Optional[str] = None, component_configs_table: Optional[str] = None, component_links_table: Optional[str] = None, learnings_table: Optional[str] = None, schedules_table: Optional[str] = None, schedule_runs_table: Optional[str] = None, approvals_table: Optional[str] = None, id: Optional[str] = None, create_schema: bool = True, ): """ Interface for interacting with a PostgreSQL database. The following order is used to determine the database connection: 1. Use the db_engine if provided 2. Use the db_url 3. Raise an error if neither is provided Args: db_url (Optional[str]): The database URL to connect to. db_engine (Optional[Engine]): The SQLAlchemy database engine to use. db_schema (Optional[str]): The database schema to use. session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions. memory_table (Optional[str]): Name of the table to store memories. metrics_table (Optional[str]): Name of the table to store metrics. eval_table (Optional[str]): Name of the table to store evaluation runs data. knowledge_table (Optional[str]): Name of the table to store knowledge content. culture_table (Optional[str]): Name of the table to store cultural knowledge. traces_table (Optional[str]): Name of the table to store run traces. spans_table (Optional[str]): Name of the table to store span events. versions_table (Optional[str]): Name of the table to store schema versions. components_table (Optional[str]): Name of the table to store components. component_configs_table (Optional[str]): Name of the table to store component configurations. component_links_table (Optional[str]): Name of the table to store component references. learnings_table (Optional[str]): Name of the table to store learnings. schedules_table (Optional[str]): Name of the table to store cron schedules. schedule_runs_table (Optional[str]): Name of the table to store schedule run history. id (Optional[str]): ID of the database. create_schema (bool): Whether to automatically create the database schema if it doesn't exist. Set to False if schema is managed externally (e.g., via migrations). Defaults to True. Raises: ValueError: If neither db_url nor db_engine is provided. ValueError: If none of the tables are provided. """ _engine: Optional[Engine] = db_engine if _engine is None and db_url is not None: _engine = create_engine( db_url, pool_pre_ping=True, pool_recycle=3600, json_serializer=json_serializer, ) if _engine is None: raise ValueError("One of db_url or db_engine must be provided") self.db_url: Optional[str] = db_url self.db_engine: Engine = _engine if id is None: base_seed = db_url or str(db_engine.url) # type: ignore schema_suffix = db_schema if db_schema is not None else "ai" seed = f"{base_seed}#{schema_suffix}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, culture_table=culture_table, traces_table=traces_table, spans_table=spans_table, versions_table=versions_table, components_table=components_table, component_configs_table=component_configs_table, component_links_table=component_links_table, learnings_table=learnings_table, schedules_table=schedules_table, schedule_runs_table=schedule_runs_table, approvals_table=approvals_table, ) self.db_schema: str = db_schema if db_schema is not None else "ai" self.metadata: MetaData = MetaData(schema=self.db_schema) self.create_schema: bool = create_schema # Initialize database session self.Session: scoped_session = scoped_session(sessionmaker(bind=self.db_engine, expire_on_commit=False)) # -- Serialization methods -- def to_dict(self): base = super().to_dict() base.update( { "db_url": self.db_url, "db_schema": self.db_schema, "type": "postgres", } ) return base @classmethod def from_dict(cls, data): return cls( db_url=data.get("db_url"), db_schema=data.get("db_schema"), session_table=data.get("session_table"), culture_table=data.get("culture_table"), memory_table=data.get("memory_table"), metrics_table=data.get("metrics_table"), eval_table=data.get("eval_table"), knowledge_table=data.get("knowledge_table"), traces_table=data.get("traces_table"), spans_table=data.get("spans_table"), versions_table=data.get("versions_table"), components_table=data.get("components_table"), component_configs_table=data.get("component_configs_table"), component_links_table=data.get("component_links_table"), learnings_table=data.get("learnings_table"), schedules_table=data.get("schedules_table"), schedule_runs_table=data.get("schedule_runs_table"), approvals_table=data.get("approvals_table"), id=data.get("id"), ) def close(self) -> None: """Close database connections and dispose of the connection pool. Should be called during application shutdown to properly release all database connections. """ if self.db_engine is not None: self.db_engine.dispose() # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a table with the given name exists in the Postgres database. Args: table_name: Name of the table to check Returns: bool: True if the table exists in the database, False otherwise """ with self.Session() as sess: return is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) def _create_all_tables(self): """Create all tables for the database.""" tables_to_create = [ (self.session_table_name, "sessions"), (self.memory_table_name, "memories"), (self.metrics_table_name, "metrics"), (self.eval_table_name, "evals"), (self.knowledge_table_name, "knowledge"), (self.versions_table_name, "versions"), (self.components_table_name, "components"), (self.component_configs_table_name, "component_configs"), (self.component_links_table_name, "component_links"), (self.learnings_table_name, "learnings"), (self.schedules_table_name, "schedules"), (self.schedule_runs_table_name, "schedule_runs"), (self.approvals_table_name, "approvals"), ] for table_name, table_type in tables_to_create: self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True) def _create_table(self, table_name: str, table_type: str) -> Table: """ Create a table with the appropriate schema based on the table type. Supports: - _unique_constraints: [{"name": "...", "columns": [...]}] - __primary_key__: ["col1", "col2", ...] - __foreign_keys__: [{"columns":[...], "ref_table":"...", "ref_columns":[...]}] - column-level foreign_key: "logical_table.column" (resolved via _resolve_* helpers) """ try: # Pass table names and db_schema for foreign key resolution table_schema = get_table_schema_definition( table_type, traces_table_name=self.trace_table_name, db_schema=self.db_schema, schedules_table_name=self.schedules_table_name, ).copy() columns: List[Column] = [] indexes: List[str] = [] # Extract special schema keys before iterating columns schema_unique_constraints = table_schema.pop("_unique_constraints", []) schema_primary_key = table_schema.pop("__primary_key__", None) schema_foreign_keys = table_schema.pop("__foreign_keys__", []) schema_composite_indexes = table_schema.pop("__composite_indexes__", []) # Build columns for col_name, col_config in table_schema.items(): column_args = [col_name, col_config["type"]()] column_kwargs: Dict[str, Any] = {} # Column-level PK only if no composite PK is defined if col_config.get("primary_key", False) and schema_primary_key is None: column_kwargs["primary_key"] = True if "nullable" in col_config: column_kwargs["nullable"] = col_config["nullable"] if "default" in col_config: column_kwargs["default"] = col_config["default"] if col_config.get("index", False): indexes.append(col_name) if col_config.get("unique", False): column_kwargs["unique"] = True # Single-column FK if "foreign_key" in col_config: fk_ref = self._resolve_fk_reference(col_config["foreign_key"]) fk_kwargs: Dict[str, Any] = {} if "ondelete" in col_config: fk_kwargs["ondelete"] = col_config["ondelete"] column_args.append(ForeignKey(fk_ref, **fk_kwargs)) columns.append(Column(*column_args, **column_kwargs)) # Create the table object table = Table(table_name, self.metadata, *columns, schema=self.db_schema) # Composite PK if schema_primary_key is not None: missing = [c for c in schema_primary_key if c not in table.c] if missing: raise ValueError(f"Composite PK references missing columns in {table_name}: {missing}") pk_constraint_name = f"{table_name}_pkey" table.append_constraint(PrimaryKeyConstraint(*schema_primary_key, name=pk_constraint_name)) # Composite FKs for fk_config in schema_foreign_keys: fk_columns = fk_config["columns"] ref_table_logical = fk_config["ref_table"] ref_columns = fk_config["ref_columns"] if len(fk_columns) != len(ref_columns): raise ValueError( f"Composite FK in {table_name} has mismatched columns/ref_columns: {fk_columns} vs {ref_columns}" ) missing = [c for c in fk_columns if c not in table.c] if missing: raise ValueError(f"Composite FK references missing columns in {table_name}: {missing}") resolved_ref_table = self._resolve_table_name(ref_table_logical) fk_constraint_name = f"{table_name}_{'_'.join(fk_columns)}_fkey" # IMPORTANT: since Table(schema=self.db_schema) is used, do NOT schema-qualify these targets. ref_column_strings = [f"{resolved_ref_table}.{col}" for col in ref_columns] table.append_constraint( ForeignKeyConstraint( fk_columns, ref_column_strings, name=fk_constraint_name, ) ) # Multi-column unique constraints for constraint in schema_unique_constraints: constraint_name = f"{table_name}_{constraint['name']}" constraint_columns = constraint["columns"] missing = [c for c in constraint_columns if c not in table.c] if missing: raise ValueError(f"Unique constraint references missing columns in {table_name}: {missing}") table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name)) # Indexes for idx_col in indexes: if idx_col not in table.c: raise ValueError(f"Index references missing column in {table_name}: {idx_col}") idx_name = f"idx_{table_name}_{idx_col}" Index(idx_name, table.c[idx_col]) # Correct way; do NOT append as constraint # Composite indexes for idx_config in schema_composite_indexes: idx_name = f"idx_{table_name}_{'_'.join(idx_config['columns'])}" idx_cols = [table.c[c] for c in idx_config["columns"]] Index(idx_name, *idx_cols) # Create schema if requested if self.create_schema: with self.Session() as sess, sess.begin(): create_schema(session=sess, db_schema=self.db_schema) # Create table table_created = False if not self.table_exists(table_name): table.create(self.db_engine, checkfirst=True) log_debug(f"Successfully created table '{self.db_schema}.{table_name}'") table_created = True else: log_debug(f"Table {self.db_schema}.{table_name} already exists, skipping creation") # Create indexes (Postgres) for idx in table.indexes: try: with self.Session() as sess: exists_query = text( "SELECT 1 FROM pg_indexes WHERE schemaname = :schema AND indexname = :index_name" ) exists = ( sess.execute(exists_query, {"schema": self.db_schema, "index_name": idx.name}).scalar() is not None ) if exists: log_debug( f"Index {idx.name} already exists in {self.db_schema}.{table_name}, skipping creation" ) continue idx.create(self.db_engine) log_debug(f"Created index: {idx.name} for table {self.db_schema}.{table_name}") except Exception as e: log_error(f"Error creating index {idx.name}: {e}") # Store the schema version for the created table if table_name != self.versions_table_name and table_created: latest_schema_version = MigrationManager(self).latest_schema_version self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public) return table except Exception as e: log_error(f"Could not create table {self.db_schema}.{table_name}: {e}") raise def _resolve_fk_reference(self, fk_ref: str) -> str: """ Resolve a simple foreign key reference to fully qualified name. Accepts: - "logical_table.column" -> "{schema}.{resolved_table}.{column}" - already-qualified refs -> returned as-is """ parts = fk_ref.split(".") if len(parts) == 2: table, column = parts resolved_table = self._resolve_table_name(table) return f"{self.db_schema}.{resolved_table}.{column}" return fk_ref def _resolve_table_name(self, logical_name: str) -> str: """ Resolve logical table name to configured table name. """ table_map = { "traces": self.trace_table_name, "spans": self.span_table_name, "sessions": self.session_table_name, "memories": self.memory_table_name, "metrics": self.metrics_table_name, "evals": self.eval_table_name, "knowledge": self.knowledge_table_name, "versions": self.versions_table_name, "components": self.components_table_name, "component_configs": self.component_configs_table_name, "component_links": self.component_links_table_name, } return table_map.get(logical_name, logical_name) def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Optional[Table]: if table_type == "sessions": self.session_table = self._get_or_create_table( table_name=self.session_table_name, table_type="sessions", create_table_if_not_found=create_table_if_not_found, ) return self.session_table if table_type == "memories": self.memory_table = self._get_or_create_table( table_name=self.memory_table_name, table_type="memories", create_table_if_not_found=create_table_if_not_found, ) return self.memory_table if table_type == "metrics": self.metrics_table = self._get_or_create_table( table_name=self.metrics_table_name, table_type="metrics", create_table_if_not_found=create_table_if_not_found, ) return self.metrics_table if table_type == "evals": self.eval_table = self._get_or_create_table( table_name=self.eval_table_name, table_type="evals", create_table_if_not_found=create_table_if_not_found, ) return self.eval_table if table_type == "knowledge": self.knowledge_table = self._get_or_create_table( table_name=self.knowledge_table_name, table_type="knowledge", create_table_if_not_found=create_table_if_not_found, ) return self.knowledge_table if table_type == "culture": self.culture_table = self._get_or_create_table( table_name=self.culture_table_name, table_type="culture", create_table_if_not_found=create_table_if_not_found, ) return self.culture_table if table_type == "versions": self.versions_table = self._get_or_create_table( table_name=self.versions_table_name, table_type="versions", create_table_if_not_found=create_table_if_not_found, ) return self.versions_table if table_type == "traces": self.traces_table = self._get_or_create_table( table_name=self.trace_table_name, table_type="traces", create_table_if_not_found=create_table_if_not_found, ) return self.traces_table if table_type == "spans": # Ensure traces table exists first (spans has FK to traces) if create_table_if_not_found: self._get_table(table_type="traces", create_table_if_not_found=True) self.spans_table = self._get_or_create_table( table_name=self.span_table_name, table_type="spans", create_table_if_not_found=create_table_if_not_found, ) return self.spans_table if table_type == "components": self.component_table = self._get_or_create_table( table_name=self.components_table_name, table_type="components", create_table_if_not_found=create_table_if_not_found, ) return self.component_table if table_type == "component_configs": self.component_configs_table = self._get_or_create_table( table_name=self.component_configs_table_name, table_type="component_configs", create_table_if_not_found=create_table_if_not_found, ) return self.component_configs_table if table_type == "component_links": self.component_links_table = self._get_or_create_table( table_name=self.component_links_table_name, table_type="component_links", create_table_if_not_found=create_table_if_not_found, ) return self.component_links_table if table_type == "learnings": self.learnings_table = self._get_or_create_table( table_name=self.learnings_table_name, table_type="learnings", create_table_if_not_found=create_table_if_not_found, ) return self.learnings_table if table_type == "schedules": self.schedules_table = self._get_or_create_table( table_name=self.schedules_table_name, table_type="schedules", create_table_if_not_found=create_table_if_not_found, ) return self.schedules_table if table_type == "schedule_runs": self.schedule_runs_table = self._get_or_create_table( table_name=self.schedule_runs_table_name, table_type="schedule_runs", create_table_if_not_found=create_table_if_not_found, ) return self.schedule_runs_table if table_type == "approvals": self.approvals_table = self._get_or_create_table( table_name=self.approvals_table_name, table_type="approvals", create_table_if_not_found=create_table_if_not_found, ) return self.approvals_table raise ValueError(f"Unknown table type: {table_type}") def _get_or_create_table( self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False ) -> Optional[Table]: """ Check if the table exists and is valid, else create it. Args: table_name (str): Name of the table to get or create table_type (str): Type of table (used to get schema definition) Returns: Optional[Table]: SQLAlchemy Table object representing the schema. """ with self.Session() as sess, sess.begin(): table_is_available = is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) if not table_is_available: if not create_table_if_not_found: return None return self._create_table(table_name=table_name, table_type=table_type) if not is_valid_table( db_engine=self.db_engine, table_name=table_name, table_type=table_type, db_schema=self.db_schema, ): raise ValueError(f"Table {self.db_schema}.{table_name} has an invalid schema") try: table = Table(table_name, self.metadata, schema=self.db_schema, autoload_with=self.db_engine) return table except Exception as e: log_error(f"Error loading existing table {self.db_schema}.{table_name}: {e}") raise def get_latest_schema_version(self, table_name: str): """Get the latest version of the database schema.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return "2.0.0" with self.Session() as sess: stmt = select(table) # Latest version for the given table stmt = stmt.where(table.c.table_name == table_name) stmt = stmt.order_by(table.c.version.desc()).limit(1) result = sess.execute(stmt).fetchone() if result is None: return "2.0.0" version_dict = dict(result._mapping) return version_dict.get("version") or "2.0.0" def upsert_schema_version(self, table_name: str, version: str) -> None: """Upsert the schema version into the database.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return current_datetime = datetime.now().isoformat() with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( table_name=table_name, version=version, created_at=current_datetime, # Store as ISO format string updated_at=current_datetime, ) # Update version if table_name already exists stmt = stmt.on_conflict_do_update( index_elements=["table_name"], set_=dict(version=version, updated_at=current_datetime), ) sess.execute(stmt) # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """ Delete a session from the database. Args: session_id (str): ID of the session to delete user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return False with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id == session_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No session found to delete with session_id: {session_id} in table {table.name}") return False else: log_debug(f"Successfully deleted session with session_id: {session_id} in table {table.name}") return True except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete all given sessions from the database. Can handle multiple session types in the same run. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id.in_(session_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) log_debug(f"Successfully deleted {result.rowcount} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Read a session from the database. Args: session_id (str): ID of the session to read. session_type (SessionType): Type of session to get. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.session_id == session_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) # Filter by session_type to ensure we get the correct session type session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type stmt = stmt.where(table.c.session_type == session_type_value) result = sess.execute(stmt).fetchone() if result is None: return None session = dict(result._mapping) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session table: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """ Get all sessions in the given table. Can filter by user_id and component_id. Args: session_type (Optional[SessionType]): The type of session to get. user_id (Optional[str]): The ID of the user to filter by. component_id (Optional[str]): The ID of the agent / workflow to filter by. start_timestamp (Optional[int]): The start timestamp to filter by. end_timestamp (Optional[int]): The end timestamp to filter by. session_name (Optional[str]): The name of the session to filter by. limit (Optional[int]): The maximum number of sessions to return. Defaults to None. page (Optional[int]): The page number to return. Defaults to None. sort_by (Optional[str]): The field to sort by. Defaults to None. sort_order (Optional[str]): The sort order. Defaults to None. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. Returns: Union[List[Session], Tuple[List[Dict], int]]: - When deserialize=True: List of Session objects - When deserialize=False: Tuple of (session dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if component_id is not None: if session_type == SessionType.AGENT: stmt = stmt.where(table.c.agent_id == component_id) elif session_type == SessionType.TEAM: stmt = stmt.where(table.c.team_id == component_id) elif session_type == SessionType.WORKFLOW: stmt = stmt.where(table.c.workflow_id == component_id) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) if session_name is not None: stmt = stmt.where( func.coalesce(table.c.session_data["session_name"].astext, "").ilike(f"%{session_name}%") ) if session_type is not None: session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type stmt = stmt.where(table.c.session_type == session_type_value) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) records = sess.execute(stmt).fetchall() if records is None: return [], 0 session = [dict(record._mapping) for record in records] if not deserialize: return session, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(record) for record in session] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(record) for record in session] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(record) for record in session] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session table: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name for the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during renaming. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess, sess.begin(): # Sanitize session_name to remove null bytes sanitized_session_name = sanitize_postgres_string(session_name) stmt = ( update(table) .where(table.c.session_id == session_id) .where(table.c.session_type == session_type.value) .values( session_data=func.cast( func.jsonb_set( func.cast(table.c.session_data, postgresql.JSONB), text("'{session_name}'"), func.to_jsonb(sanitized_session_name), ), postgresql.JSON, ) ) .returning(*table.c) ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt) row = result.fetchone() if not row: return None log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") session = dict(row._mapping) if not deserialize: return session # Return the appropriate session type if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """ Insert or update a session in the database. Args: session (Session): The session data to upsert. deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return None session_dict = session.to_dict() # Sanitize JSON/dict fields to remove null bytes from nested strings if session_dict.get("agent_data"): session_dict["agent_data"] = sanitize_postgres_strings(session_dict["agent_data"]) if session_dict.get("team_data"): session_dict["team_data"] = sanitize_postgres_strings(session_dict["team_data"]) if session_dict.get("workflow_data"): session_dict["workflow_data"] = sanitize_postgres_strings(session_dict["workflow_data"]) if session_dict.get("session_data"): session_dict["session_data"] = sanitize_postgres_strings(session_dict["session_data"]) if session_dict.get("summary"): session_dict["summary"] = sanitize_postgres_strings(session_dict["summary"]) if session_dict.get("metadata"): session_dict["metadata"] = sanitize_postgres_strings(session_dict["metadata"]) if session_dict.get("runs"): session_dict["runs"] = sanitize_postgres_strings(session_dict["runs"]) if isinstance(session, AgentSession): with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.AGENT.value, agent_id=session_dict.get("agent_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), agent_data=session_dict.get("agent_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["session_id"], set_=dict( agent_id=session_dict.get("agent_id"), user_id=session_dict.get("user_id"), agent_data=session_dict.get("agent_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ), where=(table.c.user_id == session_dict.get("user_id")) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return AgentSession.from_dict(session_dict) elif isinstance(session, TeamSession): with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.TEAM.value, team_id=session_dict.get("team_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), team_data=session_dict.get("team_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["session_id"], set_=dict( team_id=session_dict.get("team_id"), user_id=session_dict.get("user_id"), team_data=session_dict.get("team_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ), where=(table.c.user_id == session_dict.get("user_id")) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return TeamSession.from_dict(session_dict) elif isinstance(session, WorkflowSession): with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.WORKFLOW.value, workflow_id=session_dict.get("workflow_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), workflow_data=session_dict.get("workflow_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["session_id"], set_=dict( workflow_id=session_dict.get("workflow_id"), user_id=session_dict.get("user_id"), workflow_data=session_dict.get("workflow_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), runs=session_dict.get("runs"), updated_at=int(time.time()), ), where=(table.c.user_id == session_dict.get("user_id")) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None session_dict = dict(row._mapping) if session_dict is None or not deserialize: return session_dict return WorkflowSession.from_dict(session_dict) else: raise ValueError(f"Invalid session type: {session.session_type}") except Exception as e: log_error(f"Exception upserting into sessions table: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk insert or update multiple sessions. Args: sessions (List[Session]): The list of session data to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. preserve_updated_at (bool): If True, preserve the updated_at from the session object. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions Raises: Exception: If an error occurs during bulk upsert. """ try: if not sessions: return [] table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return [] # Group sessions by type for better handling agent_sessions = [s for s in sessions if isinstance(s, AgentSession)] team_sessions = [s for s in sessions if isinstance(s, TeamSession)] workflow_sessions = [s for s in sessions if isinstance(s, WorkflowSession)] results: List[Union[Session, Dict[str, Any]]] = [] # Bulk upsert agent sessions if agent_sessions: session_records = [] for agent_session in agent_sessions: session_dict = agent_session.to_dict() # Sanitize JSON/dict fields to remove null bytes from nested strings if session_dict.get("agent_data"): session_dict["agent_data"] = sanitize_postgres_strings(session_dict["agent_data"]) if session_dict.get("session_data"): session_dict["session_data"] = sanitize_postgres_strings(session_dict["session_data"]) if session_dict.get("summary"): session_dict["summary"] = sanitize_postgres_strings(session_dict["summary"]) if session_dict.get("metadata"): session_dict["metadata"] = sanitize_postgres_strings(session_dict["metadata"]) if session_dict.get("runs"): session_dict["runs"] = sanitize_postgres_strings(session_dict["runs"]) # Use preserved updated_at if flag is set (even if None), otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) session_records.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "runs": session_dict.get("runs"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) with self.Session() as sess, sess.begin(): stmt: Any = postgresql.insert(table) update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "session_id", "created_at"] } stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=update_columns, where=(table.c.user_id == stmt.excluded.user_id) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt, session_records) for row in result.fetchall(): session_dict = dict(row._mapping) if deserialize: deserialized_agent_session = AgentSession.from_dict(session_dict) if deserialized_agent_session is None: continue results.append(deserialized_agent_session) else: results.append(session_dict) # Bulk upsert team sessions if team_sessions: session_records = [] for team_session in team_sessions: session_dict = team_session.to_dict() # Sanitize JSON/dict fields to remove null bytes from nested strings if session_dict.get("team_data"): session_dict["team_data"] = sanitize_postgres_strings(session_dict["team_data"]) if session_dict.get("session_data"): session_dict["session_data"] = sanitize_postgres_strings(session_dict["session_data"]) if session_dict.get("summary"): session_dict["summary"] = sanitize_postgres_strings(session_dict["summary"]) if session_dict.get("metadata"): session_dict["metadata"] = sanitize_postgres_strings(session_dict["metadata"]) if session_dict.get("runs"): session_dict["runs"] = sanitize_postgres_strings(session_dict["runs"]) # Use preserved updated_at if flag is set (even if None), otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) session_records.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "runs": session_dict.get("runs"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table) update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "session_id", "created_at"] } stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=update_columns, where=(table.c.user_id == stmt.excluded.user_id) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt, session_records) for row in result.fetchall(): session_dict = dict(row._mapping) if deserialize: deserialized_team_session = TeamSession.from_dict(session_dict) if deserialized_team_session is None: continue results.append(deserialized_team_session) else: results.append(session_dict) # Bulk upsert workflow sessions if workflow_sessions: session_records = [] for workflow_session in workflow_sessions: session_dict = workflow_session.to_dict() # Sanitize JSON/dict fields to remove null bytes from nested strings if session_dict.get("workflow_data"): session_dict["workflow_data"] = sanitize_postgres_strings(session_dict["workflow_data"]) if session_dict.get("session_data"): session_dict["session_data"] = sanitize_postgres_strings(session_dict["session_data"]) if session_dict.get("summary"): session_dict["summary"] = sanitize_postgres_strings(session_dict["summary"]) if session_dict.get("metadata"): session_dict["metadata"] = sanitize_postgres_strings(session_dict["metadata"]) if session_dict.get("runs"): session_dict["runs"] = sanitize_postgres_strings(session_dict["runs"]) # Use preserved updated_at if flag is set (even if None), otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) session_records.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "runs": session_dict.get("runs"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table) update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "session_id", "created_at"] } stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=update_columns, where=(table.c.user_id == stmt.excluded.user_id) | (table.c.user_id.is_(None)), ).returning(table) result = sess.execute(stmt, session_records) for row in result.fetchall(): session_dict = dict(row._mapping) if deserialize: deserialized_workflow_session = WorkflowSession.from_dict(session_dict) if deserialized_workflow_session is None: continue results.append(deserialized_workflow_session) else: results.append(session_dict) return results except Exception as e: log_error(f"Exception bulk upserting sessions: {e}") return [] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Returns: bool: True if deletion was successful, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id == memory_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting user memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No user memories found with ids: {memory_ids}") else: log_debug(f"Successfully deleted {result.rowcount} user memories") except Exception as e: log_error(f"Error deleting user memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the database. Returns: List[str]: List of memory topics. """ try: table = self._get_table(table_type="memories") if table is None: return [] with self.Session() as sess, sess.begin(): # Filter out NULL topics and ensure topics is an array before extracting elements # jsonb_typeof returns 'array' for JSONB arrays conditions = [ table.c.topics.is_not(None), func.jsonb_typeof(table.c.topics) == "array", ] try: # jsonb_array_elements_text is a set-returning function that must be used with select_from stmt = select(func.jsonb_array_elements_text(table.c.topics).label("topic")) stmt = stmt.select_from(table) stmt = stmt.where(and_(*conditions)) result = sess.execute(stmt).fetchall() except ProgrammingError: # Retrying with json_array_elements_text. This works in older versions, # where the topics column was of type JSON instead of JSONB # For JSON (not JSONB), we use json_typeof json_conditions = [ table.c.topics.is_not(None), func.json_typeof(table.c.topics) == "array", ] stmt = select(func.json_array_elements_text(table.c.topics).label("topic")) stmt = stmt.select_from(table) stmt = stmt.where(and_(*json_conditions)) result = sess.execute(stmt).fetchall() # Extract topics from records - each record is a Row with a 'topic' attribute topics = [record.topic for record in result if record.topic is not None] return list(set(topics)) except Exception as e: log_error(f"Exception reading from memory table: {e}") return [] def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Returns: Union[UserMemory, Dict[str, Any], None]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.memory_id == memory_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if not result: return None memory_raw = dict(result._mapping) if not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. topics (Optional[List[str]]): The topics to filter by. search_content (Optional[str]): The content to search for. limit (Optional[int]): The maximum number of memories to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. Returns: Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of UserMemory objects - When deserialize=False: Tuple of (memory dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if topics is not None: for topic in topics: stmt = stmt.where(func.cast(table.c.topics, String).like(f'%"{topic}"%')) if search_content is not None: stmt = stmt.where(func.cast(table.c.memory, postgresql.TEXT).ilike(f"%{search_content}%")) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) memories_raw = [record._mapping for record in result] if not deserialize: return memories_raw, total_count return [UserMemory.from_dict(record) for record in memories_raw] except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_error(f"Exception deleting all memories: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. Example: ( [ { "user_id": "123", "total_memories": 10, "last_memory_updated_at": 1714560000, }, ], total_count: 1, ) """ try: table = self._get_table(table_type="memories") if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select( table.c.user_id, func.count(table.c.memory_id).label("total_memories"), func.max(table.c.updated_at).label("last_memory_updated_at"), ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) else: stmt = stmt.where(table.c.user_id.is_not(None)) stmt = stmt.group_by(table.c.user_id) stmt = stmt.order_by(func.max(table.c.updated_at).desc()) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Pagination if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [], 0 return [ { "user_id": record.user_id, # type: ignore "total_memories": record.total_memories, "last_memory_updated_at": record.last_memory_updated_at, } for record in result ], total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The user memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return None # Sanitize string fields to remove null bytes (PostgreSQL doesn't allow them) sanitized_input = sanitize_postgres_string(memory.input) sanitized_feedback = sanitize_postgres_string(memory.feedback) with self.Session() as sess, sess.begin(): if memory.memory_id is None: memory.memory_id = str(uuid4()) current_time = int(time.time()) stmt = postgresql.insert(table).values( memory_id=memory.memory_id, memory=memory.memory, input=sanitized_input, user_id=memory.user_id, agent_id=memory.agent_id, team_id=memory.team_id, topics=memory.topics, feedback=sanitized_feedback, created_at=memory.created_at, updated_at=memory.updated_at if memory.updated_at is not None else (memory.created_at if memory.created_at is not None else current_time), ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["memory_id"], set_=dict( memory=memory.memory, topics=memory.topics, input=sanitized_input, agent_id=memory.agent_id, team_id=memory.team_id, feedback=sanitized_feedback, updated_at=current_time, # Preserve created_at on update - don't overwrite existing value created_at=table.c.created_at, ), ).returning(table) result = sess.execute(stmt) row = result.fetchone() memory_raw = dict(row._mapping) if not memory_raw or not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk insert or update multiple memories in the database for improved performance. Args: memories (List[UserMemory]): The list of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. preserve_updated_at (bool): If True, preserve the updated_at from the memory object. If False (default), set updated_at to current time. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories Raises: Exception: If an error occurs during bulk upsert. """ try: if not memories: return [] table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return [] # Prepare memory records for bulk insert memory_records = [] current_time = int(time.time()) for memory in memories: if memory.memory_id is None: memory.memory_id = str(uuid4()) # Use preserved updated_at if flag is set (even if None), otherwise use current time updated_at = memory.updated_at if preserve_updated_at else current_time # Sanitize string fields to remove null bytes (PostgreSQL doesn't allow them) sanitized_input = sanitize_postgres_string(memory.input) sanitized_feedback = sanitize_postgres_string(memory.feedback) memory_records.append( { "memory_id": memory.memory_id, "memory": memory.memory, "input": sanitized_input, "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "topics": memory.topics, "feedback": sanitized_feedback, "created_at": memory.created_at, "updated_at": updated_at, } ) results: List[Union[UserMemory, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): insert_stmt = postgresql.insert(table) update_columns = { col.name: insert_stmt.excluded[col.name] for col in table.columns if col.name not in ["memory_id", "created_at"] # Don't update primary key or created_at } stmt = insert_stmt.on_conflict_do_update(index_elements=["memory_id"], set_=update_columns).returning( table ) result = sess.execute(stmt, memory_records) for row in result.fetchall(): memory_dict = dict(row._mapping) if deserialize: deserialized_memory = UserMemory.from_dict(memory_dict) if deserialized_memory is None: continue results.append(deserialized_memory) else: results.append(memory_dict) return results except Exception as e: log_error(f"Exception bulk upserting memories: {e}") return [] # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """ Get all sessions of all types (agent, team, workflow) as raw dictionaries. Args: start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None. end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None. Returns: List[Dict[str, Any]]: List of session dictionaries with session_type field. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] stmt = select( table.c.user_id, table.c.session_data, table.c.runs, table.c.created_at, table.c.session_type, ) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) with self.Session() as sess: result = sess.execute(stmt).fetchall() return [record._mapping for record in result] except Exception as e: log_error(f"Exception reading from sessions table: {e}") raise e def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]: """Get the first date for which metrics calculation is needed: 1. If there are metrics records, return the date of the first day without a complete metrics record. 2. If there are no metrics records, return the date of the first recorded session. 3. If there are no metrics records and no sessions records, return None. Args: table (Table): The table to get the starting date for. Returns: Optional[date]: The starting date for which metrics calculation is needed. """ with self.Session() as sess: stmt = select(table).order_by(table.c.date.desc()).limit(1) result = sess.execute(stmt).fetchone() # 1. Return the date of the first day without a complete metrics record. if result is not None: if result.completed: return result._mapping["date"] + timedelta(days=1) else: return result._mapping["date"] # 2. No metrics records. Return the date of the first recorded session. first_session, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) first_session_date = first_session[0]["created_at"] if first_session else None # type: ignore[index] # 3. No metrics records and no sessions records. Return None. if first_session_date is None: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics. Returns: Optional[list[dict]]: The calculated metrics. Raises: Exception: If an error occurs during metrics calculation. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return None starting_date = self._get_metrics_calculation_starting_date(table) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int( datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp() ) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()) .replace(tzinfo=timezone.utc) .timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: with self.Session() as sess, sess.begin(): results = bulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records) log_debug("Updated metrics calculations") return results except Exception as e: log_error(f"Exception refreshing metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range. Args: starting_date (Optional[date]): The starting date to filter metrics by. ending_date (Optional[date]): The ending date to filter metrics by. Returns: Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return [], None with self.Session() as sess, sess.begin(): stmt = select(table) if starting_date: stmt = stmt.where(table.c.date >= starting_date) if ending_date: stmt = stmt.where(table.c.date <= ending_date) result = sess.execute(stmt).fetchall() if not result: return [], None # Get the latest updated_at latest_stmt = select(func.max(table.c.updated_at)) latest_updated_at = sess.execute(latest_stmt).scalar() return [row._mapping for row in result], latest_updated_at except Exception as e: log_error(f"Exception getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. """ try: table = self._get_table(table_type="knowledge") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.id == id) sess.execute(stmt) except Exception as e: log_error(f"Exception deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. """ try: table = self._get_table(table_type="knowledge") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None return KnowledgeRow.model_validate(result._mapping) except Exception as e: log_error(f"Exception getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: List[KnowledgeRow]: The knowledge contents. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="knowledge") if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select(table) # Apply linked_to filter if provided if linked_to is not None: stmt = stmt.where(table.c.linked_to == linked_to) # Apply sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Get total count before applying limit and pagination count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Apply pagination after count if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count except Exception as e: log_error(f"Exception getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ try: table = self._get_table(table_type="knowledge", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): # Get the actual table columns to avoid "unconsumed column names" error table_columns = set(table.columns.keys()) # Only include fields that exist in the table and are not None insert_data = {} update_fields = {} # Map of KnowledgeRow fields to table columns field_mapping = { "id": "id", "name": "name", "description": "description", "metadata": "metadata", "type": "type", "size": "size", "linked_to": "linked_to", "access_count": "access_count", "status": "status", "status_message": "status_message", "created_at": "created_at", "updated_at": "updated_at", "external_id": "external_id", } # Build insert and update data only for fields that exist in the table # String fields that need sanitization string_fields = {"name", "description", "type", "status", "status_message", "external_id", "linked_to"} for model_field, table_column in field_mapping.items(): if table_column in table_columns: value = getattr(knowledge_row, model_field, None) if value is not None: # Sanitize string fields to remove null bytes if table_column in string_fields and isinstance(value, str): value = sanitize_postgres_string(value) # Sanitize metadata dict if present elif table_column == "metadata" and isinstance(value, dict): value = sanitize_postgres_strings(value) insert_data[table_column] = value # Don't include ID in update_fields since it's the primary key if table_column != "id": update_fields[table_column] = value # Ensure id is always included for the insert if "id" in table_columns and knowledge_row.id: insert_data["id"] = knowledge_row.id # Handle case where update_fields is empty (all fields are None or don't exist in table) if not update_fields: # If we have insert_data, just do an insert without conflict resolution if insert_data: stmt = postgresql.insert(table).values(insert_data) sess.execute(stmt) else: # If we have no data at all, this is an error log_error("No valid fields found for knowledge row upsert") return None else: # Normal upsert with conflict resolution stmt = ( postgresql.insert(table) .values(insert_data) .on_conflict_do_update(index_elements=["id"], set_=update_fields) ) sess.execute(stmt) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge row: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run, or None if the operation fails. Raises: Exception: If an error occurs during creation. """ try: table = self._get_table(table_type="evals", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): current_time = int(time.time()) eval_data = eval_run.model_dump() # Sanitize string fields in eval_run if eval_data.get("name"): eval_data["name"] = sanitize_postgres_string(eval_data["name"]) if eval_data.get("evaluated_component_name"): eval_data["evaluated_component_name"] = sanitize_postgres_string( eval_data["evaluated_component_name"] ) # Sanitize nested dicts/JSON fields if eval_data.get("eval_data"): eval_data["eval_data"] = sanitize_postgres_strings(eval_data["eval_data"]) if eval_data.get("eval_input"): eval_data["eval_input"] = sanitize_postgres_strings(eval_data["eval_input"]) stmt = postgresql.insert(table).values( {"created_at": current_time, "updated_at": current_time, **eval_data} ) sess.execute(stmt) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database. Args: eval_run_id (str): The ID of the eval run to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id == eval_run_id) result = sess.execute(stmt) if result.rowcount == 0: log_warning(f"No eval run found with ID: {eval_run_id}") else: log_debug(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database. Args: eval_run_ids (List[str]): List of eval run IDs to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id.in_(eval_run_ids)) result = sess.execute(stmt) if result.rowcount == 0: log_warning(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {result.rowcount} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.run_id == eval_run_id) result = sess.execute(stmt).fetchone() if result is None: return None eval_run_raw = dict(result._mapping) if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by. filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow). deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of dictionaries Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if model_id is not None: stmt = stmt.where(table.c.model_id == model_id) if eval_type is not None and len(eval_type) > 0: stmt = stmt.where(table.c.eval_type.in_(eval_type)) if filter_type is not None: if filter_type == EvalFilterType.AGENT: stmt = stmt.where(table.c.agent_id.is_not(None)) elif filter_type == EvalFilterType.TEAM: stmt = stmt.where(table.c.team_id.is_not(None)) elif filter_type == EvalFilterType.WORKFLOW: stmt = stmt.where(table.c.workflow_id.is_not(None)) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting if sort_by is None: stmt = stmt.order_by(table.c.created_at.desc()) else: stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) eval_runs_raw = [row._mapping for row in result] if not deserialize: return eval_runs_raw, total_count return [EvalRunRecord.model_validate(row) for row in eval_runs_raw] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Upsert the name of an eval run in the database, returning raw dictionary. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. Returns: Optional[Dict[str, Any]]: The updated eval run, or None if the operation fails. Raises: Exception: If an error occurs during update. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): # Sanitize string field to remove null bytes sanitized_name = sanitize_postgres_string(name) stmt = ( table.update() .where(table.c.run_id == eval_run_id) .values(name=sanitized_name, updated_at=int(time.time())) ) sess.execute(stmt) eval_run_raw = self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize) if not eval_run_raw or not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Error upserting eval run name {eval_run_id}: {e}") raise e # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_warning(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.id == id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted cultural knowledge id: {id}") else: log_debug(f"No cultural knowledge found with id: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to get. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge entry, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None db_row = dict(result._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge(db_row) except Exception as e: log_error(f"Exception reading from cultural knowledge table: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from the database as CulturalKnowledge objects. Args: name (Optional[str]): The name of the cultural knowledge to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. limit (Optional[int]): The maximum number of cultural knowledge entries to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: List of CulturalKnowledge dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if name is not None: stmt = stmt.where(table.c.name == name) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) db_rows = [dict(record._mapping) for record in result] if not deserialize: return db_rows, total_count return [deserialize_cultural_knowledge(row) for row in db_rows] except Exception as e: log_error(f"Error reading from cultural knowledge table: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into the database. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[CulturalKnowledge]: The upserted cultural knowledge entry. Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="culture", create_table_if_not_found=True) if table is None: return None if cultural_knowledge.id is None: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a JSON dict for DB storage content_dict = serialize_cultural_knowledge(cultural_knowledge) # Sanitize content_dict to remove null bytes from nested strings if content_dict: content_dict = cast(Dict[str, Any], sanitize_postgres_strings(content_dict)) # Sanitize string fields to remove null bytes (PostgreSQL doesn't allow them) sanitized_name = sanitize_postgres_string(cultural_knowledge.name) sanitized_summary = sanitize_postgres_string(cultural_knowledge.summary) sanitized_input = sanitize_postgres_string(cultural_knowledge.input) with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( id=cultural_knowledge.id, name=sanitized_name, summary=sanitized_summary, content=content_dict if content_dict else None, metadata=sanitize_postgres_strings(cultural_knowledge.metadata) if cultural_knowledge.metadata else None, input=sanitized_input, created_at=cultural_knowledge.created_at, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["id"], set_=dict( name=sanitized_name, summary=sanitized_summary, content=content_dict if content_dict else None, metadata=sanitize_postgres_strings(cultural_knowledge.metadata) if cultural_knowledge.metadata else None, input=sanitized_input, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None db_row = dict(row._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge(db_row) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # -- Migrations -- def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str): """Migrate all content in the given table to the right v2 table""" from agno.db.migrations.v1_to_v2 import ( get_all_table_content, parse_agent_sessions, parse_memories, parse_team_sessions, parse_workflow_sessions, ) # Get all content from the old table old_content: list[dict[str, Any]] = get_all_table_content( db=self, db_schema=v1_db_schema, table_name=v1_table_name, ) if not old_content: log_info(f"No content to migrate from table {v1_table_name}") return # Parse the content into the new format memories: List[UserMemory] = [] sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = [] if v1_table_type == "agent_sessions": sessions = parse_agent_sessions(old_content) elif v1_table_type == "team_sessions": sessions = parse_team_sessions(old_content) elif v1_table_type == "workflow_sessions": sessions = parse_workflow_sessions(old_content) elif v1_table_type == "memories": memories = parse_memories(old_content) else: raise ValueError(f"Invalid table type: {v1_table_type}") # Insert the new content into the new table if v1_table_type == "agent_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table_name}") elif v1_table_type == "team_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table_name}") elif v1_table_type == "workflow_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table_name}") elif v1_table_type == "memories": for memory in memories: self.upsert_user_memory(memory) log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}") # --- Traces --- def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None): """Build base query for traces with aggregated span counts. Args: table: The traces table. spans_table: The spans table (optional). Returns: SQLAlchemy select statement with total_spans and error_count calculated dynamically. """ from sqlalchemy import case, literal if spans_table is not None: # JOIN with spans table to calculate total_spans and error_count return ( select( table, func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"), func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label( "error_count" ), ) .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id)) .group_by(table.c.trace_id) ) else: # Fallback if spans table doesn't exist return select(table, literal(0).label("total_spans"), literal(0).label("error_count")) def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col): """Build a SQL CASE expression that returns the component level for a trace. Component levels (higher = more important): - 3: Workflow root (.run or .arun with workflow_id) - 2: Team root (.run or .arun with team_id) - 1: Agent root (.run or .arun with agent_id) - 0: Child span (not a root) Args: workflow_id_col: SQL column/expression for workflow_id team_id_col: SQL column/expression for team_id agent_id_col: SQL column/expression for agent_id name_col: SQL column/expression for name Returns: SQLAlchemy CASE expression returning the component level as an integer. """ is_root_name = or_(name_col.contains(".run"), name_col.contains(".arun")) return case( # Workflow root (level 3) (and_(workflow_id_col.isnot(None), is_root_name), 3), # Team root (level 2) (and_(team_id_col.isnot(None), is_root_name), 2), # Agent root (level 1) (and_(agent_id_col.isnot(None), is_root_name), 1), # Child span or unknown (level 0) else_=0, ) def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Uses INSERT ... ON CONFLICT DO UPDATE (upsert) to handle concurrent inserts atomically and avoid race conditions. Args: trace: The Trace object to store (one per trace_id). """ try: table = self._get_table(table_type="traces", create_table_if_not_found=True) if table is None: return trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) # Sanitize string fields and nested JSON structures if trace_dict.get("name"): trace_dict["name"] = sanitize_postgres_string(trace_dict["name"]) if trace_dict.get("status"): trace_dict["status"] = sanitize_postgres_string(trace_dict["status"]) # Sanitize any nested dict/JSON fields trace_dict = cast(Dict[str, Any], sanitize_postgres_strings(trace_dict)) with self.Session() as sess, sess.begin(): # Use upsert to handle concurrent inserts atomically # On conflict, update fields while preserving existing non-null context values # and keeping the earliest start_time insert_stmt = postgresql.insert(table).values(trace_dict) # Build component level expressions for comparing trace priority new_level = self._get_trace_component_level_expr( insert_stmt.excluded.workflow_id, insert_stmt.excluded.team_id, insert_stmt.excluded.agent_id, insert_stmt.excluded.name, ) existing_level = self._get_trace_component_level_expr( table.c.workflow_id, table.c.team_id, table.c.agent_id, table.c.name, ) # Build the ON CONFLICT DO UPDATE clause # Use LEAST for start_time, GREATEST for end_time to capture full trace duration # Use COALESCE to preserve existing non-null context values upsert_stmt = insert_stmt.on_conflict_do_update( index_elements=["trace_id"], set_={ "end_time": func.greatest(table.c.end_time, insert_stmt.excluded.end_time), "start_time": func.least(table.c.start_time, insert_stmt.excluded.start_time), "duration_ms": func.extract( "epoch", func.cast( func.greatest(table.c.end_time, insert_stmt.excluded.end_time), TIMESTAMP(timezone=True), ) - func.cast( func.least(table.c.start_time, insert_stmt.excluded.start_time), TIMESTAMP(timezone=True), ), ) * 1000, "status": insert_stmt.excluded.status, # Update name only if new trace is from a higher-level component # Priority: workflow (3) > team (2) > agent (1) > child spans (0) "name": case( (new_level > existing_level, insert_stmt.excluded.name), else_=table.c.name, ), # Preserve existing non-null context values using COALESCE "run_id": func.coalesce(insert_stmt.excluded.run_id, table.c.run_id), "session_id": func.coalesce(insert_stmt.excluded.session_id, table.c.session_id), "user_id": func.coalesce(insert_stmt.excluded.user_id, table.c.user_id), "agent_id": func.coalesce(insert_stmt.excluded.agent_id, table.c.agent_id), "team_id": func.coalesce(insert_stmt.excluded.team_id, table.c.team_id), "workflow_id": func.coalesce(insert_stmt.excluded.workflow_id, table.c.workflow_id), }, ) sess.execute(upsert_stmt) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace table = self._get_table(table_type="traces") if table is None: return None # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build query with aggregated span counts stmt = self._get_traces_base_query(table, spans_table) if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) elif run_id: stmt = stmt.where(table.c.run_id == run_id) else: log_debug("get_trace called without any filter parameters") return None # Order by most recent and get first result stmt = stmt.order_by(table.c.start_time.desc()).limit(1) result = sess.execute(stmt).fetchone() if result: return Trace.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build base query with aggregated span counts base_stmt = self._get_traces_base_query(table, spans_table) # Apply filters if run_id: base_stmt = base_stmt.where(table.c.run_id == run_id) if session_id: base_stmt = base_stmt.where(table.c.session_id == session_id) if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if status: base_stmt = base_stmt.where(table.c.status == status) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat()) # Apply advanced filter expression if filter_expr: try: from agno.db.filter_converter import TRACE_COLUMNS, filter_expr_to_sqlalchemy base_stmt = base_stmt.where( filter_expr_to_sqlalchemy(filter_expr, table, allowed_columns=TRACE_COLUMNS) ) except ValueError: # Re-raise ValueError for proper 400 response at API layer raise except (KeyError, TypeError) as e: raise ValueError(f"Invalid filter expression: {e}") from e # Get total count count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() traces = [Trace.from_dict(dict(row._mapping)) for row in results] return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, first_trace_at, last_trace_at. """ try: table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 with self.Session() as sess: # Build base query grouped by session_id base_stmt = ( select( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id, func.count(table.c.trace_id).label("total_traces"), func.min(table.c.created_at).label("first_trace_at"), func.max(table.c.created_at).label("last_trace_at"), ) .where(table.c.session_id.isnot(None)) # Only sessions with session_id .group_by( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id ) ) # Apply filters if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat()) # Apply advanced filter expression if filter_expr: try: from agno.db.filter_converter import TRACE_COLUMNS, filter_expr_to_sqlalchemy base_stmt = base_stmt.where( filter_expr_to_sqlalchemy(filter_expr, table, allowed_columns=TRACE_COLUMNS) ) except ValueError: # Re-raise ValueError for proper 400 response at API layer raise except (KeyError, TypeError) as e: raise ValueError(f"Invalid filter expression: {e}") from e # Get total count of sessions count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination and ordering offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() # Convert to list of dicts with datetime objects stats_list = [] for row in results: # Convert ISO strings to datetime objects first_trace_at_str = row.first_trace_at last_trace_at_str = row.last_trace_at # Parse ISO format strings to datetime objects first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) stats_list.append( { "session_id": row.session_id, "user_id": row.user_id, "agent_id": row.agent_id, "team_id": row.team_id, "workflow_id": row.workflow_id, "total_traces": row.total_traces, "first_trace_at": first_trace_at, "last_trace_at": last_trace_at, } ) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): span_dict = span.to_dict() # Sanitize string fields and nested JSON structures if span_dict.get("name"): span_dict["name"] = sanitize_postgres_string(span_dict["name"]) if span_dict.get("status_code"): span_dict["status_code"] = sanitize_postgres_string(span_dict["status_code"]) # Sanitize any nested dict/JSON fields span_dict = cast(Dict[str, Any], sanitize_postgres_strings(span_dict)) stmt = postgresql.insert(table).values(span_dict) sess.execute(stmt) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): for span in spans: span_dict = span.to_dict() # Sanitize string fields and nested JSON structures if span_dict.get("name"): span_dict["name"] = sanitize_postgres_string(span_dict["name"]) if span_dict.get("status_code"): span_dict["status_code"] = sanitize_postgres_string(span_dict["status_code"]) # Sanitize any nested dict/JSON fields span_dict = sanitize_postgres_strings(span_dict) stmt = postgresql.insert(table).values(span_dict) sess.execute(stmt) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.span_id == span_id) result = sess.execute(stmt).fetchone() if result: return Span.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return [] with self.Session() as sess: stmt = select(table) # Apply filters if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) if parent_span_id: stmt = stmt.where(table.c.parent_span_id == parent_span_id) if limit: stmt = stmt.limit(limit) results = sess.execute(stmt).fetchall() return [Span.from_dict(dict(row._mapping)) for row in results] except Exception as e: log_error(f"Error getting spans: {e}") return [] # --- Components --- def get_component( self, component_id: str, component_type: Optional[ComponentType] = None, ) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="components") if table is None: return None with self.Session() as sess: stmt = select(table).where( table.c.component_id == component_id, table.c.deleted_at.is_(None), ) if component_type is not None: stmt = stmt.where(table.c.component_type == component_type.value) row = sess.execute(stmt).mappings().one_or_none() return dict(row) if row else None except Exception as e: log_error(f"Error getting component: {e}") raise def upsert_component( self, component_id: str, component_type: Optional[ComponentType] = None, name: Optional[str] = None, description: Optional[str] = None, current_version: Optional[int] = None, metadata: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Create or update a component. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). Required for create, optional for update. name: Display name. description: Optional description. current_version: Optional current version. metadata: Optional metadata dict. Returns: Created/updated component dictionary. Raises: ValueError: If creating and component_type is not provided. """ try: table = self._get_table(table_type="components", create_table_if_not_found=True) if table is None: raise ValueError("Components table not found") with self.Session() as sess, sess.begin(): existing = sess.execute( select(table).where( table.c.component_id == component_id, table.c.deleted_at.is_(None), ) ).fetchone() if existing is None: # Create new component if component_type is None: raise ValueError("component_type is required when creating a new component") sess.execute( table.insert().values( component_id=component_id, component_type=component_type.value, name=name, description=description, current_version=None, metadata=metadata, created_at=int(time.time()), ) ) log_debug(f"Created component {component_id}") elif existing.deleted_at is not None: # Reactivate soft-deleted if component_type is None: raise ValueError("component_type is required when reactivating a deleted component") sess.execute( table.update() .where(table.c.component_id == component_id) .values( component_type=component_type.value, name=name or component_id, description=description, current_version=None, metadata=metadata, updated_at=int(time.time()), deleted_at=None, ) ) log_debug(f"Reactivated component {component_id}") else: # Update existing updates: Dict[str, Any] = {"updated_at": int(time.time())} if component_type is not None: updates["component_type"] = component_type.value if name is not None: updates["name"] = name if description is not None: updates["description"] = description if current_version is not None: updates["current_version"] = current_version if metadata is not None: updates["metadata"] = metadata sess.execute(table.update().where(table.c.component_id == component_id).values(**updates)) log_debug(f"Updated component {component_id}") result = self.get_component(component_id) if result is None: raise ValueError(f"Failed to get component {component_id} after upsert") return result except Exception as e: log_error(f"Error upserting component: {e}") raise def delete_component( self, component_id: str, hard_delete: bool = False, ) -> bool: """Delete a component and all its configs/links. Args: component_id: The component ID. hard_delete: If True, permanently delete. Otherwise soft-delete. Returns: True if deleted, False if not found or already deleted. """ try: components_table = self._get_table(table_type="components") configs_table = self._get_table(table_type="component_configs") links_table = self._get_table(table_type="component_links") if components_table is None: return False with self.Session() as sess, sess.begin(): # Verify component exists (and not already soft-deleted for soft-delete) if hard_delete: exists = sess.execute( select(components_table.c.component_id).where(components_table.c.component_id == component_id) ).scalar_one_or_none() else: exists = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).scalar_one_or_none() if exists is None: log_error(f"Component {component_id} not found") return False if hard_delete: # Delete links where this component is parent or child if links_table is not None: sess.execute(links_table.delete().where(links_table.c.parent_component_id == component_id)) sess.execute(links_table.delete().where(links_table.c.child_component_id == component_id)) # Delete configs if configs_table is not None: sess.execute(configs_table.delete().where(configs_table.c.component_id == component_id)) # Delete component sess.execute(components_table.delete().where(components_table.c.component_id == component_id)) else: # Soft delete (preserve current_version for potential reactivation) sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(deleted_at=int(time.time())) ) return True except Exception as e: log_error(f"Error deleting component: {e}") raise def list_components( self, component_type: Optional[ComponentType] = None, include_deleted: bool = False, limit: int = 20, offset: int = 0, exclude_component_ids: Optional[Set[str]] = None, ) -> Tuple[List[Dict[str, Any]], int]: """List components with pagination. Args: component_type: Filter by type (agent|team|workflow). include_deleted: Include soft-deleted components. limit: Maximum number of items to return. offset: Number of items to skip. exclude_component_ids: Component IDs to exclude from results. Returns: Tuple of (list of component dicts, total count). """ try: table = self._get_table(table_type="components") if table is None: return [], 0 with self.Session() as sess: # Build base where clause where_clauses = [] if component_type is not None: where_clauses.append(table.c.component_type == component_type.value) if not include_deleted: where_clauses.append(table.c.deleted_at.is_(None)) if exclude_component_ids: where_clauses.append(table.c.component_id.notin_(exclude_component_ids)) # Get total count count_stmt = select(func.count()).select_from(table) for clause in where_clauses: count_stmt = count_stmt.where(clause) total_count = sess.execute(count_stmt).scalar() or 0 # Get paginated results stmt = select(table).order_by( table.c.created_at.desc(), table.c.component_id, ) for clause in where_clauses: stmt = stmt.where(clause) stmt = stmt.limit(limit).offset(offset) rows = sess.execute(stmt).mappings().all() return [dict(r) for r in rows], total_count except Exception as e: log_error(f"Error listing components: {e}") raise def create_component_with_config( self, component_id: str, component_type: ComponentType, name: Optional[str], config: Dict[str, Any], description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, label: Optional[str] = None, stage: str = "draft", notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """Create a component with its initial config atomically. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). name: Display name. config: The config data. description: Optional description. metadata: Optional metadata dict. label: Optional config label. stage: "draft" or "published". notes: Optional notes. links: Optional list of links. Each must have child_version set. Returns: Tuple of (component dict, config dict). Raises: ValueError: If component already exists, invalid stage, or link missing child_version. """ if stage not in {"draft", "published"}: raise ValueError(f"Invalid stage: {stage}") # Validate links have child_version if links: for link in links: if link.get("child_version") is None: raise ValueError(f"child_version is required for link to {link['child_component_id']}") try: components_table = self._get_table(table_type="components", create_table_if_not_found=True) configs_table = self._get_table(table_type="component_configs", create_table_if_not_found=True) links_table = self._get_table(table_type="component_links", create_table_if_not_found=True) if components_table is None: raise ValueError("Components table not found") if configs_table is None: raise ValueError("Component configs table not found") with self.Session() as sess, sess.begin(): # Check if component already exists existing = sess.execute( select(components_table.c.component_id).where(components_table.c.component_id == component_id) ).scalar_one_or_none() if existing is not None: raise ValueError(f"Component {component_id} already exists") # Check label uniqueness if label is not None: existing_label = sess.execute( select(configs_table.c.version).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) ).first() if existing_label: raise ValueError(f"Label '{label}' already exists for {component_id}") now = int(time.time()) version = 1 # Create component sess.execute( components_table.insert().values( component_id=component_id, component_type=component_type.value, name=name, description=description, metadata=metadata, current_version=version if stage == "published" else None, created_at=now, ) ) # Create initial config sess.execute( configs_table.insert().values( component_id=component_id, version=version, label=label, stage=stage, config=config, notes=notes, created_at=now, ) ) # Create links if provided if links and links_table is not None: for link in links: sess.execute( links_table.insert().values( parent_component_id=component_id, parent_version=version, link_kind=link["link_kind"], link_key=link["link_key"], child_component_id=link["child_component_id"], child_version=link["child_version"], position=link["position"], meta=link.get("meta"), created_at=now, ) ) # Fetch and return both component = self.get_component(component_id) config_result = self.get_config(component_id, version=version) if component is None: raise ValueError(f"Failed to get component {component_id} after creation") if config_result is None: raise ValueError(f"Failed to get config for {component_id} after creation") return component, config_result except Exception as e: log_error(f"Error creating component with config: {e}") raise # --- Component Configs --- def get_config( self, component_id: str, version: Optional[int] = None, label: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Get a config by component ID and version or label. Args: component_id: The component ID. version: Specific version number. If None, uses current or latest draft. label: Config label to lookup. Ignored if version is provided. Returns: Config dictionary or None if not found. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return None with self.Session() as sess: # Verify component exists and get current_version component_row = ( sess.execute( select(components_table.c.component_id, components_table.c.current_version).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ) .mappings() .one_or_none() ) if component_row is None: return None current_version = component_row["current_version"] if version is not None: stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) elif label is not None: stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) elif current_version is not None: # Use the current published version stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.version == current_version, ) else: # No current_version set (draft only) - get the latest version stmt = ( select(configs_table) .where(configs_table.c.component_id == component_id) .order_by(configs_table.c.version.desc()) .limit(1) ) row = sess.execute(stmt).mappings().one_or_none() return dict(row) if row else None except Exception as e: log_error(f"Error getting config: {e}") raise def upsert_config( self, component_id: str, config: Optional[Dict[str, Any]] = None, version: Optional[int] = None, label: Optional[str] = None, stage: Optional[str] = None, notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, Any]: """Create or update a config version for a component. Rules: - Draft configs can be edited freely - Published configs are immutable - Publishing a config automatically sets it as current_version Args: component_id: The component ID. config: The config data. Required for create, optional for update. version: If None, creates new version. If provided, updates that version. label: Optional human-readable label. stage: "draft" or "published". Defaults to "draft" for new configs. notes: Optional notes. links: Optional list of links. Each link must have child_version set. Returns: Created/updated config dictionary. Raises: ValueError: If component doesn't exist, version not found, label conflict, or attempting to update a published config. """ if stage is not None and stage not in {"draft", "published"}: raise ValueError(f"Invalid stage: {stage}") try: components_table = self._get_table(table_type="components") configs_table = self._get_table(table_type="component_configs", create_table_if_not_found=True) links_table = self._get_table(table_type="component_links", create_table_if_not_found=True) if components_table is None: raise ValueError("Components table not found") if configs_table is None: raise ValueError("Component configs table not found") with self.Session() as sess, sess.begin(): # Verify component exists and is not deleted component = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).scalar_one_or_none() if component is None: raise ValueError(f"Component {component_id} not found") # Label uniqueness check if label is not None: label_query = select(configs_table.c.version).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) if version is not None: label_query = label_query.where(configs_table.c.version != version) if sess.execute(label_query).first(): raise ValueError(f"Label '{label}' already exists for {component_id}") # Validate links have child_version if links: for link in links: if link.get("child_version") is None: raise ValueError(f"child_version is required for link to {link['child_component_id']}") if version is None: if config is None: raise ValueError("config is required when creating a new version") # Default to draft for new configs if stage is None: stage = "draft" max_version = sess.execute( select(configs_table.c.version) .where(configs_table.c.component_id == component_id) .order_by(configs_table.c.version.desc()) .limit(1) ).scalar() final_version = (max_version or 0) + 1 sess.execute( configs_table.insert().values( component_id=component_id, version=final_version, label=label, stage=stage, config=config, notes=notes, created_at=int(time.time()), ) ) else: existing = ( sess.execute( select(configs_table.c.version, configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ) .mappings() .one_or_none() ) if existing is None: raise ValueError(f"Config {component_id} v{version} not found") # Published configs are immutable if existing["stage"] == "published": raise ValueError(f"Cannot update published config {component_id} v{version}") # Build update dict with only provided fields updates: Dict[str, Any] = {"updated_at": int(time.time())} if label is not None: updates["label"] = label if stage is not None: updates["stage"] = stage if config is not None: updates["config"] = config if notes is not None: updates["notes"] = notes sess.execute( configs_table.update() .where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) .values(**updates) ) final_version = version if links is not None and links_table is not None: sess.execute( links_table.delete().where( links_table.c.parent_component_id == component_id, links_table.c.parent_version == final_version, ) ) for link in links: sess.execute( links_table.insert().values( parent_component_id=component_id, parent_version=final_version, link_kind=link["link_kind"], link_key=link["link_key"], child_component_id=link["child_component_id"], child_version=link["child_version"], position=link["position"], meta=link.get("meta"), created_at=int(time.time()), ) ) # Determine final stage (could be from update or create) final_stage = stage if stage is not None else (existing["stage"] if version is not None else "draft") if final_stage == "published": sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(current_version=final_version, updated_at=int(time.time())) ) result = self.get_config(component_id, version=final_version) if result is None: raise ValueError(f"Failed to get config {component_id} v{final_version} after upsert") return result except Exception as e: log_error(f"Error upserting config: {e}") raise def delete_config( self, component_id: str, version: int, ) -> bool: """Delete a specific config version. Only draft configs can be deleted. Published configs are immutable. Cannot delete the current version. Args: component_id: The component ID. version: The version to delete. Returns: True if deleted, False if not found. Raises: ValueError: If attempting to delete a published or current config. """ try: configs_table = self._get_table(table_type="component_configs") links_table = self._get_table(table_type="component_links") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return False with self.Session() as sess, sess.begin(): # Get config stage and check if it's current config_row = sess.execute( select(configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ).scalar_one_or_none() if config_row is None: return False # Check if it's current version current = sess.execute( select(components_table.c.current_version).where(components_table.c.component_id == component_id) ).scalar_one_or_none() if current == version: raise ValueError(f"Cannot delete current config {component_id} v{version}") # Delete associated links if links_table is not None: sess.execute( links_table.delete().where( links_table.c.parent_component_id == component_id, links_table.c.parent_version == version, ) ) # Delete the config sess.execute( configs_table.delete().where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ) return True except Exception as e: log_error(f"Error deleting config: {e}") raise def list_configs( self, component_id: str, include_config: bool = False, ) -> List[Dict[str, Any]]: """List all config versions for a component. Args: component_id: The component ID. include_config: If True, include full config blob. Otherwise just metadata. Returns: List of config dictionaries, newest first. Returns empty list if component not found or deleted. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return [] with self.Session() as sess: # Verify component exists and is not deleted exists = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).scalar_one_or_none() if exists is None: return [] # Select columns based on include_config flag if include_config: stmt = select(configs_table) else: stmt = select( configs_table.c.component_id, configs_table.c.version, configs_table.c.label, configs_table.c.stage, configs_table.c.notes, configs_table.c.created_at, configs_table.c.updated_at, ) stmt = stmt.where(configs_table.c.component_id == component_id).order_by(configs_table.c.version.desc()) results = sess.execute(stmt).mappings().all() return [dict(row) for row in results] except Exception as e: log_error(f"Error listing configs: {e}") raise def set_current_version( self, component_id: str, version: int, ) -> bool: """Set a specific published version as current. Only published configs can be set as current. This is used for rollback scenarios where you want to switch to a previous published version. Args: component_id: The component ID. version: The version to set as current (must be published). Returns: True if successful, False if component or version not found. Raises: ValueError: If attempting to set a draft config as current. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return False with self.Session() as sess, sess.begin(): # Verify component exists and is not deleted component_exists = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).scalar_one_or_none() if component_exists is None: return False # Verify version exists and get stage stage = sess.execute( select(configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ).scalar_one_or_none() if stage is None: return False # Only published configs can be set as current if stage != "published": raise ValueError( f"Cannot set draft config {component_id} v{version} as current. " "Only published configs can be current." ) # Update pointer result = sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(current_version=version, updated_at=int(time.time())) ) if result.rowcount == 0: return False log_debug(f"Set {component_id} current version to {version}") return True except Exception as e: log_error(f"Error setting current version: {e}") raise # --- Component Links --- def get_links( self, component_id: str, version: int, link_kind: Optional[str] = None, ) -> List[Dict[str, Any]]: """Get links for a config version. Args: component_id: The component ID. version: The config version. link_kind: Optional filter by link kind (member|step). Returns: List of link dictionaries, ordered by position. """ try: table = self._get_table(table_type="component_links") if table is None: return [] with self.Session() as sess: stmt = ( select(table) .where( table.c.parent_component_id == component_id, table.c.parent_version == version, ) .order_by(table.c.position) ) if link_kind is not None: stmt = stmt.where(table.c.link_kind == link_kind) rows = sess.execute(stmt).mappings().all() return [dict(r) for r in rows] except Exception as e: log_error(f"Error getting links: {e}") raise def get_dependents( self, component_id: str, version: Optional[int] = None, ) -> List[Dict[str, Any]]: """Find all components that reference this component. Args: component_id: The component ID to find dependents of. version: Optional specific version. If None, finds links to any version. Returns: List of link dictionaries showing what depends on this component. """ try: table = self._get_table(table_type="component_links") if table is None: return [] with self.Session() as sess: stmt = select(table).where(table.c.child_component_id == component_id) if version is not None: stmt = stmt.where(table.c.child_version == version) rows = sess.execute(stmt).mappings().all() return [dict(r) for r in rows] except Exception as e: log_error(f"Error getting dependents: {e}") raise def _resolve_version( self, component_id: str, version: Optional[int], ) -> Optional[int]: """Resolve a version number, handling None as 'current'. Args: component_id: The component ID. version: Version number or None for current. Returns: Resolved version number, or None if component missing/deleted or no current. """ if version is not None: return version try: components_table = self._get_table(table_type="components") if components_table is None: return None with self.Session() as sess: return sess.execute( select(components_table.c.current_version).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).scalar_one_or_none() except Exception as e: log_error(f"Error resolving version: {e}") raise def load_component_graph( self, component_id: str, version: Optional[int] = None, label: Optional[str] = None, *, _visited: Optional[Set[Tuple[str, int]]] = None, _max_depth: int = 50, ) -> Optional[Dict[str, Any]]: """Load a component with its full resolved graph. Handles cycles by returning a stub with cycle_detected=True. Has a max depth guard to prevent stack overflow. Args: component_id: The component ID. version: Specific version or None for current. label: Optional label of the component. _visited: Internal cycle tracking (do not pass). _max_depth: Internal depth limit (do not pass). Returns: Dictionary with component, config, children, and resolved_versions. Returns None if component not found or depth exceeded. """ try: if _max_depth <= 0: return None component = self.get_component(component_id) if component is None: return None resolved_version = self._resolve_version(component_id, version) if resolved_version is None: return None # Cycle detection if _visited is None: _visited = set() node_key = (component_id, resolved_version) if node_key in _visited: return { "component": component, "config": self.get_config(component_id, version=resolved_version), "children": [], "resolved_versions": {component_id: resolved_version}, "cycle_detected": True, } _visited.add(node_key) config = self.get_config(component_id, version=resolved_version) if config is None: return None links = self.get_links(component_id, resolved_version) children: List[Dict[str, Any]] = [] resolved_versions: Dict[str, Optional[int]] = {component_id: resolved_version} for link in links: child_id = link["child_component_id"] child_ver = link.get("child_version") resolved_child_ver = self._resolve_version(child_id, child_ver) resolved_versions[child_id] = resolved_child_ver if resolved_child_ver is None: children.append( { "link": link, "graph": None, "error": "child_version_unresolvable", } ) continue child_graph = self.load_component_graph( child_id, version=resolved_child_ver, _visited=_visited, _max_depth=_max_depth - 1, ) if child_graph: resolved_versions.update(child_graph.get("resolved_versions", {})) children.append({"link": link, "graph": child_graph}) return { "component": component, "config": config, "children": children, "resolved_versions": resolved_versions, } except Exception as e: log_error(f"Error loading component graph: {e}") raise # -- Learning methods -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Retrieve a learning record. Args: learning_type: Type of learning ('user_profile', 'session_context', etc.) user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). Returns: Dict with 'content' key containing the learning data, or None. """ try: table = self._get_table(table_type="learnings") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.learning_type == learning_type) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if session_id is not None: stmt = stmt.where(table.c.session_id == session_id) if namespace is not None: stmt = stmt.where(table.c.namespace == namespace) if entity_id is not None: stmt = stmt.where(table.c.entity_id == entity_id) if entity_type is not None: stmt = stmt.where(table.c.entity_type == entity_type) result = sess.execute(stmt).fetchone() if result is None: return None row = dict(result._mapping) return {"content": row.get("content")} except Exception as e: log_debug(f"Error retrieving learning: {e}") return None def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: """Insert or update a learning record. Args: id: Unique identifier for the learning. learning_type: Type of learning ('user_profile', 'session_context', etc.) content: The learning content as a dict. user_id: Associated user ID. agent_id: Associated agent ID. team_id: Associated team ID. workflow_id: Associated workflow ID. session_id: Associated session ID. namespace: Namespace for scoping ('user', 'global', or custom). entity_id: Associated entity ID (for entity-specific learnings). entity_type: Entity type ('person', 'company', etc.). metadata: Optional metadata. """ try: table = self._get_table(table_type="learnings", create_table_if_not_found=True) if table is None: return current_time = int(time.time()) with self.Session() as sess, sess.begin(): stmt = postgresql.insert(table).values( learning_id=id, learning_type=learning_type, namespace=namespace, user_id=user_id, agent_id=agent_id, team_id=team_id, workflow_id=workflow_id, session_id=session_id, entity_id=entity_id, entity_type=entity_type, content=content, metadata=metadata, created_at=current_time, updated_at=current_time, ) stmt = stmt.on_conflict_do_update( index_elements=["learning_id"], set_=dict( content=content, metadata=metadata, updated_at=current_time, ), ) sess.execute(stmt) log_debug(f"Upserted learning: {id}") except Exception as e: log_debug(f"Error upserting learning: {e}") def delete_learning(self, id: str) -> bool: """Delete a learning record. Args: id: The learning ID to delete. Returns: True if deleted, False otherwise. """ try: table = self._get_table(table_type="learnings") if table is None: return False with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.learning_id == id) result = sess.execute(stmt) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting learning: {e}") return False def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: """Get multiple learning records. Args: learning_type: Filter by learning type. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). limit: Maximum number of records to return. Returns: List of learning records. """ try: table = self._get_table(table_type="learnings") if table is None: return [] with self.Session() as sess: stmt = select(table) if learning_type is not None: stmt = stmt.where(table.c.learning_type == learning_type) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if session_id is not None: stmt = stmt.where(table.c.session_id == session_id) if namespace is not None: stmt = stmt.where(table.c.namespace == namespace) if entity_id is not None: stmt = stmt.where(table.c.entity_id == entity_id) if entity_type is not None: stmt = stmt.where(table.c.entity_type == entity_type) stmt = stmt.order_by(table.c.updated_at.desc()) if limit is not None: stmt = stmt.limit(limit) result = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in result] except Exception as e: log_debug(f"Error getting learnings: {e}") return [] # -- Schedule methods -- def get_schedule(self, schedule_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == schedule_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule: {e}") return None def get_schedule_by_name(self, name: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.name == name)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule by name: {e}") return None def get_schedules( self, enabled: Optional[bool] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="schedules") if table is None: return [], 0 with self.Session() as sess: # Build base query with filters base_query = select(table) if enabled is not None: base_query = base_query.where(table.c.enabled == enabled) # Get total count count_stmt = select(func.count()).select_from(base_query.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit # Get paginated results stmt = base_query.order_by(table.c.created_at.desc()).limit(limit).offset(offset) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total_count except Exception as e: log_debug(f"Error listing schedules: {e}") return [], 0 def create_schedule(self, schedule_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="schedules", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create schedules table") with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**schedule_data)) return schedule_data except Exception as e: log_error(f"Error creating schedule: {e}") raise def update_schedule(self, schedule_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None kwargs["updated_at"] = int(time.time()) with self.Session() as sess, sess.begin(): sess.execute(table.update().where(table.c.id == schedule_id).values(**kwargs)) return self.get_schedule(schedule_id) except Exception as e: log_debug(f"Error updating schedule: {e}") return None def delete_schedule(self, schedule_id: str) -> bool: try: table = self._get_table(table_type="schedules") if table is None: return False runs_table = self._get_table(table_type="schedule_runs") with self.Session() as sess, sess.begin(): if runs_table is not None: sess.execute(runs_table.delete().where(runs_table.c.schedule_id == schedule_id)) result = sess.execute(table.delete().where(table.c.id == schedule_id)) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting schedule: {e}") return False def claim_due_schedule(self, worker_id: str, lock_grace_seconds: int = 300) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None now = int(time.time()) stale_lock_threshold = now - lock_grace_seconds with self.Session() as sess, sess.begin(): # Atomic UPDATE...RETURNING with subquery for TOCTOU safety subq = ( select(table.c.id) .where( table.c.enabled == True, # noqa: E712 table.c.next_run_at <= now, or_( table.c.locked_by.is_(None), table.c.locked_at <= stale_lock_threshold, ), ) .order_by(table.c.next_run_at.asc()) .limit(1) .with_for_update(skip_locked=True) .scalar_subquery() ) stmt = ( update(table) .where(table.c.id == subq) .values(locked_by=worker_id, locked_at=now) .returning(*table.c) ) result = sess.execute(stmt).fetchone() if result is None: return None return dict(result._mapping) except Exception as e: log_debug(f"Error claiming schedule: {e}") return None def release_schedule(self, schedule_id: str, next_run_at: Optional[int] = None) -> bool: try: table = self._get_table(table_type="schedules") if table is None: return False updates: Dict[str, Any] = {"locked_by": None, "locked_at": None, "updated_at": int(time.time())} if next_run_at is not None: updates["next_run_at"] = next_run_at with self.Session() as sess, sess.begin(): result = sess.execute(table.update().where(table.c.id == schedule_id).values(**updates)) return result.rowcount > 0 except Exception as e: log_debug(f"Error releasing schedule: {e}") return False def create_schedule_run(self, run_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="schedule_runs", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create schedule_runs table") with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**run_data)) return run_data except Exception as e: log_error(f"Error creating schedule run: {e}") raise def update_schedule_run(self, schedule_run_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedule_runs") if table is None: return None with self.Session() as sess, sess.begin(): sess.execute(table.update().where(table.c.id == schedule_run_id).values(**kwargs)) return self.get_schedule_run(schedule_run_id) except Exception as e: log_debug(f"Error updating schedule run: {e}") return None def get_schedule_run(self, run_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedule_runs") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == run_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule run: {e}") return None def get_schedule_runs( self, schedule_id: str, limit: int = 20, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="schedule_runs") if table is None: return [], 0 with self.Session() as sess: # Get total count count_stmt = select(func.count()).select_from(table).where(table.c.schedule_id == schedule_id) total_count = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit # Get paginated results stmt = ( select(table) .where(table.c.schedule_id == schedule_id) .order_by(table.c.created_at.desc()) .limit(limit) .offset(offset) ) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total_count except Exception as e: log_debug(f"Error getting schedule runs: {e}") return [], 0 # -- Approval methods -- def create_approval(self, approval_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="approvals", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create approvals table") data = {**approval_data} now = int(time.time()) data.setdefault("created_at", now) data.setdefault("updated_at", now) with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**data)) return data except Exception as e: log_error(f"Error creating approval: {e}") raise def get_approval(self, approval_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="approvals") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == approval_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting approval: {e}") return None def get_approvals( self, status: Optional[str] = None, source_type: Optional[str] = None, approval_type: Optional[str] = None, pause_type: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, user_id: Optional[str] = None, schedule_id: Optional[str] = None, run_id: Optional[str] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="approvals") if table is None: return [], 0 with self.Session() as sess: stmt = select(table) count_stmt = select(func.count()).select_from(table) if status is not None: stmt = stmt.where(table.c.status == status) count_stmt = count_stmt.where(table.c.status == status) if source_type is not None: stmt = stmt.where(table.c.source_type == source_type) count_stmt = count_stmt.where(table.c.source_type == source_type) if approval_type is not None: stmt = stmt.where(table.c.approval_type == approval_type) count_stmt = count_stmt.where(table.c.approval_type == approval_type) if pause_type is not None: stmt = stmt.where(table.c.pause_type == pause_type) count_stmt = count_stmt.where(table.c.pause_type == pause_type) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) count_stmt = count_stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) count_stmt = count_stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) count_stmt = count_stmt.where(table.c.workflow_id == workflow_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) count_stmt = count_stmt.where(table.c.user_id == user_id) if schedule_id is not None: stmt = stmt.where(table.c.schedule_id == schedule_id) count_stmt = count_stmt.where(table.c.schedule_id == schedule_id) if run_id is not None: stmt = stmt.where(table.c.run_id == run_id) count_stmt = count_stmt.where(table.c.run_id == run_id) total = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit stmt = stmt.order_by(table.c.created_at.desc()).limit(limit).offset(offset) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total except Exception as e: log_debug(f"Error listing approvals: {e}") return [], 0 def update_approval( self, approval_id: str, expected_status: Optional[str] = None, **kwargs: Any ) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="approvals") if table is None: return None kwargs["updated_at"] = int(time.time()) with self.Session() as sess, sess.begin(): stmt = table.update().where(table.c.id == approval_id) if expected_status is not None: stmt = stmt.where(table.c.status == expected_status) result = sess.execute(stmt.values(**kwargs)) if result.rowcount == 0: return None return self.get_approval(approval_id) except Exception as e: log_debug(f"Error updating approval: {e}") return None def delete_approval(self, approval_id: str) -> bool: try: table = self._get_table(table_type="approvals") if table is None: return False with self.Session() as sess, sess.begin(): result = sess.execute(table.delete().where(table.c.id == approval_id)) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting approval: {e}") return False def get_pending_approval_count(self, user_id: Optional[str] = None) -> int: try: table = self._get_table(table_type="approvals") if table is None: return 0 with self.Session() as sess: stmt = select(func.count()).select_from(table).where(table.c.status == "pending") if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) return sess.execute(stmt).scalar() or 0 except Exception as e: log_debug(f"Error counting approvals: {e}") return 0 def update_approval_run_status(self, run_id: str, run_status: RunStatus) -> int: """Update run_status on all approvals for a given run_id. Args: run_id: The run ID to match. run_status: The new run status. Returns: Number of approvals updated. """ try: table = self._get_table(table_type="approvals") if table is None: return 0 with self.Session() as sess, sess.begin(): stmt = ( table.update() .where(table.c.run_id == run_id) .values(run_status=run_status.value, updated_at=int(time.time())) ) result = sess.execute(stmt) return result.rowcount except Exception as e: log_debug(f"Error updating approval run_status: {e}") return 0
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/postgres/postgres.py", "license": "Apache License 2.0", "lines": 4254, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/postgres/schemas.py
"""Table schemas and related utils used by the PostgresDb class""" from typing import Any try: from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.types import BigInteger, Boolean, Date, Integer, String, Text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") SESSION_TABLE_SCHEMA = { "session_id": {"type": String, "primary_key": True, "nullable": False}, "session_type": {"type": String, "nullable": False, "index": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "workflow_id": {"type": String, "nullable": True}, "user_id": {"type": String, "nullable": True}, "session_data": {"type": JSONB, "nullable": True}, "agent_data": {"type": JSONB, "nullable": True}, "team_data": {"type": JSONB, "nullable": True}, "workflow_data": {"type": JSONB, "nullable": True}, "metadata": {"type": JSONB, "nullable": True}, "runs": {"type": JSONB, "nullable": True}, "summary": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } MEMORY_TABLE_SCHEMA = { "memory_id": {"type": String, "primary_key": True, "nullable": False}, "memory": {"type": JSONB, "nullable": False}, "feedback": {"type": Text, "nullable": True}, "input": {"type": Text, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "user_id": {"type": String, "nullable": True, "index": True}, "topics": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True, "index": True}, } EVAL_TABLE_SCHEMA = { "run_id": {"type": String, "primary_key": True, "nullable": False}, "eval_type": {"type": String, "nullable": False}, "eval_data": {"type": JSONB, "nullable": False}, "eval_input": {"type": JSONB, "nullable": False}, "name": {"type": String, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "workflow_id": {"type": String, "nullable": True}, "model_id": {"type": String, "nullable": True}, "model_provider": {"type": String, "nullable": True}, "evaluated_component_name": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False}, "description": {"type": Text, "nullable": False}, "metadata": {"type": JSONB, "nullable": True}, "type": {"type": String, "nullable": True}, "size": {"type": BigInteger, "nullable": True}, "linked_to": {"type": String, "nullable": True}, "access_count": {"type": BigInteger, "nullable": True}, "status": {"type": String, "nullable": True}, "status_message": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "external_id": {"type": String, "nullable": True}, } METRICS_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "agent_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "agent_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "users_count": {"type": BigInteger, "nullable": False, "default": 0}, "token_metrics": {"type": JSONB, "nullable": False, "default": {}}, "model_metrics": {"type": JSONB, "nullable": False, "default": {}}, "date": {"type": Date, "nullable": False, "index": True}, "aggregation_period": {"type": String, "nullable": False}, "created_at": {"type": BigInteger, "nullable": False}, "updated_at": {"type": BigInteger, "nullable": True}, "completed": {"type": Boolean, "nullable": False, "default": False}, "_unique_constraints": [ { "name": "uq_metrics_date_period", "columns": ["date", "aggregation_period"], } ], } CULTURAL_KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False, "index": True}, "summary": {"type": Text, "nullable": True}, "content": {"type": JSONB, "nullable": True}, "metadata": {"type": JSONB, "nullable": True}, "input": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, } VERSIONS_TABLE_SCHEMA = { "table_name": {"type": String, "nullable": False, "primary_key": True}, "version": {"type": String, "nullable": False}, "created_at": {"type": String, "nullable": False, "index": True}, "updated_at": {"type": String, "nullable": True}, } TRACE_TABLE_SCHEMA = { "trace_id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False}, "status": {"type": String, "nullable": False, "index": True}, "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "run_id": {"type": String, "nullable": True, "index": True}, "session_id": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string } def _get_span_table_schema(traces_table_name: str = "agno_traces", db_schema: str = "agno") -> dict[str, Any]: """Get the span table schema with the correct foreign key reference. Args: traces_table_name: The name of the traces table to reference in the foreign key. db_schema: The database schema name. Returns: The span table schema dictionary. """ return { "span_id": {"type": String, "primary_key": True, "nullable": False}, "trace_id": { "type": String, "nullable": False, "index": True, "foreign_key": f"{db_schema}.{traces_table_name}.trace_id", }, "parent_span_id": {"type": String, "nullable": True, "index": True}, "name": {"type": String, "nullable": False}, "span_kind": {"type": String, "nullable": False}, "status_code": {"type": String, "nullable": False}, "status_message": {"type": Text, "nullable": True}, "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "attributes": {"type": JSONB, "nullable": True}, "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string } COMPONENT_TABLE_SCHEMA = { "component_id": {"type": String, "primary_key": True}, "component_type": {"type": String, "nullable": False, "index": True}, # agent|team|workflow "name": {"type": String, "nullable": True, "index": True}, "description": {"type": Text, "nullable": True}, "current_version": {"type": Integer, "nullable": True, "index": True}, "metadata": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "deleted_at": {"type": BigInteger, "nullable": True}, } COMPONENT_CONFIGS_TABLE_SCHEMA = { "component_id": {"type": String, "primary_key": True, "foreign_key": "components.component_id"}, "version": {"type": Integer, "primary_key": True}, "label": {"type": String, "nullable": True}, # stable|v1.2.0|pre-refactor "stage": {"type": String, "nullable": False, "default": "draft", "index": True}, # draft|published "config": {"type": JSONB, "nullable": False}, "notes": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "deleted_at": {"type": BigInteger, "nullable": True}, } COMPONENT_LINKS_TABLE_SCHEMA = { "parent_component_id": {"type": String, "nullable": False}, "parent_version": {"type": Integer, "nullable": False}, "link_kind": {"type": String, "nullable": False, "index": True}, "link_key": {"type": String, "nullable": False}, "child_component_id": {"type": String, "nullable": False, "foreign_key": "components.component_id"}, "child_version": {"type": Integer, "nullable": True}, "position": {"type": Integer, "nullable": False}, "meta": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "__primary_key__": ["parent_component_id", "parent_version", "link_kind", "link_key"], "__foreign_keys__": [ { "columns": ["parent_component_id", "parent_version"], "ref_table": "component_configs", "ref_columns": ["component_id", "version"], } ], } LEARNINGS_TABLE_SCHEMA = { "learning_id": {"type": String, "primary_key": True, "nullable": False}, "learning_type": {"type": String, "nullable": False, "index": True}, "namespace": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "session_id": {"type": String, "nullable": True, "index": True}, "entity_id": {"type": String, "nullable": True, "index": True}, "entity_type": {"type": String, "nullable": True, "index": True}, "content": {"type": JSONB, "nullable": False}, "metadata": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } SCHEDULE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False, "index": True}, "description": {"type": Text, "nullable": True}, "method": {"type": String, "nullable": False}, "endpoint": {"type": String, "nullable": False}, "payload": {"type": JSONB, "nullable": True}, "cron_expr": {"type": String, "nullable": False}, "timezone": {"type": String, "nullable": False}, "timeout_seconds": {"type": BigInteger, "nullable": False}, "max_retries": {"type": BigInteger, "nullable": False}, "retry_delay_seconds": {"type": BigInteger, "nullable": False}, "enabled": {"type": Boolean, "nullable": False, "default": True}, "next_run_at": {"type": BigInteger, "nullable": True, "index": True}, "locked_by": {"type": String, "nullable": True}, "locked_at": {"type": BigInteger, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "__composite_indexes__": [ {"name": "enabled_next_run_at", "columns": ["enabled", "next_run_at"]}, ], } def _get_schedule_runs_table_schema( schedules_table_name: str = "agno_schedules", db_schema: str = "agno" ) -> dict[str, Any]: """Get the schedule runs table schema with a foreign key to the schedules table.""" return { "id": {"type": String, "primary_key": True, "nullable": False}, "schedule_id": { "type": String, "nullable": False, "index": True, "foreign_key": f"{db_schema}.{schedules_table_name}.id", "ondelete": "CASCADE", }, "attempt": {"type": BigInteger, "nullable": False}, "triggered_at": {"type": BigInteger, "nullable": True}, "completed_at": {"type": BigInteger, "nullable": True}, "status": {"type": String, "nullable": False, "index": True}, "status_code": {"type": BigInteger, "nullable": True}, "run_id": {"type": String, "nullable": True}, "session_id": {"type": String, "nullable": True}, "error": {"type": Text, "nullable": True}, "input": {"type": JSONB, "nullable": True}, "output": {"type": JSONB, "nullable": True}, "requirements": {"type": JSONB, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, } APPROVAL_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "run_id": {"type": String, "nullable": False, "index": True}, "session_id": {"type": String, "nullable": False, "index": True}, "status": {"type": String, "nullable": False, "index": True}, "source_type": {"type": String, "nullable": False, "index": True}, "approval_type": {"type": String, "nullable": True, "index": True}, "pause_type": {"type": String, "nullable": False, "index": True}, "tool_name": {"type": String, "nullable": True}, "tool_args": {"type": JSONB, "nullable": True}, "expires_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "schedule_id": {"type": String, "nullable": True, "index": True}, "schedule_run_id": {"type": String, "nullable": True, "index": True}, "source_name": {"type": String, "nullable": True}, "requirements": {"type": JSONB, "nullable": True}, "context": {"type": JSONB, "nullable": True}, "resolution_data": {"type": JSONB, "nullable": True}, "resolved_by": {"type": String, "nullable": True}, "resolved_at": {"type": BigInteger, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, # Run status from the associated run. Updated when run completes/errors/cancels. # Values: "PAUSED", "COMPLETED", "RUNNING", "ERROR", "CANCELLED", or None. "run_status": {"type": String, "nullable": True, "index": True}, } def get_table_schema_definition( table_type: str, traces_table_name: str = "agno_traces", db_schema: str = "agno", schedules_table_name: str = "agno_schedules", ) -> dict[str, Any]: """ Get the expected schema definition for the given table. Args: table_type (str): The type of table to get the schema for. traces_table_name (str): The name of the traces table (used for spans foreign key). db_schema (str): The database schema name (used for spans foreign key). Returns: Dict[str, Any]: Dictionary containing column definitions for the table """ # Handle tables with dynamic foreign key references if table_type == "spans": return _get_span_table_schema(traces_table_name, db_schema) if table_type == "schedule_runs": return _get_schedule_runs_table_schema(schedules_table_name, db_schema) schemas = { "sessions": SESSION_TABLE_SCHEMA, "evals": EVAL_TABLE_SCHEMA, "metrics": METRICS_TABLE_SCHEMA, "memories": MEMORY_TABLE_SCHEMA, "knowledge": KNOWLEDGE_TABLE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA, "versions": VERSIONS_TABLE_SCHEMA, "traces": TRACE_TABLE_SCHEMA, "components": COMPONENT_TABLE_SCHEMA, "component_configs": COMPONENT_CONFIGS_TABLE_SCHEMA, "component_links": COMPONENT_LINKS_TABLE_SCHEMA, "learnings": LEARNINGS_TABLE_SCHEMA, "schedules": SCHEDULE_TABLE_SCHEMA, "approvals": APPROVAL_TABLE_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema # type: ignore[return-value]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/postgres/schemas.py", "license": "Apache License 2.0", "lines": 324, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/postgres/utils.py
"""Utility functions for the Postgres database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from sqlalchemy import Engine from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession from agno.db.postgres.schemas import get_table_schema_definition from agno.db.schemas.culture import CulturalKnowledge from agno.utils.log import log_debug, log_error, log_warning try: from sqlalchemy import Table, func from sqlalchemy.dialects import postgresql from sqlalchemy.exc import NoSuchTableError from sqlalchemy.inspection import inspect from sqlalchemy.orm import Session from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") # -- DB util methods -- def apply_sorting(stmt, table: Table, sort_by: Optional[str] = None, sort_order: Optional[str] = None): """Apply sorting to the given SQLAlchemy statement. Args: stmt: The SQLAlchemy statement to modify table: The table being queried sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The modified statement with sorting applied Note: For 'updated_at' sorting, uses COALESCE(updated_at, created_at) to fall back to created_at when updated_at is NULL. This ensures pre-2.0 records (which may have NULL updated_at) are sorted correctly by their creation time. """ if sort_by is None: return stmt if not hasattr(table.c, sort_by): log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return stmt # For updated_at, use COALESCE to fall back to created_at if updated_at is NULL # This handles pre-2.0 records that may have NULL updated_at values if sort_by == "updated_at" and hasattr(table.c, "created_at"): sort_column = func.coalesce(table.c.updated_at, table.c.created_at) else: sort_column = getattr(table.c, sort_by) if sort_order and sort_order == "asc": return stmt.order_by(sort_column.asc()) else: return stmt.order_by(sort_column.desc()) def create_schema(session: Session, db_schema: str) -> None: """Create the database schema if it doesn't exist. Args: session: The SQLAlchemy session to use db_schema (str): The definition of the database schema to create """ try: log_debug(f"Creating schema if not exists: {db_schema}") session.execute(text(f"CREATE SCHEMA IF NOT EXISTS {db_schema};")) except Exception as e: log_warning(f"Could not create schema {db_schema}: {e}") async def acreate_schema(session: AsyncSession, db_schema: str) -> None: """Create the database schema if it doesn't exist. Args: session: The SQLAlchemy session to use db_schema (str): The definition of the database schema to create """ try: log_debug(f"Creating schema if not exists: {db_schema}") await session.execute(text(f"CREATE SCHEMA IF NOT EXISTS {db_schema};")) except Exception as e: log_warning(f"Could not create schema {db_schema}: {e}") def is_table_available(session: Session, table_name: str, db_schema: str) -> bool: """ Check if a table with the given name exists in the given schema. Returns: bool: True if the table exists, False otherwise. """ try: exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_schema = :schema AND table_name = :table" ) exists = session.execute(exists_query, {"schema": db_schema, "table": table_name}).scalar() is not None return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False async def ais_table_available(session: AsyncSession, table_name: str, db_schema: str) -> bool: """ Check if a table with the given name exists in the given schema. Returns: bool: True if the table exists, False otherwise. """ try: exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_schema = :schema AND table_name = :table" ) exists = (await session.execute(exists_query, {"schema": db_schema, "table": table_name})).scalar() is not None return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False def is_valid_table(db_engine: Engine, table_name: str, table_type: str, db_schema: str) -> bool: """ Check if the existing table has the expected column names. Args: table_name (str): Name of the table to validate schema (str): Database schema name Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns inspector = inspect(db_engine) existing_columns_info = inspector.get_columns(table_name, schema=db_schema) existing_columns = set(col["name"] for col in existing_columns_info) # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {db_schema}.{table_name}") return False return True except Exception as e: log_error(f"Error validating table schema for {db_schema}.{table_name}: {e}") return False async def ais_valid_table(db_engine: AsyncEngine, table_name: str, table_type: str, db_schema: str) -> bool: """ Check if the existing table has the expected column names. Args: table_name (str): Name of the table to validate schema (str): Database schema name Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns from the async engine async with db_engine.connect() as conn: existing_columns = await conn.run_sync(_get_table_columns, table_name, db_schema) # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {db_schema}.{table_name}") return False return True except NoSuchTableError: log_error(f"Table {db_schema}.{table_name} does not exist") return False except Exception as e: log_error(f"Error validating table schema for {db_schema}.{table_name}: {e}") return False def _get_table_columns(conn, table_name: str, db_schema: str) -> set[str]: """Helper function to get table columns using sync inspector.""" inspector = inspect(conn) columns_info = inspector.get_columns(table_name, schema=db_schema) return {col["name"] for col in columns_info} # -- Metrics util methods -- def bulk_upsert_metrics(session: Session, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database. Args: table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] stmt = postgresql.insert(table) # Columns to update in case of conflict update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] } stmt = stmt.on_conflict_do_update(index_elements=["date", "aggregation_period"], set_=update_columns).returning( # type: ignore table ) result = session.execute(stmt, metrics_records) results = [row._mapping for row in result.fetchall()] session.commit() return results # type: ignore async def abulk_upsert_metrics(session: AsyncSession, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database. Args: table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] stmt = postgresql.insert(table) # Columns to update in case of conflict update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] } stmt = stmt.on_conflict_do_update(index_elements=["date", "aggregation_period"], set_=update_columns).returning( # type: ignore table ) result = await session.execute(stmt, metrics_records) results = [row._mapping for row in result.fetchall()] await session.commit() return results # type: ignore def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) runs = session.get("runs", []) or [] metrics[runs_count_key] += len(runs) if runs: for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_data = session.get("session_data", {}) or {} session_metrics = session_data.get("session_metrics", {}) or {} for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: dates_to_process (list[date]): The dates to fetch session data for. Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single JSON dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as JSON containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a JSON dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the JSON content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/postgres/utils.py", "license": "Apache License 2.0", "lines": 366, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/redis/redis.py
import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.redis.utils import ( apply_filters, apply_pagination, apply_sorting, calculate_date_metrics, create_index_entries, deserialize_cultural_knowledge_from_db, deserialize_data, fetch_all_sessions_data, generate_redis_key, get_all_keys_for_table, get_dates_to_calculate_metrics_for, remove_index_entries, serialize_cultural_knowledge_for_db, serialize_data, ) from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info from agno.utils.string import generate_id try: from redis import Redis, RedisCluster except ImportError: raise ImportError("`redis` not installed. Please install it using `pip install redis`") class RedisDb(BaseDb): def __init__( self, id: Optional[str] = None, redis_client: Optional[Union[Redis, RedisCluster]] = None, db_url: Optional[str] = None, db_prefix: str = "agno", expire: Optional[int] = None, session_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, culture_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, ): """ Interface for interacting with a Redis database. The following order is used to determine the database connection: 1. Use the redis_client if provided 2. Use the db_url 3. Raise an error if neither is provided db_url only supports single-node Redis connections, if you need Redis Cluster support, provide a redis_client. Args: id (Optional[str]): The ID of the database. redis_client (Optional[Redis]): Redis client instance to use. If not provided a new client will be created. db_url (Optional[str]): Redis connection URL (e.g., "redis://localhost:6379/0" or "rediss://user:pass@host:port/db") db_prefix (str): Prefix for all Redis keys expire (Optional[int]): TTL for Redis keys in seconds session_table (Optional[str]): Name of the table to store sessions memory_table (Optional[str]): Name of the table to store memories metrics_table (Optional[str]): Name of the table to store metrics eval_table (Optional[str]): Name of the table to store evaluation runs knowledge_table (Optional[str]): Name of the table to store knowledge documents culture_table (Optional[str]): Name of the table to store cultural knowledge traces_table (Optional[str]): Name of the table to store traces spans_table (Optional[str]): Name of the table to store spans Raises: ValueError: If neither redis_client nor db_url is provided. """ if id is None: base_seed = db_url or str(redis_client) seed = f"{base_seed}#{db_prefix}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, culture_table=culture_table, traces_table=traces_table, spans_table=spans_table, ) self.db_prefix = db_prefix self.expire = expire if redis_client is not None: self.redis_client = redis_client elif db_url is not None: self.redis_client = Redis.from_url(db_url, decode_responses=True) else: raise ValueError("One of redis_client or db_url must be provided") # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Redis implementation, always returns True.""" return True def _get_table_name(self, table_type: str) -> str: """Get the active table name for the given table type.""" if table_type == "sessions": return self.session_table_name elif table_type == "memories": return self.memory_table_name elif table_type == "metrics": return self.metrics_table_name elif table_type == "evals": return self.eval_table_name elif table_type == "knowledge": return self.knowledge_table_name elif table_type == "culture": return self.culture_table_name elif table_type == "traces": return self.trace_table_name elif table_type == "spans": return self.span_table_name else: raise ValueError(f"Unknown table type: {table_type}") def _store_record( self, table_type: str, record_id: str, data: Dict[str, Any], index_fields: Optional[List[str]] = None ) -> bool: """Generic method to store a record in Redis, considering optional indexing. Args: table_type (str): The type of table to store the record in. record_id (str): The ID of the record to store. data (Dict[str, Any]): The data to store in the record. index_fields (Optional[List[str]]): The fields to index the record by. Returns: bool: True if the record was stored successfully, False otherwise. """ try: key = generate_redis_key(prefix=self.db_prefix, table_type=table_type, key_id=record_id) serialized_data = serialize_data(data) self.redis_client.set(key, serialized_data, ex=self.expire) if index_fields: create_index_entries( redis_client=self.redis_client, prefix=self.db_prefix, table_type=table_type, record_id=record_id, record_data=data, index_fields=index_fields, ) return True except Exception as e: log_error(f"Error storing Redis record: {e}") return False def _get_record(self, table_type: str, record_id: str) -> Optional[Dict[str, Any]]: """Generic method to get a record from Redis. Args: table_type (str): The type of table to get the record from. record_id (str): The ID of the record to get. Returns: Optional[Dict[str, Any]]: The record data if found, None otherwise. """ try: key = generate_redis_key(prefix=self.db_prefix, table_type=table_type, key_id=record_id) data = self.redis_client.get(key) if data is None: return None return deserialize_data(data) # type: ignore except Exception as e: log_error(f"Error getting record {record_id}: {e}") return None def _delete_record(self, table_type: str, record_id: str, index_fields: Optional[List[str]] = None) -> bool: """Generic method to delete a record from Redis. Args: table_type (str): The type of table to delete the record from. record_id (str): The ID of the record to delete. index_fields (Optional[List[str]]): The fields to index the record by. Returns: bool: True if the record was deleted successfully, False otherwise. Raises: Exception: If any error occurs while deleting the record. """ try: # Handle index deletion first if index_fields: record_data = self._get_record(table_type, record_id) if record_data: remove_index_entries( redis_client=self.redis_client, prefix=self.db_prefix, table_type=table_type, record_id=record_id, record_data=record_data, index_fields=index_fields, ) key = generate_redis_key(prefix=self.db_prefix, table_type=table_type, key_id=record_id) result = self.redis_client.delete(key) if result is None or result == 0: return False return True except Exception as e: log_error(f"Error deleting record {record_id}: {e}") return False def _get_all_records(self, table_type: str) -> List[Dict[str, Any]]: """Generic method to get all records for a table type. Args: table_type (str): The type of table to get the records from. Returns: List[Dict[str, Any]]: The records data if found, None otherwise. Raises: Exception: If any error occurs while getting the records. """ try: keys = get_all_keys_for_table(redis_client=self.redis_client, prefix=self.db_prefix, table_type=table_type) records = [] for key in keys: data = self.redis_client.get(key) if data: records.append(deserialize_data(data)) # type: ignore return records except Exception as e: log_error(f"Error getting all records for {table_type}: {e}") return [] def get_latest_schema_version(self): """Get the latest version of the database schema.""" pass def upsert_schema_version(self, version: str) -> None: """Upsert the schema version into the database.""" pass # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """Delete a session from Redis. Args: session_id (str): The ID of the session to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If any error occurs while deleting the session. """ try: if user_id is not None: session = self._get_record("sessions", session_id) if session is None or session.get("user_id") != user_id: log_debug(f"No session found to delete with session_id: {session_id} and user_id: {user_id}") return False if self._delete_record( table_type="sessions", record_id=session_id, index_fields=["user_id", "agent_id", "team_id", "workflow_id", "session_type"], ): log_debug(f"Successfully deleted session: {session_id}") return True else: log_debug(f"No session found to delete with session_id: {session_id}") return False except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete multiple sessions from Redis. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If any error occurs while deleting the sessions. """ try: deleted_count = 0 for session_id in session_ids: if user_id is not None: session = self._get_record("sessions", session_id) if session is None or session.get("user_id") != user_id: continue if self._delete_record( "sessions", session_id, index_fields=["user_id", "agent_id", "team_id", "workflow_id", "session_type"], ): deleted_count += 1 log_debug(f"Successfully deleted {deleted_count} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Read a session from Redis. Args: session_id (str): The ID of the session to get. session_type (SessionType): The type of session to get. user_id (Optional[str]): The ID of the user to filter by. Returns: Optional[Union[AgentSession, TeamSession, WorkflowSession]]: The session if found, None otherwise. Raises: Exception: If any error occurs while getting the session. """ try: session = self._get_record("sessions", session_id) if session is None: return None # Apply filters if user_id is not None and session.get("user_id") != user_id: return None if not deserialize: return session if session_type == SessionType.AGENT.value: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM.value: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW.value: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading session: {e}") raise e # TODO: optimizable def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, create_index_if_not_found: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """Get all sessions matching the given filters. Args: session_type (Optional[SessionType]): The type of session to filter by. user_id (Optional[str]): The ID of the user to filter by. component_id (Optional[str]): The ID of the component to filter by. session_name (Optional[str]): The name of the session to filter by. limit (Optional[int]): The maximum number of sessions to return. page (Optional[int]): The page number to return. sort_by (Optional[str]): The field to sort by. sort_order (Optional[str]): The order to sort by. Returns: List[Union[AgentSession, TeamSession, WorkflowSession]]: The list of sessions. """ try: all_sessions = self._get_all_records("sessions") conditions: Dict[str, Any] = {} if session_type is not None: conditions["session_type"] = session_type if user_id is not None: conditions["user_id"] = user_id filtered_sessions = apply_filters(records=all_sessions, conditions=conditions) if component_id is not None: if session_type == SessionType.AGENT: filtered_sessions = [s for s in filtered_sessions if s.get("agent_id") == component_id] elif session_type == SessionType.TEAM: filtered_sessions = [s for s in filtered_sessions if s.get("team_id") == component_id] elif session_type == SessionType.WORKFLOW: filtered_sessions = [s for s in filtered_sessions if s.get("workflow_id") == component_id] if start_timestamp is not None: filtered_sessions = [s for s in filtered_sessions if s.get("created_at", 0) >= start_timestamp] if end_timestamp is not None: filtered_sessions = [s for s in filtered_sessions if s.get("created_at", 0) <= end_timestamp] if session_name is not None: filtered_sessions = [ s for s in filtered_sessions if session_name.lower() in s.get("session_data", {}).get("session_name", "").lower() ] sorted_sessions = apply_sorting(records=filtered_sessions, sort_by=sort_by, sort_order=sort_order) sessions = apply_pagination(records=sorted_sessions, limit=limit, page=page) sessions = [record for record in sessions] if not deserialize: return sessions, len(filtered_sessions) if session_type == SessionType.AGENT: return [AgentSession.from_dict(record) for record in sessions] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(record) for record in sessions] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(record) for record in sessions] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading sessions: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """Rename a session in Redis. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name of the session. user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: Optional[Session]: The renamed session if successful, None otherwise. Raises: Exception: If any error occurs while renaming the session. """ try: session = self._get_record("sessions", session_id) if session is None: return None if user_id is not None and session.get("user_id") != user_id: return None # Update session_name, in session_data if "session_data" not in session: session["session_data"] = {} session["session_data"]["session_name"] = session_name session["updated_at"] = int(time.time()) # Store updated session success = self._store_record("sessions", session_id, session) if not success: return None log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Error renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """Insert or update a session in Redis. Args: session (Session): The session to upsert. Returns: Optional[Session]: The upserted session if successful, None otherwise. Raises: Exception: If any error occurs while upserting the session. """ try: session_dict = session.to_dict() existing = self._get_record(table_type="sessions", record_id=session.session_id) if ( existing and existing.get("user_id") is not None and existing.get("user_id") != session_dict.get("user_id") ): return None if isinstance(session, AgentSession): data = { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "team_id": session_dict.get("team_id"), "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "team_data": session_dict.get("team_data"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at") or int(time.time()), "updated_at": int(time.time()), } success = self._store_record( table_type="sessions", record_id=session.session_id, data=data, index_fields=["user_id", "agent_id", "session_type"], ) if not success: return None if not deserialize: return data return AgentSession.from_dict(data) elif isinstance(session, TeamSession): data = { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "agent_id": None, "team_id": session_dict.get("team_id"), "workflow_id": None, "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "agent_data": None, "workflow_data": None, "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at") or int(time.time()), "updated_at": int(time.time()), } success = self._store_record( table_type="sessions", record_id=session.session_id, data=data, index_fields=["user_id", "team_id", "session_type"], ) if not success: return None if not deserialize: return data return TeamSession.from_dict(data) else: data = { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at") or int(time.time()), "updated_at": int(time.time()), "agent_id": None, "team_id": None, "agent_data": None, "team_data": None, "summary": None, } success = self._store_record( table_type="sessions", record_id=session.session_id, data=data, index_fields=["user_id", "workflow_id", "session_type"], ) if not success: return None if not deserialize: return data return WorkflowSession.from_dict(data) except Exception as e: log_error(f"Error upserting session: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: log_info( f"RedisDb doesn't support efficient bulk operations, falling back to individual upserts for {len(sessions)} sessions" ) # Fall back to individual upserts results = [] for session in sessions: if session is not None: result = self.upsert_session(session, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from Redis. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user. If provided, verifies the memory belongs to this user before deleting. Returns: bool: True if the memory was deleted, False otherwise. Raises: Exception: If any error occurs while deleting the memory. """ try: # If user_id is provided, verify ownership before deleting if user_id is not None: memory = self._get_record("memories", memory_id) if memory is None: log_debug(f"No user memory found with id: {memory_id}") return if memory.get("user_id") != user_id: log_debug(f"Memory {memory_id} does not belong to user {user_id}") return if self._delete_record( "memories", memory_id, index_fields=["user_id", "agent_id", "team_id", "workflow_id"] ): log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting user memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from Redis. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user. If provided, only deletes memories belonging to this user. """ try: # TODO: cant we optimize this? for memory_id in memory_ids: # If user_id is provided, verify ownership before deleting if user_id is not None: memory = self._get_record("memories", memory_id) if memory is None: continue if memory.get("user_id") != user_id: log_debug(f"Memory {memory_id} does not belong to user {user_id}, skipping deletion") continue self._delete_record( "memories", memory_id, index_fields=["user_id", "agent_id", "team_id", "workflow_id"], ) except Exception as e: log_error(f"Error deleting user memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from Redis. Returns: List[str]: The list of memory topics. """ try: all_memories = self._get_all_records("memories") topics = set() for memory in all_memories: memory_topics = memory.get("topics", []) if isinstance(memory_topics, list): topics.update(memory_topics) return list(topics) except Exception as e: log_error(f"Exception reading memory topics: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a memory from Redis. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to deserialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user. If provided, only returns the memory if it belongs to this user. Returns: Optional[UserMemory]: The memory data if found, None otherwise. """ try: memory_raw = self._get_record("memories", memory_id) if memory_raw is None: return None # Filter by user_id if provided if user_id is not None and memory_raw.get("user_id") != user_id: return None if not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception reading memory: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from Redis as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. topics (Optional[List[str]]): The topics to filter by. search_content (Optional[str]): The content to search for. limit (Optional[int]): The maximum number of memories to return. page (Optional[int]): The page number to return. sort_by (Optional[str]): The field to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to deserialize the memories. Returns: Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of UserMemory objects - When deserialize=False: Tuple of (memory dictionaries, total count) Raises: Exception: If any error occurs while reading the memories. """ try: all_memories = self._get_all_records("memories") # Apply filters conditions = {} if user_id is not None: conditions["user_id"] = user_id if agent_id is not None: conditions["agent_id"] = agent_id if team_id is not None: conditions["team_id"] = team_id filtered_memories = apply_filters(records=all_memories, conditions=conditions) # Apply topic filter if topics is not None: filtered_memories = [ m for m in filtered_memories if any(topic in m.get("topics", []) for topic in topics) ] # Apply content search if search_content is not None: filtered_memories = [ m for m in filtered_memories if search_content.lower() in str(m.get("memory", "")).lower() ] sorted_memories = apply_sorting(records=filtered_memories, sort_by=sort_by, sort_order=sort_order) paginated_memories = apply_pagination(records=sorted_memories, limit=limit, page=page) if not deserialize: return paginated_memories, len(filtered_memories) return [UserMemory.from_dict(record) for record in paginated_memories] except Exception as e: log_error(f"Exception reading memories: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: """Get user memory stats from Redis. Args: limit (Optional[int]): The maximum number of stats to return. page (Optional[int]): The page number to return. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A tuple containing the list of stats and the total number of stats. Raises: Exception: If any error occurs while getting the user memory stats. """ try: all_memories = self._get_all_records("memories") # Group by user_id user_stats = {} for memory in all_memories: memory_user_id = memory.get("user_id") # filter by user_id if provided if user_id is not None and memory_user_id != user_id: continue if memory_user_id is None: continue if memory_user_id not in user_stats: user_stats[memory_user_id] = { "user_id": memory_user_id, "total_memories": 0, "last_memory_updated_at": 0, } user_stats[memory_user_id]["total_memories"] += 1 updated_at = memory.get("updated_at", 0) if updated_at > user_stats[memory_user_id]["last_memory_updated_at"]: user_stats[memory_user_id]["last_memory_updated_at"] = updated_at stats_list = list(user_stats.values()) # Sorting by last_memory_updated_at descending stats_list.sort(key=lambda x: x["last_memory_updated_at"], reverse=True) total_count = len(stats_list) paginated_stats = apply_pagination(records=stats_list, limit=limit, page=page) return paginated_stats, total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in Redis. Args: memory (UserMemory): The memory to upsert. Returns: Optional[UserMemory]: The upserted memory data if successful, None otherwise. """ try: if memory.memory_id is None: memory.memory_id = str(uuid4()) data = { "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "memory_id": memory.memory_id, "memory": memory.memory, "topics": memory.topics, "input": memory.input, "feedback": memory.feedback, "created_at": memory.created_at, "updated_at": int(time.time()), } success = self._store_record( "memories", memory.memory_id, data, index_fields=["user_id", "agent_id", "team_id", "workflow_id"] ) if not success: return None if not deserialize: return data return UserMemory.from_dict(data) except Exception as e: log_error(f"Error upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: log_info( f"RedisDb doesn't support efficient bulk operations, falling back to individual upserts for {len(memories)} memories" ) # Fall back to individual upserts results = [] for memory in memories: if memory is not None: result = self.upsert_user_memory(memory, deserialize=deserialize) if result is not None: results.append(result) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: # Get all keys for memories table keys = get_all_keys_for_table(redis_client=self.redis_client, prefix=self.db_prefix, table_type="memories") if keys: # Delete all memory keys in a single batch operation self.redis_client.delete(*keys) except Exception as e: log_error(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """Get all sessions for metrics calculation. Args: start_timestamp (Optional[int]): The start timestamp to filter by. end_timestamp (Optional[int]): The end timestamp to filter by. Returns: List[Dict[str, Any]]: The list of sessions. Raises: Exception: If any error occurs while getting the sessions. """ try: all_sessions = self._get_all_records("sessions") # Filter by timestamp if provided if start_timestamp is not None or end_timestamp is not None: filtered_sessions = [] for session in all_sessions: created_at = session.get("created_at", 0) if start_timestamp is not None and created_at < start_timestamp: continue if end_timestamp is not None and created_at > end_timestamp: continue filtered_sessions.append(session) return filtered_sessions return all_sessions except Exception as e: log_error(f"Error reading sessions for metrics: {e}") raise e def _get_metrics_calculation_starting_date(self) -> Optional[date]: """Get the first date for which metrics calculation is needed. Returns: Optional[date]: The first date for which metrics calculation is needed. Raises: Exception: If any error occurs while getting the metrics calculation starting date. """ try: all_metrics = self._get_all_records("metrics") if all_metrics: # Find the latest completed metric completed_metrics = [m for m in all_metrics if m.get("completed", False)] if completed_metrics: latest_completed = max(completed_metrics, key=lambda x: x.get("date", "")) return datetime.fromisoformat(latest_completed["date"]).date() + timedelta(days=1) else: # Find the earliest incomplete metric incomplete_metrics = [m for m in all_metrics if not m.get("completed", False)] if incomplete_metrics: earliest_incomplete = min(incomplete_metrics, key=lambda x: x.get("date", "")) return datetime.fromisoformat(earliest_incomplete["date"]).date() # No metrics records, find first session sessions_raw, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) if sessions_raw: first_session_date = sessions_raw[0]["created_at"] # type: ignore return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() return None except Exception as e: log_error(f"Error getting metrics starting date: {e}") raise e def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics. Returns: Optional[list[dict]]: The list of metrics. Raises: Exception: If any error occurs while calculating the metrics. """ try: starting_date = self._get_metrics_calculation_starting_date() if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) # Check if a record already exists for this date and aggregation period existing_record = self._get_record("metrics", metrics_record["id"]) if existing_record: # Update the existing record while preserving created_at metrics_record["created_at"] = existing_record.get("created_at", metrics_record["created_at"]) success = self._store_record("metrics", metrics_record["id"], metrics_record) if success: results.append(metrics_record) log_debug("Updated metrics calculations") return results except Exception as e: log_error(f"Error calculating metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range. Args: starting_date (Optional[date]): The starting date to filter by. ending_date (Optional[date]): The ending date to filter by. Returns: Tuple[List[dict], Optional[int]]: A tuple containing the list of metrics and the latest updated_at. Raises: Exception: If any error occurs while getting the metrics. """ try: all_metrics = self._get_all_records("metrics") # Filter by date range if starting_date is not None or ending_date is not None: filtered_metrics = [] for metric in all_metrics: metric_date = datetime.fromisoformat(metric.get("date", "")).date() if starting_date is not None and metric_date < starting_date: continue if ending_date is not None and metric_date > ending_date: continue filtered_metrics.append(metric) all_metrics = filtered_metrics # Get latest updated_at latest_updated_at = None if all_metrics: latest_updated_at = max(metric.get("updated_at", 0) for metric in all_metrics) return all_metrics, latest_updated_at except Exception as e: log_error(f"Error getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If any error occurs while deleting the knowledge content. """ try: self._delete_record("knowledge", id) except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If any error occurs while getting the knowledge content. """ try: document_raw = self._get_record("knowledge", id) if document_raw is None: return None return KnowledgeRow.model_validate(document_raw) except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If any error occurs while getting the knowledge contents. """ try: all_documents = self._get_all_records("knowledge") if len(all_documents) == 0: return [], 0 # Apply linked_to filter if provided if linked_to is not None: all_documents = [doc for doc in all_documents if doc.get("linked_to") == linked_to] total_count = len(all_documents) # Apply sorting sorted_documents = apply_sorting(records=all_documents, sort_by=sort_by, sort_order=sort_order) # Apply pagination paginated_documents = apply_pagination(records=sorted_documents, limit=limit, page=page) return [KnowledgeRow.model_validate(doc) for doc in paginated_documents], total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. Raises: Exception: If any error occurs while upserting the knowledge content. """ try: data = knowledge_row.model_dump() success = self._store_record("knowledge", knowledge_row.id, data) # type: ignore return knowledge_row if success else None except Exception as e: log_error(f"Error upserting knowledge content: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in Redis. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run if successful, None otherwise. Raises: Exception: If any error occurs while creating the eval run. """ try: current_time = int(time.time()) data = {"created_at": current_time, "updated_at": current_time, **eval_run.model_dump()} success = self._store_record( "evals", eval_run.run_id, data, index_fields=["agent_id", "team_id", "workflow_id", "model_id", "eval_type"], ) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run if success else None except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from Redis. Args: eval_run_id (str): The ID of the eval run to delete. Raises: Exception: If any error occurs while deleting the eval run. """ try: if self._delete_record( "evals", eval_run_id, index_fields=["agent_id", "team_id", "workflow_id", "model_id", "eval_type"] ): log_debug(f"Deleted eval run with ID: {eval_run_id}") else: log_debug(f"No eval run found with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from Redis. Args: eval_run_ids (List[str]): The IDs of the eval runs to delete. Raises: Exception: If any error occurs while deleting the eval runs. """ try: deleted_count = 0 for eval_run_id in eval_run_ids: if self._delete_record( "evals", eval_run_id, index_fields=["agent_id", "team_id", "workflow_id", "model_id", "eval_type"] ): deleted_count += 1 if deleted_count == 0: log_debug(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {deleted_count} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from Redis. Args: eval_run_id (str): The ID of the eval run to get. Returns: Optional[EvalRunRecord]: The eval run if found, None otherwise. Raises: Exception: If any error occurs while getting the eval run. """ try: eval_run_raw = self._get_record("evals", eval_run_id) if eval_run_raw is None: return None if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from Redis. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number to return. sort_by (Optional[str]): The field to sort by. sort_order (Optional[str]): The order to sort by. Returns: List[EvalRunRecord]: The list of eval runs. Raises: Exception: If any error occurs while getting the eval runs. """ try: all_eval_runs = self._get_all_records("evals") # Apply filters filtered_runs = [] for run in all_eval_runs: # Agent/team/workflow filters if agent_id is not None and run.get("agent_id") != agent_id: continue if team_id is not None and run.get("team_id") != team_id: continue if workflow_id is not None and run.get("workflow_id") != workflow_id: continue if model_id is not None and run.get("model_id") != model_id: continue # Eval type filter if eval_type is not None and len(eval_type) > 0: if run.get("eval_type") not in eval_type: continue # Filter type if filter_type is not None: if filter_type == EvalFilterType.AGENT and run.get("agent_id") is None: continue elif filter_type == EvalFilterType.TEAM and run.get("team_id") is None: continue elif filter_type == EvalFilterType.WORKFLOW and run.get("workflow_id") is None: continue filtered_runs.append(run) if sort_by is None: sort_by = "created_at" sort_order = "desc" sorted_runs = apply_sorting(records=filtered_runs, sort_by=sort_by, sort_order=sort_order) paginated_runs = apply_pagination(records=sorted_runs, limit=limit, page=page) if not deserialize: return paginated_runs, len(filtered_runs) return [EvalRunRecord.model_validate(row) for row in paginated_runs] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Update the name of an eval run in Redis. Args: eval_run_id (str): The ID of the eval run to rename. name (str): The new name of the eval run. Returns: Optional[Dict[str, Any]]: The updated eval run data if successful, None otherwise. Raises: Exception: If any error occurs while updating the eval run name. """ try: eval_run_data = self._get_record("evals", eval_run_id) if eval_run_data is None: return None eval_run_data["name"] = name eval_run_data["updated_at"] = int(time.time()) success = self._store_record("evals", eval_run_id, eval_run_data) if not success: return None log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not deserialize: return eval_run_data return EvalRunRecord.model_validate(eval_run_data) except Exception as e: log_error(f"Error updating eval run name {eval_run_id}: {e}") raise # -- Cultural Knowledge methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: keys = get_all_keys_for_table(redis_client=self.redis_client, prefix=self.db_prefix, table_type="culture") if keys: self.redis_client.delete(*keys) except Exception as e: log_error(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: if self._delete_record("culture", id, index_fields=["name", "agent_id", "team_id"]): log_debug(f"Successfully deleted cultural knowledge id: {id}") else: log_debug(f"No cultural knowledge found with id: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get cultural knowledge by ID. Args: id (str): The ID of the cultural knowledge to retrieve. deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge object. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge if found, None otherwise. Raises: Exception: If an error occurs during retrieval. """ try: cultural_knowledge = self._get_record("culture", id) if cultural_knowledge is None: return None if not deserialize: return cultural_knowledge return deserialize_cultural_knowledge_from_db(cultural_knowledge) except Exception as e: log_error(f"Error getting cultural knowledge: {e}") raise e def get_all_cultural_knowledge( self, agent_id: Optional[str] = None, team_id: Optional[str] = None, name: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge with filtering and pagination. Args: agent_id (Optional[str]): Filter by agent ID. team_id (Optional[str]): Filter by team ID. name (Optional[str]): Filter by name (case-insensitive partial match). limit (Optional[int]): Maximum number of results to return. page (Optional[int]): Page number for pagination. sort_by (Optional[str]): Field to sort by. sort_order (Optional[str]): Sort order ('asc' or 'desc'). deserialize (Optional[bool]): Whether to deserialize to CulturalKnowledge objects. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: Tuple with list of dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: all_cultural_knowledge = self._get_all_records("culture") # Apply filters filtered_items = [] for item in all_cultural_knowledge: if agent_id is not None and item.get("agent_id") != agent_id: continue if team_id is not None and item.get("team_id") != team_id: continue if name is not None and name.lower() not in item.get("name", "").lower(): continue filtered_items.append(item) sorted_items = apply_sorting(records=filtered_items, sort_by=sort_by, sort_order=sort_order) paginated_items = apply_pagination(records=sorted_items, limit=limit, page=page) if not deserialize: return paginated_items, len(filtered_items) return [deserialize_cultural_knowledge_from_db(item) for item in paginated_items] except Exception as e: log_error(f"Error getting all cultural knowledge: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert cultural knowledge in Redis. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the result. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The upserted cultural knowledge. Raises: Exception: If an error occurs during upsert. """ try: # Serialize content, categories, and notes into a dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) item_id = cultural_knowledge.id or str(uuid4()) # Create the item dict with serialized content data = { "id": item_id, "name": cultural_knowledge.name, "summary": cultural_knowledge.summary, "content": content_dict if content_dict else None, "metadata": cultural_knowledge.metadata, "input": cultural_knowledge.input, "created_at": cultural_knowledge.created_at, "updated_at": int(time.time()), "agent_id": cultural_knowledge.agent_id, "team_id": cultural_knowledge.team_id, } success = self._store_record("culture", item_id, data, index_fields=["name", "agent_id", "team_id"]) if not success: return None if not deserialize: return data return deserialize_cultural_knowledge_from_db(data) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # --- Traces --- def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Args: trace: The Trace object to store (one per trace_id). """ try: # Check if trace already exists existing = self._get_record("traces", trace.trace_id) if existing: # workflow (level 3) > team (level 2) > agent (level 1) > child/unknown (level 0) def get_component_level( workflow_id: Optional[str], team_id: Optional[str], agent_id: Optional[str], name: str ) -> int: # Check if name indicates a root span is_root_name = ".run" in name or ".arun" in name if not is_root_name: return 0 # Child span (not a root) elif workflow_id: return 3 # Workflow root elif team_id: return 2 # Team root elif agent_id: return 1 # Agent root else: return 0 # Unknown existing_level = get_component_level( existing.get("workflow_id"), existing.get("team_id"), existing.get("agent_id"), existing.get("name", ""), ) new_level = get_component_level(trace.workflow_id, trace.team_id, trace.agent_id, trace.name) # Only update name if new trace is from a higher or equal level should_update_name = new_level > existing_level # Parse existing start_time to calculate correct duration existing_start_time_str = existing.get("start_time") if isinstance(existing_start_time_str, str): existing_start_time = datetime.fromisoformat(existing_start_time_str.replace("Z", "+00:00")) else: existing_start_time = trace.start_time recalculated_duration_ms = int((trace.end_time - existing_start_time).total_seconds() * 1000) # Update existing record existing["end_time"] = trace.end_time.isoformat() existing["duration_ms"] = recalculated_duration_ms existing["status"] = trace.status if should_update_name: existing["name"] = trace.name # Update context fields ONLY if new value is not None (preserve non-null values) if trace.run_id is not None: existing["run_id"] = trace.run_id if trace.session_id is not None: existing["session_id"] = trace.session_id if trace.user_id is not None: existing["user_id"] = trace.user_id if trace.agent_id is not None: existing["agent_id"] = trace.agent_id if trace.team_id is not None: existing["team_id"] = trace.team_id if trace.workflow_id is not None: existing["workflow_id"] = trace.workflow_id log_debug( f" Updating trace with context: run_id={existing.get('run_id', 'unchanged')}, " f"session_id={existing.get('session_id', 'unchanged')}, " f"user_id={existing.get('user_id', 'unchanged')}, " f"agent_id={existing.get('agent_id', 'unchanged')}, " f"team_id={existing.get('team_id', 'unchanged')}, " ) self._store_record( "traces", trace.trace_id, existing, index_fields=["run_id", "session_id", "user_id", "agent_id", "team_id", "workflow_id", "status"], ) else: trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) self._store_record( "traces", trace.trace_id, trace_dict, index_fields=["run_id", "session_id", "user_id", "agent_id", "team_id", "workflow_id", "status"], ) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace as TraceSchema if trace_id: result = self._get_record("traces", trace_id) if result: # Calculate total_spans and error_count all_spans = self._get_all_records("spans") trace_spans = [s for s in all_spans if s.get("trace_id") == trace_id] result["total_spans"] = len(trace_spans) result["error_count"] = len([s for s in trace_spans if s.get("status_code") == "ERROR"]) return TraceSchema.from_dict(result) return None elif run_id: all_traces = self._get_all_records("traces") matching = [t for t in all_traces if t.get("run_id") == run_id] if matching: # Sort by start_time descending and get most recent matching.sort(key=lambda x: x.get("start_time", ""), reverse=True) result = matching[0] # Calculate total_spans and error_count all_spans = self._get_all_records("spans") trace_spans = [s for s in all_spans if s.get("trace_id") == result.get("trace_id")] result["total_spans"] = len(trace_spans) result["error_count"] = len([s for s in trace_spans if s.get("status_code") == "ERROR"]) return TraceSchema.from_dict(result) return None else: log_debug("get_trace called without any filter parameters") return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace as TraceSchema log_debug( f"get_traces called with filters: run_id={run_id}, session_id={session_id}, " f"user_id={user_id}, agent_id={agent_id}, page={page}, limit={limit}" ) all_traces = self._get_all_records("traces") all_spans = self._get_all_records("spans") # Apply filters filtered_traces = [] for trace in all_traces: if run_id and trace.get("run_id") != run_id: continue if session_id and trace.get("session_id") != session_id: continue if user_id and trace.get("user_id") != user_id: continue if agent_id and trace.get("agent_id") != agent_id: continue if team_id and trace.get("team_id") != team_id: continue if workflow_id and trace.get("workflow_id") != workflow_id: continue if status and trace.get("status") != status: continue if start_time: trace_start = trace.get("start_time", "") if trace_start and trace_start < start_time.isoformat(): continue if end_time: trace_end = trace.get("end_time", "") if trace_end and trace_end > end_time.isoformat(): continue filtered_traces.append(trace) total_count = len(filtered_traces) # Sort by start_time descending filtered_traces.sort(key=lambda x: x.get("start_time", ""), reverse=True) # Apply pagination paginated_traces = apply_pagination(records=filtered_traces, limit=limit, page=page) traces = [] for row in paginated_traces: # Calculate total_spans and error_count trace_spans = [s for s in all_spans if s.get("trace_id") == row.get("trace_id")] row["total_spans"] = len(trace_spans) row["error_count"] = len([s for s in trace_spans if s.get("status_code") == "ERROR"]) traces.append(TraceSchema.from_dict(row)) return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, first_trace_at, last_trace_at. """ try: log_debug( f"get_trace_stats called with filters: user_id={user_id}, agent_id={agent_id}, " f"workflow_id={workflow_id}, team_id={team_id}, " f"start_time={start_time}, end_time={end_time}, page={page}, limit={limit}" ) all_traces = self._get_all_records("traces") # Filter traces and group by session_id session_stats: Dict[str, Dict[str, Any]] = {} for trace in all_traces: trace_session_id = trace.get("session_id") if not trace_session_id: continue # Apply filters if user_id and trace.get("user_id") != user_id: continue if agent_id and trace.get("agent_id") != agent_id: continue if team_id and trace.get("team_id") != team_id: continue if workflow_id and trace.get("workflow_id") != workflow_id: continue created_at = trace.get("created_at", "") if start_time and created_at < start_time.isoformat(): continue if end_time and created_at > end_time.isoformat(): continue if trace_session_id not in session_stats: session_stats[trace_session_id] = { "session_id": trace_session_id, "user_id": trace.get("user_id"), "agent_id": trace.get("agent_id"), "team_id": trace.get("team_id"), "workflow_id": trace.get("workflow_id"), "total_traces": 0, "first_trace_at": created_at, "last_trace_at": created_at, } session_stats[trace_session_id]["total_traces"] += 1 if created_at < session_stats[trace_session_id]["first_trace_at"]: session_stats[trace_session_id]["first_trace_at"] = created_at if created_at > session_stats[trace_session_id]["last_trace_at"]: session_stats[trace_session_id]["last_trace_at"] = created_at # Convert to list and sort by last_trace_at descending stats_list = list(session_stats.values()) stats_list.sort(key=lambda x: x.get("last_trace_at", ""), reverse=True) total_count = len(stats_list) # Apply pagination paginated_stats = apply_pagination(records=stats_list, limit=limit, page=page) # Convert ISO strings to datetime objects for stat in paginated_stats: first_trace_at_str = stat["first_trace_at"] last_trace_at_str = stat["last_trace_at"] stat["first_trace_at"] = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) stat["last_trace_at"] = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) return paginated_stats, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: self._store_record( "spans", span.span_id, span.to_dict(), index_fields=["trace_id", "parent_span_id"], ) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: for span in spans: self._store_record( "spans", span.span_id, span.to_dict(), index_fields=["trace_id", "parent_span_id"], ) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span as SpanSchema result = self._get_record("spans", span_id) if result: return SpanSchema.from_dict(result) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span as SpanSchema all_spans = self._get_all_records("spans") # Apply filters filtered_spans = [] for span in all_spans: if trace_id and span.get("trace_id") != trace_id: continue if parent_span_id and span.get("parent_span_id") != parent_span_id: continue filtered_spans.append(span) # Apply limit if limit: filtered_spans = filtered_spans[:limit] return [SpanSchema.from_dict(s) for s in filtered_spans] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for RedisDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for RedisDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for RedisDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for RedisDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/redis/redis.py", "license": "Apache License 2.0", "lines": 1814, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/redis/schemas.py
"""Table schemas and related utils used by the RedisDb class""" from typing import Any SESSION_SCHEMA = { "session_id": {"type": "string", "primary_key": True}, "session_type": {"type": "string"}, "agent_id": {"type": "string"}, "team_id": {"type": "string"}, "workflow_id": {"type": "string"}, "user_id": {"type": "string"}, "session_data": {"type": "json"}, "agent_data": {"type": "json"}, "team_data": {"type": "json"}, "workflow_data": {"type": "json"}, "metadata": {"type": "json"}, "runs": {"type": "json"}, "summary": {"type": "json"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, } USER_MEMORY_SCHEMA = { "memory_id": {"type": "string", "primary_key": True}, "memory": {"type": "json"}, "agent_id": {"type": "string"}, "team_id": {"type": "string"}, "user_id": {"type": "string"}, "topics": {"type": "json"}, "input": {"type": "string"}, "feedback": {"type": "string"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, } METRICS_SCHEMA = { "id": {"type": "string", "primary_key": True}, "agent_runs_count": {"type": "integer", "default": 0}, "team_runs_count": {"type": "integer", "default": 0}, "workflow_runs_count": {"type": "integer", "default": 0}, "agent_sessions_count": {"type": "integer", "default": 0}, "team_sessions_count": {"type": "integer", "default": 0}, "workflow_sessions_count": {"type": "integer", "default": 0}, "users_count": {"type": "integer", "default": 0}, "token_metrics": {"type": "json", "default": {}}, "model_metrics": {"type": "json", "default": {}}, "date": {"type": "date"}, "aggregation_period": {"type": "string"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, "completed": {"type": "boolean", "default": False}, } EVAL_SCHEMA = { "run_id": {"type": "string", "primary_key": True}, "eval_type": {"type": "string"}, "eval_data": {"type": "json"}, "eval_input": {"type": "json"}, "name": {"type": "string"}, "agent_id": {"type": "string"}, "team_id": {"type": "string"}, "workflow_id": {"type": "string"}, "model_id": {"type": "string"}, "model_provider": {"type": "string"}, "evaluated_component_name": {"type": "string"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, } KNOWLEDGE_SCHEMA = { "id": {"type": "string", "primary_key": True}, "name": {"type": "string"}, "description": {"type": "string"}, "metadata": {"type": "json"}, "type": {"type": "string"}, "size": {"type": "integer"}, "linked_to": {"type": "string"}, "access_count": {"type": "integer"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, "status": {"type": "string"}, "status_message": {"type": "string"}, "external_id": {"type": "string"}, } CULTURAL_KNOWLEDGE_SCHEMA = { "id": {"type": "string", "primary_key": True}, "name": {"type": "string"}, "summary": {"type": "string"}, "content": {"type": "json"}, "metadata": {"type": "json"}, "input": {"type": "string"}, "created_at": {"type": "integer"}, "updated_at": {"type": "integer"}, "agent_id": {"type": "string"}, "team_id": {"type": "string"}, } TRACE_SCHEMA = { "trace_id": {"type": "string", "primary_key": True}, "name": {"type": "string"}, "status": {"type": "string"}, "duration_ms": {"type": "integer"}, "run_id": {"type": "string"}, "session_id": {"type": "string"}, "user_id": {"type": "string"}, "agent_id": {"type": "string"}, "team_id": {"type": "string"}, "workflow_id": {"type": "string"}, "start_time": {"type": "string"}, "end_time": {"type": "string"}, "created_at": {"type": "string"}, } SPAN_SCHEMA = { "span_id": {"type": "string", "primary_key": True}, "trace_id": {"type": "string"}, "parent_span_id": {"type": "string"}, "name": {"type": "string"}, "span_kind": {"type": "string"}, "status_code": {"type": "string"}, "status_message": {"type": "string"}, "start_time": {"type": "string"}, "end_time": {"type": "string"}, "attributes": {"type": "json"}, "created_at": {"type": "string"}, } def get_table_schema_definition(table_type: str) -> dict[str, Any]: """ Get the expected schema definition for the given table. For Redis, we don't need actual schemas since it's a key-value store, but we maintain this for compatibility with the base interface. Args: table_type (str): The type of table to get the schema for. Returns: Dict[str, Any]: Dictionary containing schema information for the table """ schemas = { "sessions": SESSION_SCHEMA, "memories": USER_MEMORY_SCHEMA, "metrics": METRICS_SCHEMA, "evals": EVAL_SCHEMA, "knowledge": KNOWLEDGE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_SCHEMA, "traces": TRACE_SCHEMA, "spans": SPAN_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/redis/schemas.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/redis/utils.py
"""Utility functions for the Redis database class.""" import json import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional, Union from uuid import UUID from agno.db.schemas.culture import CulturalKnowledge from agno.db.utils import get_sort_value from agno.utils.log import log_warning try: from redis import Redis, RedisCluster except ImportError: raise ImportError("`redis` not installed. Please install it using `pip install redis`") # -- Serialization and deserialization -- class CustomEncoder(json.JSONEncoder): """Custom encoder to handle non JSON serializable types.""" def default(self, obj): if isinstance(obj, UUID): return str(obj) elif isinstance(obj, (date, datetime)): return obj.isoformat() return super().default(obj) def serialize_data(data: dict) -> str: return json.dumps(data, ensure_ascii=False, cls=CustomEncoder) def deserialize_data(data: str) -> dict: return json.loads(data) # -- Redis utils -- def generate_redis_key(prefix: str, table_type: str, key_id: str) -> str: """Generate Redis key with proper namespacing.""" return f"{prefix}:{table_type}:{key_id}" def generate_index_key(prefix: str, table_type: str, index_field: str, index_value: str) -> str: """Generate Redis key for index entries.""" return f"{prefix}:{table_type}:index:{index_field}:{index_value}" def get_all_keys_for_table(redis_client: Union[Redis, RedisCluster], prefix: str, table_type: str) -> List[str]: """Get all relevant keys for the given table type. Args: redis_client (Redis): The Redis client. prefix (str): The prefix for the keys. table_type (str): The table type. Returns: List[str]: A list of all relevant keys for the given table type. """ pattern = f"{prefix}:{table_type}:*" all_keys = redis_client.scan_iter(match=pattern) relevant_keys = [] for key in all_keys: if ":index:" in key: # Skip index keys continue relevant_keys.append(key) return relevant_keys # -- DB util methods -- def apply_sorting( records: List[Dict[str, Any]], sort_by: Optional[str] = None, sort_order: Optional[str] = None ) -> List[Dict[str, Any]]: """Apply sorting to the given records list. Args: records: The list of dictionaries to sort sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The sorted list Note: If sorting by "updated_at", will fallback to "created_at" in case of None. """ if sort_by is None or not records: return records try: is_descending = sort_order == "desc" # Sort using the helper function that handles updated_at -> created_at fallback sorted_records = sorted( records, key=lambda x: (get_sort_value(x, sort_by) is None, get_sort_value(x, sort_by)), reverse=is_descending, ) return sorted_records except Exception as e: log_warning(f"Error sorting Redis records: {e}") return records def apply_pagination( records: List[Dict[str, Any]], limit: Optional[int] = None, page: Optional[int] = None ) -> List[Dict[str, Any]]: if limit is None: return records if page is not None and page > 0: start_idx = (page - 1) * limit end_idx = start_idx + limit return records[start_idx:end_idx] return records[:limit] def apply_filters(records: List[Dict[str, Any]], conditions: Dict[str, Any]) -> List[Dict[str, Any]]: if not conditions: return records filtered_records = [] for record in records: match = True for key, value in conditions.items(): if key not in record or record[key] != value: match = False break if match: filtered_records.append(record) return filtered_records def create_index_entries( redis_client: Union[Redis, RedisCluster], prefix: str, table_type: str, record_id: str, record_data: Dict[str, Any], index_fields: List[str], ) -> None: for field in index_fields: if field in record_data and record_data[field] is not None: index_key = generate_index_key(prefix, table_type, field, str(record_data[field])) redis_client.sadd(index_key, record_id) def remove_index_entries( redis_client: Union[Redis, RedisCluster], prefix: str, table_type: str, record_id: str, record_data: Dict[str, Any], index_fields: List[str], ) -> None: for field in index_fields: if field in record_data and record_data[field] is not None: index_key = generate_index_key(prefix, table_type, field, str(record_data[field])) redis_client.srem(index_key, record_id) # -- Metrics utils -- def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data. Returns: dict: A dictionary with the calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) # Create a deterministic ID based on date and aggregation period. This simplifies avoiding duplicates metric_id = f"{date_to_process.isoformat()}_daily" return { "id": metric_id, "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: sessions (List[Dict[str, Any]]): The sessions data. dates_to_process (list[date]): The dates to process. start_timestamp (int): The start timestamp. Returns: Optional[dict]: A dictionary with the session data for the given dates, for all session types. """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as a dict containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/redis/utils.py", "license": "Apache License 2.0", "lines": 277, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/schemas/evals.py
from enum import Enum from typing import Any, Dict, Optional from pydantic import BaseModel class EvalType(str, Enum): ACCURACY = "accuracy" AGENT_AS_JUDGE = "agent_as_judge" PERFORMANCE = "performance" RELIABILITY = "reliability" class EvalFilterType(str, Enum): AGENT = "agent" TEAM = "team" WORKFLOW = "workflow" class EvalRunRecord(BaseModel): """Evaluation run results stored in the database""" agent_id: Optional[str] = None model_id: Optional[str] = None model_provider: Optional[str] = None team_id: Optional[str] = None workflow_id: Optional[str] = None name: Optional[str] = None evaluated_component_name: Optional[str] = None run_id: str eval_type: EvalType eval_data: Dict[str, Any] eval_input: Optional[Dict[str, Any]] = None
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/schemas/evals.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/schemas/knowledge.py
from datetime import datetime from typing import Any, Dict, Optional from pydantic import BaseModel, ConfigDict, model_validator class KnowledgeRow(BaseModel): """Knowledge Row that is stored in the database""" # id for this knowledge, auto-generated if not provided id: Optional[str] = None name: str description: str metadata: Optional[Dict[str, Any]] = None type: Optional[str] = None size: Optional[int] = None linked_to: Optional[str] = None access_count: Optional[int] = None status: Optional[str] = None status_message: Optional[str] = None created_at: Optional[int] = None updated_at: Optional[int] = None external_id: Optional[str] = None model_config = ConfigDict(from_attributes=True, arbitrary_types_allowed=True) @model_validator(mode="after") def generate_id(self) -> "KnowledgeRow": if self.id is None: from uuid import uuid4 self.id = str(uuid4()) return self def to_dict(self) -> Dict[str, Any]: _dict = self.model_dump(exclude={"updated_at"}) _dict["updated_at"] = datetime.fromtimestamp(self.updated_at).isoformat() if self.updated_at else None return _dict
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/schemas/knowledge.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/schemas/memory.py
from dataclasses import dataclass from datetime import datetime from typing import Any, Dict, List, Optional from agno.utils.dttm import now_epoch_s, to_epoch_s @dataclass class UserMemory: """Model for User Memories""" memory: str memory_id: Optional[str] = None topics: Optional[List[str]] = None user_id: Optional[str] = None input: Optional[str] = None created_at: Optional[int] = None updated_at: Optional[int] = None feedback: Optional[str] = None agent_id: Optional[str] = None team_id: Optional[str] = None def __post_init__(self) -> None: """Automatically set/normalize created_at and updated_at.""" self.created_at = now_epoch_s() if self.created_at is None else to_epoch_s(self.created_at) if self.updated_at is not None: self.updated_at = to_epoch_s(self.updated_at) def to_dict(self) -> Dict[str, Any]: created_at = datetime.fromtimestamp(self.created_at).isoformat() if self.created_at is not None else None updated_at = datetime.fromtimestamp(self.updated_at).isoformat() if self.updated_at is not None else created_at _dict = { "memory_id": self.memory_id, "memory": self.memory, "topics": self.topics, "created_at": created_at, "updated_at": updated_at, "input": self.input, "user_id": self.user_id, "agent_id": self.agent_id, "team_id": self.team_id, "feedback": self.feedback, } return {k: v for k, v in _dict.items() if v is not None} @classmethod def from_dict(cls, data: Dict[str, Any]) -> "UserMemory": data = dict(data) # Preserve 0 and None explicitly; only process if key exists if "created_at" in data and data["created_at"] is not None: data["created_at"] = to_epoch_s(data["created_at"]) if "updated_at" in data and data["updated_at"] is not None: data["updated_at"] = to_epoch_s(data["updated_at"]) return cls(**data)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/schemas/memory.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/singlestore/schemas.py
"""Table schemas and related utils used by the SingleStoreDb class""" from typing import Any try: from sqlalchemy.types import JSON, BigInteger, Boolean, Date, String, Text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") SESSION_TABLE_SCHEMA = { "session_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "session_type": {"type": lambda: String(20), "nullable": False, "index": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "workflow_id": {"type": lambda: String(128), "nullable": True}, "user_id": {"type": lambda: String(128), "nullable": True}, "session_data": {"type": JSON, "nullable": True}, "agent_data": {"type": JSON, "nullable": True}, "team_data": {"type": JSON, "nullable": True}, "workflow_data": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "runs": {"type": JSON, "nullable": True}, "summary": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } USER_MEMORY_TABLE_SCHEMA = { "memory_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "memory": {"type": JSON, "nullable": False}, "input": {"type": Text, "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "user_id": {"type": lambda: String(128), "nullable": True, "index": True}, "topics": {"type": JSON, "nullable": True}, "feedback": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True, "index": True}, } EVAL_TABLE_SCHEMA = { "run_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "eval_type": {"type": lambda: String(50), "nullable": False}, "eval_data": {"type": JSON, "nullable": False}, "eval_input": {"type": JSON, "nullable": False}, "name": {"type": lambda: String(255), "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, "workflow_id": {"type": lambda: String(128), "nullable": True}, "model_id": {"type": lambda: String(128), "nullable": True}, "model_provider": {"type": lambda: String(50), "nullable": True}, "evaluated_component_name": {"type": lambda: String(255), "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(255), "nullable": False}, "description": {"type": Text, "nullable": False}, "metadata": {"type": JSON, "nullable": True}, "type": {"type": lambda: String(50), "nullable": True}, "size": {"type": BigInteger, "nullable": True}, "linked_to": {"type": lambda: String(128), "nullable": True}, "access_count": {"type": BigInteger, "nullable": True}, "status": {"type": lambda: String(50), "nullable": True}, "status_message": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "external_id": {"type": lambda: String(128), "nullable": True}, } METRICS_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "agent_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "agent_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "users_count": {"type": BigInteger, "nullable": False, "default": 0}, "token_metrics": {"type": JSON, "nullable": False, "default": {}}, "model_metrics": {"type": JSON, "nullable": False, "default": {}}, "date": {"type": Date, "nullable": False, "index": True}, "aggregation_period": {"type": lambda: String(20), "nullable": False, "index": True}, "created_at": {"type": BigInteger, "nullable": False}, "updated_at": {"type": BigInteger, "nullable": True}, "completed": {"type": Boolean, "nullable": False, "default": False}, } CULTURAL_KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(255), "nullable": False, "index": True}, "summary": {"type": Text, "nullable": True}, "content": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "input": {"type": Text, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": lambda: String(128), "nullable": True}, "team_id": {"type": lambda: String(128), "nullable": True}, } VERSIONS_TABLE_SCHEMA = { "table_name": {"type": lambda: String(128), "nullable": False, "primary_key": True}, "version": {"type": lambda: String(10), "nullable": False}, "created_at": {"type": lambda: String(128), "nullable": False, "index": True}, "updated_at": {"type": lambda: String(128), "nullable": True}, } TRACE_TABLE_SCHEMA = { "trace_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "name": {"type": lambda: String(512), "nullable": False}, "status": {"type": lambda: String(20), "nullable": False, "index": True}, "start_time": {"type": lambda: String(64), "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": lambda: String(64), "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "run_id": {"type": lambda: String(128), "nullable": True, "index": True}, "session_id": {"type": lambda: String(128), "nullable": True, "index": True}, "user_id": {"type": lambda: String(128), "nullable": True, "index": True}, "agent_id": {"type": lambda: String(128), "nullable": True, "index": True}, "team_id": {"type": lambda: String(128), "nullable": True, "index": True}, "workflow_id": {"type": lambda: String(128), "nullable": True, "index": True}, "created_at": {"type": lambda: String(64), "nullable": False, "index": True}, # ISO 8601 datetime string } def _get_span_table_schema(traces_table_name: str = "agno_traces", db_schema: str = "agno") -> dict[str, Any]: """Get the span table schema with the correct foreign key reference. Args: traces_table_name: The name of the traces table to reference in the foreign key. db_schema: The database schema name. Returns: The span table schema dictionary. """ return { "span_id": {"type": lambda: String(128), "primary_key": True, "nullable": False}, "trace_id": { "type": lambda: String(128), "nullable": False, "index": True, "foreign_key": f"{db_schema}.{traces_table_name}.trace_id", }, "parent_span_id": {"type": lambda: String(128), "nullable": True, "index": True}, "name": {"type": lambda: String(512), "nullable": False}, "span_kind": {"type": lambda: String(50), "nullable": False}, "status_code": {"type": lambda: String(20), "nullable": False}, "status_message": {"type": Text, "nullable": True}, "start_time": {"type": lambda: String(64), "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": lambda: String(64), "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "attributes": {"type": JSON, "nullable": True}, "created_at": {"type": lambda: String(64), "nullable": False, "index": True}, # ISO 8601 datetime string } def get_table_schema_definition( table_type: str, traces_table_name: str = "agno_traces", db_schema: str = "agno" ) -> dict[str, Any]: """ Get the expected schema definition for the given table. Args: table_type (str): The type of table to get the schema for. traces_table_name (str): The name of the traces table (used for spans foreign key). db_schema (str): The database schema name (used for spans foreign key). Returns: Dict[str, Any]: Dictionary containing column definitions for the table """ # Handle spans table specially to resolve the foreign key reference if table_type == "spans": return _get_span_table_schema(traces_table_name, db_schema) schemas = { "sessions": SESSION_TABLE_SCHEMA, "evals": EVAL_TABLE_SCHEMA, "metrics": METRICS_TABLE_SCHEMA, "memories": USER_MEMORY_TABLE_SCHEMA, "knowledge": KNOWLEDGE_TABLE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA, "versions": VERSIONS_TABLE_SCHEMA, "traces": TRACE_TABLE_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema # type: ignore[return-value]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/singlestore/schemas.py", "license": "Apache License 2.0", "lines": 171, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/db/singlestore/singlestore.py
import json import time from datetime import date, datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, SessionType from agno.db.migrations.manager import MigrationManager from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.db.singlestore.schemas import get_table_schema_definition from agno.db.singlestore.utils import ( apply_sorting, bulk_upsert_metrics, calculate_date_metrics, create_schema, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, is_table_available, is_valid_table, serialize_cultural_knowledge_for_db, ) from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id try: from sqlalchemy import ForeignKey, Index, UniqueConstraint, and_, func, select, update from sqlalchemy.dialects import mysql from sqlalchemy.engine import Engine, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.schema import Column, MetaData, Table from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") class SingleStoreDb(BaseDb): def __init__( self, id: Optional[str] = None, db_engine: Optional[Engine] = None, db_schema: Optional[str] = None, db_url: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, versions_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, create_schema: bool = True, ): """ Interface for interacting with a SingleStore database. The following order is used to determine the database connection: 1. Use the db_engine if provided 2. Use the db_url 3. Raise an error if neither is provided Args: id (Optional[str]): The ID of the database. db_engine (Optional[Engine]): The SQLAlchemy database engine to use. db_schema (Optional[str]): The database schema to use. db_url (Optional[str]): The database URL to connect to. session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions. culture_table (Optional[str]): Name of the table to store cultural knowledge. memory_table (Optional[str]): Name of the table to store memories. metrics_table (Optional[str]): Name of the table to store metrics. eval_table (Optional[str]): Name of the table to store evaluation runs data. knowledge_table (Optional[str]): Name of the table to store knowledge content. versions_table (Optional[str]): Name of the table to store schema versions. create_schema (bool): Whether to automatically create the database schema if it doesn't exist. Set to False if schema is managed externally (e.g., via migrations). Defaults to True. Raises: ValueError: If neither db_url nor db_engine is provided. ValueError: If none of the tables are provided. """ if id is None: base_seed = db_url or str(db_engine.url) if db_engine else "singlestore" # type: ignore schema_suffix = db_schema if db_schema is not None else "ai" seed = f"{base_seed}#{schema_suffix}" id = generate_id(seed) super().__init__( id=id, session_table=session_table, culture_table=culture_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, versions_table=versions_table, traces_table=traces_table, spans_table=spans_table, ) _engine: Optional[Engine] = db_engine if _engine is None and db_url is not None: _engine = create_engine( db_url, connect_args={ "charset": "utf8mb4", "ssl": {"ssl_disabled": False, "ssl_ca": None, "ssl_check_hostname": False}, }, ) if _engine is None: raise ValueError("One of db_url or db_engine must be provided") self.db_url: Optional[str] = db_url self.db_engine: Engine = _engine self.db_schema: Optional[str] = db_schema self.metadata: MetaData = MetaData(schema=self.db_schema) self.create_schema: bool = create_schema # Initialize database session self.Session: scoped_session = scoped_session(sessionmaker(bind=self.db_engine)) # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a table with the given name exists in the SingleStore database. Args: table_name: Name of the table to check Returns: bool: True if the table exists in the database, False otherwise """ with self.Session() as sess: return is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) def _create_table_structure_only(self, table_name: str, table_type: str) -> Table: """ Create a table structure definition without actually creating the table in the database. Used to avoid autoload issues with SingleStore JSON types. Args: table_name (str): Name of the table table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object with column definitions """ try: # Pass traces_table_name and db_schema for spans table foreign key resolution table_schema = get_table_schema_definition( table_type, traces_table_name=self.trace_table_name, db_schema=self.db_schema or "agno" ) columns: List[Column] = [] # Get the columns from the table schema for col_name, col_config in table_schema.items(): # Skip constraint definitions if col_name.startswith("_"): continue column_args = [col_name, col_config["type"]()] column_kwargs: Dict[str, Any] = {} if col_config.get("primary_key", False): column_kwargs["primary_key"] = True if "nullable" in col_config: column_kwargs["nullable"] = col_config["nullable"] if col_config.get("unique", False): column_kwargs["unique"] = True columns.append(Column(*column_args, **column_kwargs)) table = Table(table_name, self.metadata, *columns, schema=self.db_schema, extend_existing=True) return table except Exception as e: table_ref = f"{self.db_schema}.{table_name}" if self.db_schema else table_name log_error(f"Could not create table structure for {table_ref}: {e}") raise def _create_all_tables(self): """Create all tables for the database.""" tables_to_create = [ (self.session_table_name, "sessions"), (self.memory_table_name, "memories"), (self.metrics_table_name, "metrics"), (self.eval_table_name, "evals"), (self.knowledge_table_name, "knowledge"), (self.versions_table_name, "versions"), ] for table_name, table_type in tables_to_create: self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True) def _create_table(self, table_name: str, table_type: str) -> Table: """ Create a table with the appropriate schema based on the table type. Args: table_name (str): Name of the table to create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object """ table_ref = f"{self.db_schema}.{table_name}" if self.db_schema else table_name try: # Pass traces_table_name and db_schema for spans table foreign key resolution table_schema = get_table_schema_definition( table_type, traces_table_name=self.trace_table_name, db_schema=self.db_schema or "agno" ).copy() columns: List[Column] = [] indexes: List[str] = [] unique_constraints: List[str] = [] schema_unique_constraints = table_schema.pop("_unique_constraints", []) # Get the columns, indexes, and unique constraints from the table schema for col_name, col_config in table_schema.items(): column_args = [col_name, col_config["type"]()] column_kwargs: Dict[str, Any] = {} if col_config.get("primary_key", False): column_kwargs["primary_key"] = True if "nullable" in col_config: column_kwargs["nullable"] = col_config["nullable"] if col_config.get("index", False): indexes.append(col_name) if col_config.get("unique", False): column_kwargs["unique"] = True unique_constraints.append(col_name) # Handle foreign key constraint if "foreign_key" in col_config: column_args.append(ForeignKey(col_config["foreign_key"])) columns.append(Column(*column_args, **column_kwargs)) table = Table(table_name, self.metadata, *columns, schema=self.db_schema, extend_existing=True) # Add multi-column unique constraints with table-specific names for constraint in schema_unique_constraints: constraint_name = f"{table_name}_{constraint['name']}" constraint_columns = constraint["columns"] table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name)) # Add indexes to the table definition for idx_col in indexes: idx_name = f"idx_{table_name}_{idx_col}" table.append_constraint(Index(idx_name, idx_col)) # Create schema if one is specified if self.create_schema and self.db_schema is not None: with self.Session() as sess, sess.begin(): create_schema(session=sess, db_schema=self.db_schema) # SingleStore has a limitation on the number of unique multi-field constraints per table. # We need to work around that limitation for the sessions table. table_created = False if not self.table_exists(table_name): if table_type == "sessions": with self.Session() as sess, sess.begin(): # Build column definitions columns_sql = [] for col in table.columns: col_sql = f"{col.name} {col.type.compile(self.db_engine.dialect)}" if not col.nullable: col_sql += " NOT NULL" columns_sql.append(col_sql) columns_def = ", ".join(columns_sql) # Add primary key, shard key and unique constraint table_sql = f"""CREATE TABLE IF NOT EXISTS {table_ref} ( {columns_def}, PRIMARY KEY (session_id), SHARD KEY (session_id), UNIQUE KEY uq_session_type (session_id, session_type) )""" sess.execute(text(table_sql)) else: table.create(self.db_engine, checkfirst=True) log_debug(f"Successfully created table '{table_ref}'") table_created = True else: log_debug(f"Table '{table_ref}' already exists, skipping creation") # Create indexes for idx in table.indexes: try: # Check if index already exists with self.Session() as sess: if self.db_schema is not None: exists_query = text( "SELECT 1 FROM information_schema.statistics WHERE table_schema = :schema AND index_name = :index_name" ) exists = ( sess.execute(exists_query, {"schema": self.db_schema, "index_name": idx.name}).scalar() is not None ) else: exists_query = text( "SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND index_name = :index_name" ) exists = sess.execute(exists_query, {"index_name": idx.name}).scalar() is not None if exists: log_debug(f"Index {idx.name} already exists in {table_ref}, skipping creation") continue idx.create(self.db_engine) log_debug(f"Created index: {idx.name} for table {table_ref}") except Exception as e: log_error(f"Error creating index {idx.name}: {e}") # Store the schema version for the created table if table_name != self.versions_table_name and table_created: latest_schema_version = MigrationManager(self).latest_schema_version self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public) return table except Exception as e: log_error(f"Could not create table {table_ref}: {e}") raise def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Optional[Table]: if table_type == "sessions": self.session_table = self._get_or_create_table( table_name=self.session_table_name, table_type="sessions", create_table_if_not_found=create_table_if_not_found, ) return self.session_table if table_type == "memories": self.memory_table = self._get_or_create_table( table_name=self.memory_table_name, table_type="memories", create_table_if_not_found=create_table_if_not_found, ) return self.memory_table if table_type == "metrics": self.metrics_table = self._get_or_create_table( table_name=self.metrics_table_name, table_type="metrics", create_table_if_not_found=create_table_if_not_found, ) return self.metrics_table if table_type == "evals": self.eval_table = self._get_or_create_table( table_name=self.eval_table_name, table_type="evals", create_table_if_not_found=create_table_if_not_found, ) return self.eval_table if table_type == "knowledge": self.knowledge_table = self._get_or_create_table( table_name=self.knowledge_table_name, table_type="knowledge", create_table_if_not_found=create_table_if_not_found, ) return self.knowledge_table if table_type == "culture": self.culture_table = self._get_or_create_table( table_name=self.culture_table_name, table_type="culture", create_table_if_not_found=create_table_if_not_found, ) return self.culture_table if table_type == "versions": self.versions_table = self._get_or_create_table( table_name=self.versions_table_name, table_type="versions", create_table_if_not_found=create_table_if_not_found, ) return self.versions_table if table_type == "traces": self.traces_table = self._get_or_create_table( table_name=self.trace_table_name, table_type="traces", create_table_if_not_found=create_table_if_not_found, ) return self.traces_table if table_type == "spans": # Ensure traces table exists first (for foreign key) if create_table_if_not_found: self._get_table(table_type="traces", create_table_if_not_found=True) self.spans_table = self._get_or_create_table( table_name=self.span_table_name, table_type="spans", create_table_if_not_found=create_table_if_not_found, ) return self.spans_table raise ValueError(f"Unknown table type: {table_type}") def _get_or_create_table( self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False, ) -> Optional[Table]: """ Check if the table exists and is valid, else create it. Args: table_name (str): Name of the table to get or create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object representing the schema. """ with self.Session() as sess, sess.begin(): table_is_available = is_table_available(session=sess, table_name=table_name, db_schema=self.db_schema) if not table_is_available: if not create_table_if_not_found: return None # Also store the schema version for the created table if table_name != self.versions_table_name: latest_schema_version = MigrationManager(self).latest_schema_version self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public) return self._create_table(table_name=table_name, table_type=table_type) if not is_valid_table( db_engine=self.db_engine, table_name=table_name, table_type=table_type, db_schema=self.db_schema, ): table_ref = f"{self.db_schema}.{table_name}" if self.db_schema else table_name raise ValueError(f"Table {table_ref} has an invalid schema") try: return self._create_table_structure_only(table_name=table_name, table_type=table_type) except Exception as e: table_ref = f"{self.db_schema}.{table_name}" if self.db_schema else table_name log_error(f"Error loading existing table {table_ref}: {e}") raise def get_latest_schema_version(self, table_name: str) -> str: """Get the latest version of the database schema.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return "2.0.0" with self.Session() as sess: stmt = select(table) # Latest version for the given table stmt = stmt.where(table.c.table_name == table_name) stmt = stmt.order_by(table.c.version.desc()).limit(1) result = sess.execute(stmt).fetchone() if result is None: return "2.0.0" version_dict = dict(result._mapping) return version_dict.get("version") or "2.0.0" def upsert_schema_version(self, table_name: str, version: str) -> None: """Upsert the schema version into the database.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return current_datetime = datetime.now().isoformat() with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values( table_name=table_name, version=version, created_at=current_datetime, # Store as ISO format string updated_at=current_datetime, ) # Update version if table_name already exists stmt = stmt.on_duplicate_key_update( version=version, updated_at=current_datetime, ) sess.execute(stmt) # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """ Delete a session from the database. Args: session_id (str): ID of the session to delete user_id (Optional[str]): User ID to filter by. Defaults to None. Returns: bool: True if the session was deleted, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return False with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id == session_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No session found to delete with session_id: {session_id} in table {table.name}") return False else: log_debug(f"Successfully deleted session with session_id: {session_id} in table {table.name}") return True except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete all given sessions from the database. Can handle multiple session types in the same run. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id.in_(session_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) log_debug(f"Successfully deleted {result.rowcount} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Read a session from the database. Args: session_id (str): ID of the session to read. session_type (SessionType): Type of session to get. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Union[Session, Dict[str, Any], None]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.session_id == session_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if result is None: return None session = dict(result._mapping) if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session table: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """ Get all sessions in the given table. Can filter by user_id and entity_id. Args: session_type (Optional[SessionType]): The type of session to filter by. user_id (Optional[str]): The ID of the user to filter by. component_id (Optional[str]): The ID of the agent / workflow to filter by. session_name (Optional[str]): The name of the session to filter by. start_timestamp (Optional[int]): The start timestamp to filter by. end_timestamp (Optional[int]): The end timestamp to filter by. limit (Optional[int]): The maximum number of sessions to return. Defaults to None. page (Optional[int]): The page number to return. Defaults to None. sort_by (Optional[str]): The field to sort by. Defaults to None. sort_order (Optional[str]): The sort order. Defaults to None. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[Session], Tuple[List[Dict], int]]: - When deserialize=True: List of Session objects - When deserialize=False: Tuple of (session dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if component_id is not None: if session_type == SessionType.AGENT: stmt = stmt.where(table.c.agent_id == component_id) elif session_type == SessionType.TEAM: stmt = stmt.where(table.c.team_id == component_id) elif session_type == SessionType.WORKFLOW: stmt = stmt.where(table.c.workflow_id == component_id) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) if session_name is not None: # SingleStore JSON extraction syntax stmt = stmt.where( func.coalesce(func.JSON_EXTRACT_STRING(table.c.session_data, "session_name"), "").like( f"%{session_name}%" ) ) if session_type is not None: session_type_value = session_type.value if isinstance(session_type, SessionType) else session_type stmt = stmt.where(table.c.session_type == session_type_value) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) records = sess.execute(stmt).fetchall() if records is None: return [] if deserialize else ([], 0) session = [dict(record._mapping) for record in records] if not deserialize: return session, total_count if session_type == SessionType.AGENT: return [AgentSession.from_dict(record) for record in session] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(record) for record in session] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(record) for record in session] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Exception reading from session table: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name for the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during renaming. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess, sess.begin(): stmt = ( update(table) .where(table.c.session_id == session_id) .where(table.c.session_type == session_type.value) .values(session_data=func.JSON_SET_STRING(table.c.session_data, "session_name", session_name)) ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt) if result.rowcount == 0: return None # Fetch the updated record select_stmt = select(table).where(table.c.session_id == session_id) if user_id is not None: select_stmt = select_stmt.where(table.c.user_id == user_id) row = sess.execute(select_stmt).fetchone() if not row: return None session = dict(row._mapping) log_debug(f"Renamed session with id '{session_id}' to '{session_name}'") if not deserialize: return session if session_type == SessionType.AGENT: return AgentSession.from_dict(session) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_error(f"Error renaming session: {e}") raise e def upsert_session(self, session: Session, deserialize: Optional[bool] = True) -> Optional[Session]: """ Insert or update a session in the database. Args: session (Session): The session data to upsert. deserialize (Optional[bool]): Whether to deserialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return None session_dict = session.to_dict() if isinstance(session, AgentSession): with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.AGENT.value, agent_id=session_dict.get("agent_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), agent_data=session_dict.get("agent_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( agent_id=stmt.inserted.agent_id, user_id=stmt.inserted.user_id, agent_data=stmt.inserted.agent_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the result select_stmt = select(table).where( (table.c.session_id == session_dict.get("session_id")) & (table.c.agent_id == session_dict.get("agent_id")) ) row = sess.execute(select_stmt).fetchone() if row is None: return None if not deserialize: return row._mapping return AgentSession.from_dict(row._mapping) elif isinstance(session, TeamSession): with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.TEAM.value, team_id=session_dict.get("team_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), team_data=session_dict.get("team_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( team_id=stmt.inserted.team_id, user_id=stmt.inserted.user_id, team_data=stmt.inserted.team_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the result select_stmt = select(table).where( (table.c.session_id == session_dict.get("session_id")) & (table.c.team_id == session_dict.get("team_id")) ) row = sess.execute(select_stmt).fetchone() if row is None: return None if not deserialize: return row._mapping return TeamSession.from_dict(row._mapping) else: with self.Session() as sess, sess.begin(): existing_row = sess.execute( select(table.c.user_id) .where(table.c.session_id == session_dict.get("session_id")) .with_for_update() ).fetchone() if existing_row is not None: existing_uid = existing_row[0] if existing_uid is not None and existing_uid != session_dict.get("user_id"): return None stmt = mysql.insert(table).values( session_id=session_dict.get("session_id"), session_type=SessionType.WORKFLOW.value, workflow_id=session_dict.get("workflow_id"), user_id=session_dict.get("user_id"), runs=session_dict.get("runs"), workflow_data=session_dict.get("workflow_data"), session_data=session_dict.get("session_data"), summary=session_dict.get("summary"), metadata=session_dict.get("metadata"), created_at=session_dict.get("created_at"), updated_at=session_dict.get("created_at"), ) stmt = stmt.on_duplicate_key_update( workflow_id=stmt.inserted.workflow_id, user_id=stmt.inserted.user_id, workflow_data=stmt.inserted.workflow_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=int(time.time()), ) sess.execute(stmt) # Fetch the result select_stmt = select(table).where( (table.c.session_id == session_dict.get("session_id")) & (table.c.workflow_id == session_dict.get("workflow_id")) ) row = sess.execute(select_stmt).fetchone() if row is None: return None if not deserialize: return row._mapping return WorkflowSession.from_dict(row._mapping) except Exception as e: log_error(f"Error upserting into sessions table: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return [] # Group sessions by type for batch processing agent_sessions = [] team_sessions = [] workflow_sessions = [] for session in sessions: if isinstance(session, AgentSession): agent_sessions.append(session) elif isinstance(session, TeamSession): team_sessions.append(session) elif isinstance(session, WorkflowSession): workflow_sessions.append(session) results: List[Union[Session, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): # Bulk upsert agent sessions if agent_sessions: agent_data = [] for session in agent_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) agent_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": session_dict.get("agent_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "agent_data": session_dict.get("agent_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if agent_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( agent_id=stmt.inserted.agent_id, user_id=stmt.inserted.user_id, agent_data=stmt.inserted.agent_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, agent_data) # Fetch the results for agent sessions agent_ids = [session.session_id for session in agent_sessions] select_stmt = select(table).where(table.c.session_id.in_(agent_ids)) result = sess.execute(select_stmt).fetchall() for row in result: if deserialize: deserialized_session = AgentSession.from_dict(session_dict) if deserialized_session is None: continue results.append(deserialized_session) else: results.append(dict(row._mapping)) # Bulk upsert team sessions if team_sessions: team_data = [] for session in team_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) team_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": session_dict.get("team_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "team_data": session_dict.get("team_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if team_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( team_id=stmt.inserted.team_id, user_id=stmt.inserted.user_id, team_data=stmt.inserted.team_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, team_data) # Fetch the results for team sessions team_ids = [session.session_id for session in team_sessions] select_stmt = select(table).where(table.c.session_id.in_(team_ids)) result = sess.execute(select_stmt).fetchall() for row in result: if deserialize: deserialized_team_session = TeamSession.from_dict(session_dict) if deserialized_team_session is None: continue results.append(deserialized_team_session) else: results.append(dict(row._mapping)) # Bulk upsert workflow sessions if workflow_sessions: workflow_data = [] for session in workflow_sessions: session_dict = session.to_dict() # Use preserved updated_at if flag is set, otherwise use current time updated_at = session_dict.get("updated_at") if preserve_updated_at else int(time.time()) workflow_data.append( { "session_id": session_dict.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": session_dict.get("workflow_id"), "user_id": session_dict.get("user_id"), "runs": session_dict.get("runs"), "workflow_data": session_dict.get("workflow_data"), "session_data": session_dict.get("session_data"), "summary": session_dict.get("summary"), "metadata": session_dict.get("metadata"), "created_at": session_dict.get("created_at"), "updated_at": updated_at, } ) if workflow_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( workflow_id=stmt.inserted.workflow_id, user_id=stmt.inserted.user_id, workflow_data=stmt.inserted.workflow_data, session_data=stmt.inserted.session_data, summary=stmt.inserted.summary, metadata=stmt.inserted.metadata, runs=stmt.inserted.runs, updated_at=stmt.inserted.updated_at, ) sess.execute(stmt, workflow_data) # Fetch the results for workflow sessions workflow_ids = [session.session_id for session in workflow_sessions] select_stmt = select(table).where(table.c.session_id.in_(workflow_ids)) result = sess.execute(select_stmt).fetchall() for row in result: if deserialize: deserialized_workflow_session = WorkflowSession.from_dict(session_dict) if deserialized_workflow_session is None: continue results.append(deserialized_workflow_session) else: results.append(dict(row._mapping)) return results except Exception as e: log_error(f"Exception during bulk session upsert: {e}") return [] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Returns: bool: True if deletion was successful, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id == memory_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted memory id: {memory_id}") else: log_debug(f"No memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No memories found with ids: {memory_ids}") except Exception as e: log_error(f"Error deleting memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the database. Returns: List[str]: List of memory topics. """ try: table = self._get_table(table_type="memories") if table is None: return [] with self.Session() as sess, sess.begin(): stmt = select(table.c.topics) result = sess.execute(stmt).fetchall() topics = [] for record in result: if record is not None and record[0] is not None: topic_list = json.loads(record[0]) if isinstance(record[0], str) else record[0] if isinstance(topic_list, list): topics.extend(topic_list) return list(set(topics)) except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None ) -> Optional[UserMemory]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The ID of the user to filter by. Defaults to None. Returns: Union[UserMemory, Dict[str, Any], None]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.memory_id == memory_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if not result: return None memory_raw = result._mapping if not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. topics (Optional[List[str]]): The topics to filter by. search_content (Optional[str]): The content to search for. limit (Optional[int]): The maximum number of memories to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. Returns: Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of UserMemory objects - When deserialize=False: Tuple of (memory dictionaries, total count) Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if topics is not None: topic_conditions = [func.JSON_ARRAY_CONTAINS_STRING(table.c.topics, topic) for topic in topics] if topic_conditions: stmt = stmt.where(and_(*topic_conditions)) if search_content is not None: stmt = stmt.where(table.c.memory.like(f"%{search_content}%")) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) memories_raw = [record._mapping for record in result] if not deserialize: return memories_raw, total_count return [UserMemory.from_dict(record) for record in memories_raw] except Exception as e: log_error(f"Exception reading from memory table: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. Example: ( [ { "user_id": "123", "total_memories": 10, "last_memory_updated_at": 1714560000, }, ], total_count: 1, ) """ try: table = self._get_table(table_type="memories") if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select( table.c.user_id, func.count(table.c.memory_id).label("total_memories"), func.max(table.c.updated_at).label("last_memory_updated_at"), ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) else: stmt = stmt.where(table.c.user_id.is_not(None)) stmt = stmt.group_by(table.c.user_id) stmt = stmt.order_by(func.max(table.c.updated_at).desc()) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Pagination if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [], 0 return [ { "user_id": record.user_id, # type: ignore "total_memories": record.total_memories, "last_memory_updated_at": record.last_memory_updated_at, } for record in result ], total_count except Exception as e: log_error(f"Exception getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The user memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): if memory.memory_id is None: memory.memory_id = str(uuid4()) current_time = int(time.time()) stmt = mysql.insert(table).values( memory_id=memory.memory_id, memory=memory.memory, input=memory.input, user_id=memory.user_id, agent_id=memory.agent_id, team_id=memory.team_id, topics=memory.topics, feedback=memory.feedback, created_at=memory.created_at, updated_at=current_time, ) stmt = stmt.on_duplicate_key_update( memory=stmt.inserted.memory, topics=stmt.inserted.topics, input=stmt.inserted.input, user_id=stmt.inserted.user_id, agent_id=stmt.inserted.agent_id, team_id=stmt.inserted.team_id, feedback=stmt.inserted.feedback, updated_at=stmt.inserted.updated_at, # Preserve created_at on update - don't overwrite existing value created_at=table.c.created_at, ) sess.execute(stmt) # Fetch the result select_stmt = select(table).where(table.c.memory_id == memory.memory_id) row = sess.execute(select_stmt).fetchone() if row is None: return None memory_raw = row._mapping if not memory_raw or not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Error upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return [] # Prepare data for bulk insert memory_data = [] current_time = int(time.time()) for memory in memories: if memory.memory_id is None: memory.memory_id = str(uuid4()) # Use preserved updated_at if flag is set, otherwise use current time updated_at = memory.updated_at if preserve_updated_at else current_time memory_data.append( { "memory_id": memory.memory_id, "memory": memory.memory, "input": memory.input, "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "topics": memory.topics, "feedback": memory.feedback, "created_at": memory.created_at, "updated_at": updated_at, } ) results: List[Union[UserMemory, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): if memory_data: stmt = mysql.insert(table) stmt = stmt.on_duplicate_key_update( memory=stmt.inserted.memory, topics=stmt.inserted.topics, input=stmt.inserted.input, user_id=stmt.inserted.user_id, agent_id=stmt.inserted.agent_id, team_id=stmt.inserted.team_id, feedback=stmt.inserted.feedback, updated_at=stmt.inserted.updated_at, # Preserve created_at on update created_at=table.c.created_at, ) sess.execute(stmt, memory_data) # Fetch the results memory_ids = [memory.memory_id for memory in memories if memory.memory_id] select_stmt = select(table).where(table.c.memory_id.in_(memory_ids)) result = sess.execute(select_stmt).fetchall() for row in result: memory_raw = dict(row._mapping) if deserialize: results.append(UserMemory.from_dict(memory_raw)) else: results.append(memory_raw) return results except Exception as e: log_error(f"Exception during bulk memory upsert: {e}") return [] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_error(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """ Get all sessions of all types (agent, team, workflow) as raw dictionaries. Args: start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None. end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None. Returns: List[Dict[str, Any]]: List of session dictionaries with session_type field. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] stmt = select( table.c.user_id, table.c.session_data, table.c.runs, table.c.created_at, table.c.session_type, ) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) with self.Session() as sess: result = sess.execute(stmt).fetchall() return [record._mapping for record in result] except Exception as e: log_error(f"Exception reading from sessions table: {e}") return [] def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]: """Get the first date for which metrics calculation is needed: 1. If there are metrics records, return the date of the first day without a complete metrics record. 2. If there are no metrics records, return the date of the first recorded session. 3. If there are no metrics records and no sessions records, return None. Args: table (Table): The table to get the starting date for. Returns: Optional[date]: The starting date for which metrics calculation is needed. """ with self.Session() as sess: stmt = select(table).order_by(table.c.date.desc()).limit(1) result = sess.execute(stmt).fetchone() # 1. Return the date of the first day without a complete metrics record. if result is not None: if result.completed: return result._mapping["date"] + timedelta(days=1) else: return result._mapping["date"] # 2. No metrics records. Return the date of the first recorded session. sessions_result, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) if not isinstance(sessions_result, list): raise ValueError("Error obtaining session list to calculate metrics") first_session_date = sessions_result[0]["created_at"] if sessions_result and len(sessions_result) > 0 else None # type: ignore # 3. No metrics records and no sessions records. Return None. if first_session_date is None: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics. Returns: Optional[list[dict]]: The calculated metrics. Raises: Exception: If an error occurs during metrics calculation. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return None starting_date = self._get_metrics_calculation_starting_date(table) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int(datetime.combine(dates_to_process[0], datetime.min.time()).timestamp()) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()).timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: with self.Session() as sess, sess.begin(): bulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records) log_debug("Updated metrics calculations") return metrics_records except Exception as e: log_error(f"Error calculating metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range. Args: starting_date (Optional[date]): The starting date to filter metrics by. ending_date (Optional[date]): The ending date to filter metrics by. Returns: Tuple[List[dict], int]: A tuple containing the metrics and the timestamp of the latest update. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select(table) if starting_date: stmt = stmt.where(table.c.date >= starting_date) if ending_date: stmt = stmt.where(table.c.date <= ending_date) result = sess.execute(stmt).fetchall() if not result: return [], None # Get the latest updated_at latest_stmt = select(func.max(table.c.updated_at)) latest_updated_at = sess.execute(latest_stmt).scalar() return [row._mapping for row in result], latest_updated_at except Exception as e: log_error(f"Error getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. """ try: table = self._get_table(table_type="knowledge") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.id == id) sess.execute(stmt) log_debug(f"Deleted knowledge content with id '{id}'") except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. """ try: table = self._get_table(table_type="knowledge") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None return KnowledgeRow.model_validate(result._mapping) except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ table = self._get_table(table_type="knowledge") if table is None: return [], 0 try: with self.Session() as sess, sess.begin(): stmt = select(table) # Apply linked_to filter if provided if linked_to is not None: stmt = stmt.where(table.c.linked_to == linked_to) # Apply sorting if sort_by is not None: stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1)) # Get total count before applying limit and pagination count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Apply pagination after count if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if result is None: return [], 0 return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ try: table = self._get_table(table_type="knowledge", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): # Only include fields that are not None in the update update_fields = { k: v for k, v in { "name": knowledge_row.name, "description": knowledge_row.description, "metadata": knowledge_row.metadata, "type": knowledge_row.type, "size": knowledge_row.size, "linked_to": knowledge_row.linked_to, "access_count": knowledge_row.access_count, "status": knowledge_row.status, "status_message": knowledge_row.status_message, "created_at": knowledge_row.created_at, "updated_at": knowledge_row.updated_at, "external_id": knowledge_row.external_id, }.items() if v is not None } stmt = mysql.insert(table).values(knowledge_row.model_dump()) stmt = stmt.on_duplicate_key_update(**update_fields) sess.execute(stmt) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge row: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run, or None if the operation fails. Raises: Exception: If an error occurs during creation. """ try: table = self._get_table(table_type="evals", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): current_time = int(time.time()) stmt = mysql.insert(table).values( {"created_at": current_time, "updated_at": current_time, **eval_run.model_dump()} ) sess.execute(stmt) log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database. Args: eval_run_id (str): The ID of the eval run to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id == eval_run_id) result = sess.execute(stmt) if result.rowcount == 0: log_warning(f"No eval run found with ID: {eval_run_id}") else: log_debug(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database. Args: eval_run_ids (List[str]): List of eval run IDs to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id.in_(eval_run_ids)) result = sess.execute(stmt) if result.rowcount == 0: log_debug(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {result.rowcount} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.run_id == eval_run_id) result = sess.execute(stmt).fetchone() if result is None: return None eval_run_raw = result._mapping if not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by. filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow). deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of dictionaries Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if model_id is not None: stmt = stmt.where(table.c.model_id == model_id) if eval_type is not None and len(eval_type) > 0: stmt = stmt.where(table.c.eval_type.in_(eval_type)) if filter_type is not None: if filter_type == EvalFilterType.AGENT: stmt = stmt.where(table.c.agent_id.is_not(None)) elif filter_type == EvalFilterType.TEAM: stmt = stmt.where(table.c.team_id.is_not(None)) elif filter_type == EvalFilterType.WORKFLOW: stmt = stmt.where(table.c.workflow_id.is_not(None)) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting if sort_by is None: stmt = stmt.order_by(table.c.created_at.desc()) else: stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) eval_runs_raw = [row._mapping for row in result] if not deserialize: return eval_runs_raw, total_count return [EvalRunRecord.model_validate(row) for row in eval_runs_raw] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Upsert the name of an eval run in the database, returning raw dictionary. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. Returns: Optional[Dict[str, Any]]: The updated eval run, or None if the operation fails. Raises: Exception: If an error occurs during update. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = ( table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time())) ) sess.execute(stmt) eval_run_raw = self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize) log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not eval_run_raw or not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Error renaming eval run {eval_run_id}: {e}") raise e # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural knowledge from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: log_warning(f"Exception deleting all cultural knowledge: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to delete. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.id == id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted cultural knowledge id: {id}") else: log_debug(f"No cultural knowledge found with id: {id}") except Exception as e: log_error(f"Error deleting cultural knowledge: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural knowledge entry from the database. Args: id (str): The ID of the cultural knowledge to get. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[Union[CulturalKnowledge, Dict[str, Any]]]: The cultural knowledge entry, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None db_row = dict(result._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge_from_db(db_row) except Exception as e: log_error(f"Exception reading from cultural knowledge table: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural knowledge from the database as CulturalKnowledge objects. Args: name (Optional[str]): The name of the cultural knowledge to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. limit (Optional[int]): The maximum number of cultural knowledge entries to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalKnowledge objects - When deserialize=False: List of CulturalKnowledge dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if name is not None: stmt = stmt.where(table.c.name == name) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) db_rows = [dict(record._mapping) for record in result] if not deserialize: return db_rows, total_count return [deserialize_cultural_knowledge_from_db(row) for row in db_rows] except Exception as e: log_error(f"Error reading from cultural knowledge table: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural knowledge entry into the database. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge to upsert. deserialize (Optional[bool]): Whether to deserialize the cultural knowledge. Defaults to True. Returns: Optional[CulturalKnowledge]: The upserted cultural knowledge entry. Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="culture", create_table_if_not_found=True) if table is None: return None if cultural_knowledge.id is None: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a JSON dict for DB storage content_dict = serialize_cultural_knowledge_for_db(cultural_knowledge) with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values( id=cultural_knowledge.id, name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_dict if content_dict else None, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, created_at=cultural_knowledge.created_at, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) stmt = stmt.on_duplicate_key_update( name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_dict if content_dict else None, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) sess.execute(stmt) # Fetch the inserted/updated row return self.get_cultural_knowledge(id=cultural_knowledge.id, deserialize=deserialize) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # --- Traces --- def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None): """Build base query for traces with aggregated span counts. Args: table: The traces table. spans_table: The spans table (optional). Returns: SQLAlchemy select statement with total_spans and error_count calculated dynamically. """ from sqlalchemy import case, literal if spans_table is not None: # JOIN with spans table to calculate total_spans and error_count return ( select( table, func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"), func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label( "error_count" ), ) .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id)) .group_by(table.c.trace_id) ) else: # Fallback if spans table doesn't exist return select(table, literal(0).label("total_spans"), literal(0).label("error_count")) def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col): """Build a SQL CASE expression that returns the component level for a trace. Component levels (higher = more important): - 3: Workflow root (.run or .arun with workflow_id) - 2: Team root (.run or .arun with team_id) - 1: Agent root (.run or .arun with agent_id) - 0: Child span (not a root) Args: workflow_id_col: SQL column/expression for workflow_id team_id_col: SQL column/expression for team_id agent_id_col: SQL column/expression for agent_id name_col: SQL column/expression for name Returns: SQLAlchemy CASE expression returning the component level as an integer. """ from sqlalchemy import case, or_ is_root_name = or_(name_col.like("%.run%"), name_col.like("%.arun%")) return case( # Workflow root (level 3) (and_(workflow_id_col.isnot(None), is_root_name), 3), # Team root (level 2) (and_(team_id_col.isnot(None), is_root_name), 2), # Agent root (level 1) (and_(agent_id_col.isnot(None), is_root_name), 1), # Child span or unknown (level 0) else_=0, ) def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Uses INSERT ... ON DUPLICATE KEY UPDATE (upsert) to handle concurrent inserts atomically and avoid race conditions. Args: trace: The Trace object to store (one per trace_id). """ from sqlalchemy import case try: table = self._get_table(table_type="traces", create_table_if_not_found=True) if table is None: return trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) with self.Session() as sess, sess.begin(): # Use upsert to handle concurrent inserts atomically # On conflict, update fields while preserving existing non-null context values # and keeping the earliest start_time insert_stmt = mysql.insert(table).values(trace_dict) # Build component level expressions for comparing trace priority new_level = self._get_trace_component_level_expr( insert_stmt.inserted.workflow_id, insert_stmt.inserted.team_id, insert_stmt.inserted.agent_id, insert_stmt.inserted.name, ) existing_level = self._get_trace_component_level_expr( table.c.workflow_id, table.c.team_id, table.c.agent_id, table.c.name, ) # Build the ON DUPLICATE KEY UPDATE clause # Use LEAST for start_time, GREATEST for end_time to capture full trace duration # Duration is calculated using TIMESTAMPDIFF in microseconds then converted to ms upsert_stmt = insert_stmt.on_duplicate_key_update( end_time=func.greatest(table.c.end_time, insert_stmt.inserted.end_time), start_time=func.least(table.c.start_time, insert_stmt.inserted.start_time), # Calculate duration in milliseconds using TIMESTAMPDIFF # TIMESTAMPDIFF(MICROSECOND, start, end) / 1000 gives milliseconds duration_ms=func.timestampdiff( text("MICROSECOND"), func.least(table.c.start_time, insert_stmt.inserted.start_time), func.greatest(table.c.end_time, insert_stmt.inserted.end_time), ) / 1000, status=insert_stmt.inserted.status, # Update name only if new trace is from a higher-level component # Priority: workflow (3) > team (2) > agent (1) > child spans (0) name=case( (new_level > existing_level, insert_stmt.inserted.name), else_=table.c.name, ), # Preserve existing non-null context values using COALESCE run_id=func.coalesce(insert_stmt.inserted.run_id, table.c.run_id), session_id=func.coalesce(insert_stmt.inserted.session_id, table.c.session_id), user_id=func.coalesce(insert_stmt.inserted.user_id, table.c.user_id), agent_id=func.coalesce(insert_stmt.inserted.agent_id, table.c.agent_id), team_id=func.coalesce(insert_stmt.inserted.team_id, table.c.team_id), workflow_id=func.coalesce(insert_stmt.inserted.workflow_id, table.c.workflow_id), ) sess.execute(upsert_stmt) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace table = self._get_table(table_type="traces") if table is None: return None # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build query with aggregated span counts stmt = self._get_traces_base_query(table, spans_table) if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) elif run_id: stmt = stmt.where(table.c.run_id == run_id) else: log_debug("get_trace called without any filter parameters") return None # Order by most recent and get first result stmt = stmt.order_by(table.c.start_time.desc()).limit(1) result = sess.execute(stmt).fetchone() if result: return Trace.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List, int]: """Get traces matching the provided filters. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from agno.tracing.schemas import Trace log_debug( 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}" ) table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build base query with aggregated span counts base_stmt = self._get_traces_base_query(table, spans_table) # Apply filters if run_id: base_stmt = base_stmt.where(table.c.run_id == run_id) if session_id: base_stmt = base_stmt.where(table.c.session_id == session_id) if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if status: base_stmt = base_stmt.where(table.c.status == status) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat()) # Get total count count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() traces = [Trace.from_dict(dict(row._mapping)) for row in results] return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). Each dict contains: session_id, user_id, agent_id, team_id, total_traces, first_trace_at, last_trace_at. """ try: log_debug( f"get_trace_stats called with filters: user_id={user_id}, agent_id={agent_id}, " f"workflow_id={workflow_id}, team_id={team_id}, " f"start_time={start_time}, end_time={end_time}, page={page}, limit={limit}" ) table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 with self.Session() as sess: # Build base query grouped by session_id base_stmt = ( select( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id, func.count(table.c.trace_id).label("total_traces"), func.min(table.c.created_at).label("first_trace_at"), func.max(table.c.created_at).label("last_trace_at"), ) .where(table.c.session_id.isnot(None)) # Only sessions with session_id .group_by( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id ) ) # Apply filters if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat()) # Get total count of sessions count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 log_debug(f"Total matching sessions: {total_count}") # Apply pagination and ordering offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() log_debug(f"Returning page {page} with {len(results)} session stats") # Convert to list of dicts with datetime objects stats_list = [] for row in results: # Convert ISO strings to datetime objects first_trace_at_str = row.first_trace_at last_trace_at_str = row.last_trace_at # Parse ISO format strings to datetime objects (handle None values) first_trace_at = None last_trace_at = None if first_trace_at_str is not None: first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) if last_trace_at_str is not None: last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) stats_list.append( { "session_id": row.session_id, "user_id": row.user_id, "agent_id": row.agent_id, "team_id": row.team_id, "workflow_id": row.workflow_id, "total_traces": row.total_traces, "first_trace_at": first_trace_at, "last_trace_at": last_trace_at, } ) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # --- Spans --- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): stmt = mysql.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): for span in spans: stmt = mysql.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.span_id == span_id) result = sess.execute(stmt).fetchone() if result: return Span.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, limit: Optional[int] = 1000, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. limit: Maximum number of spans to return. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return [] with self.Session() as sess: stmt = select(table) # Apply filters if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) if parent_span_id: stmt = stmt.where(table.c.parent_span_id == parent_span_id) if limit: stmt = stmt.limit(limit) results = sess.execute(stmt).fetchall() return [Span.from_dict(dict(row._mapping)) for row in results] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Learning methods (stubs) -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for SingleStoreDb") def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: raise NotImplementedError("Learning methods not yet implemented for SingleStoreDb") def delete_learning(self, id: str) -> bool: raise NotImplementedError("Learning methods not yet implemented for SingleStoreDb") def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: raise NotImplementedError("Learning methods not yet implemented for SingleStoreDb")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/singlestore/singlestore.py", "license": "Apache License 2.0", "lines": 2511, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/singlestore/utils.py
"""Utility functions for the SingleStore database class.""" import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from sqlalchemy import Engine from agno.db.schemas.culture import CulturalKnowledge from agno.db.singlestore.schemas import get_table_schema_definition from agno.utils.log import log_debug, log_error, log_warning try: from sqlalchemy import Table, func from sqlalchemy.inspection import inspect from sqlalchemy.orm import Session from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") # -- DB util methods -- def apply_sorting(stmt, table: Table, sort_by: Optional[str] = None, sort_order: Optional[str] = None): """Apply sorting to the given SQLAlchemy statement. Args: stmt: The SQLAlchemy statement to modify table: The table being queried sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The modified statement with sorting applied Note: For 'updated_at' sorting, uses COALESCE(updated_at, created_at) to fall back to created_at when updated_at is NULL. This ensures pre-2.0 records (which may have NULL updated_at) are sorted correctly by their creation time. """ if sort_by is None: return stmt if not hasattr(table.c, sort_by): log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return stmt # For updated_at, use COALESCE to fall back to created_at if updated_at is NULL # This handles pre-2.0 records that may have NULL updated_at values if sort_by == "updated_at" and hasattr(table.c, "created_at"): sort_column = func.coalesce(table.c.updated_at, table.c.created_at) else: sort_column = getattr(table.c, sort_by) if sort_order and sort_order == "asc": return stmt.order_by(sort_column.asc()) else: return stmt.order_by(sort_column.desc()) def create_schema(session: Session, db_schema: str) -> None: """Create the database schema if it doesn't exist. Args: session: The SQLAlchemy session to use db_schema (str): The definition of the database schema to create Raises: Exception: If the schema creation fails. """ try: log_debug(f"Creating schema if not exists: {db_schema}") session.execute(text(f"CREATE SCHEMA IF NOT EXISTS {db_schema};")) except Exception as e: log_warning(f"Could not create schema {db_schema}: {e}") def is_table_available(session: Session, table_name: str, db_schema: Optional[str]) -> bool: """ Check if a table with the given name exists in the given schema. Returns: bool: True if the table exists, False otherwise. """ try: if db_schema is not None: exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_schema = :schema AND table_name = :table" ) exists = session.execute(exists_query, {"schema": db_schema, "table": table_name}).scalar() is not None table_ref = f"{db_schema}.{table_name}" else: # Check in current database/schema exists_query = text( "SELECT 1 FROM information_schema.tables WHERE table_name = :table AND table_schema = DATABASE()" ) exists = session.execute(exists_query, {"table": table_name}).scalar() is not None table_ref = table_name if not exists: log_debug(f"Table {table_ref} {'exists' if exists else 'does not exist'}") return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False def is_valid_table(db_engine: Engine, table_name: str, table_type: str, db_schema: Optional[str]) -> bool: """ Check if the existing table has the expected column names. Args: table_name (str): Name of the table to validate schema (str): Database schema name Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} table_ref = f"{db_schema}.{table_name}" if db_schema else table_name inspector = inspect(db_engine) try: import warnings # Suppressing SQLAlchemy warnings about unrecognized SingleStore JSON types, which are expected with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Did not recognize type 'JSON'", category=Warning) existing_columns_info = inspector.get_columns(table_name, schema=db_schema) existing_columns = set(col["name"] for col in existing_columns_info) except Exception: # If column inspection fails (e.g., unrecognized JSON type), assume table is valid return True # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {table_ref}") return False return True except Exception as e: table_ref = f"{db_schema}.{table_name}" if db_schema else table_name log_error(f"Error validating table schema for {table_ref}: {e}") return False # -- Metrics util methods -- def bulk_upsert_metrics(session: Session, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database with proper duplicate handling. Args: table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] for record in metrics_records: date_val = record.get("date") period_val = record.get("aggregation_period") # Check if record already exists based on date + aggregation_period existing_record = ( session.query(table).filter(table.c.date == date_val, table.c.aggregation_period == period_val).first() ) if existing_record: # Update existing record update_data = { k: v for k, v in record.items() if k not in ["id", "date", "aggregation_period", "created_at"] } update_data["updated_at"] = record.get("updated_at") session.query(table).filter(table.c.date == date_val, table.c.aggregation_period == period_val).update( update_data ) # Get the updated record for return updated_record = ( session.query(table).filter(table.c.date == date_val, table.c.aggregation_period == period_val).first() ) if updated_record: results.append(dict(updated_record._mapping)) else: # Insert new record stmt = table.insert().values(**record) session.execute(stmt) results.append(record) session.commit() return results def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) metrics[runs_count_key] += len(session.get("runs", [])) if runs := session.get("runs", []): for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) session_metrics = session.get("session_data", {}).get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: dates_to_process (list[date]): The dates to fetch session data for. Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> Dict[str, Any]: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single JSON dict for the database content column. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: Dict[str, Any]: A dictionary with the content field as JSON containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return content_dict if content_dict else {} def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a JSON dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the JSON content field content_json = db_row.get("content", {}) or {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/singlestore/utils.py", "license": "Apache License 2.0", "lines": 315, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/sqlite/schemas.py
"""Table schemas and related utils used by the SqliteDb class""" from typing import Any try: from sqlalchemy.types import JSON, BigInteger, Boolean, Date, String except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") SESSION_TABLE_SCHEMA = { "session_id": {"type": String, "primary_key": True, "nullable": False}, "session_type": {"type": String, "nullable": False, "index": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "workflow_id": {"type": String, "nullable": True}, "user_id": {"type": String, "nullable": True}, "session_data": {"type": JSON, "nullable": True}, "agent_data": {"type": JSON, "nullable": True}, "team_data": {"type": JSON, "nullable": True}, "workflow_data": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "runs": {"type": JSON, "nullable": True}, "summary": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } USER_MEMORY_TABLE_SCHEMA = { "memory_id": {"type": String, "primary_key": True, "nullable": False}, "memory": {"type": JSON, "nullable": False}, "input": {"type": String, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "user_id": {"type": String, "nullable": True, "index": True}, "topics": {"type": JSON, "nullable": True}, "feedback": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True, "index": True}, } EVAL_TABLE_SCHEMA = { "run_id": {"type": String, "primary_key": True, "nullable": False}, "eval_type": {"type": String, "nullable": False}, "eval_data": {"type": JSON, "nullable": False}, "eval_input": {"type": JSON, "nullable": False}, "name": {"type": String, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, "workflow_id": {"type": String, "nullable": True}, "model_id": {"type": String, "nullable": True}, "model_provider": {"type": String, "nullable": True}, "evaluated_component_name": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False}, "description": {"type": String, "nullable": False}, "metadata": {"type": JSON, "nullable": True}, "type": {"type": String, "nullable": True}, "size": {"type": BigInteger, "nullable": True}, "linked_to": {"type": String, "nullable": True}, "access_count": {"type": BigInteger, "nullable": True}, "status": {"type": String, "nullable": True}, "status_message": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "external_id": {"type": String, "nullable": True}, } METRICS_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "agent_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_runs_count": {"type": BigInteger, "nullable": False, "default": 0}, "agent_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "team_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "workflow_sessions_count": {"type": BigInteger, "nullable": False, "default": 0}, "users_count": {"type": BigInteger, "nullable": False, "default": 0}, "token_metrics": {"type": JSON, "nullable": False, "default": "{}"}, "model_metrics": {"type": JSON, "nullable": False, "default": "{}"}, "date": {"type": Date, "nullable": False, "index": True}, "aggregation_period": {"type": String, "nullable": False, "index": True}, "created_at": {"type": BigInteger, "nullable": False}, "updated_at": {"type": BigInteger, "nullable": True}, "completed": {"type": Boolean, "nullable": False, "default": False}, "_unique_constraints": [ { "name": "uq_metrics_date_period", "columns": ["date", "aggregation_period"], } ], } TRACE_TABLE_SCHEMA = { "trace_id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False}, "status": {"type": String, "nullable": False, "index": True}, "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "run_id": {"type": String, "nullable": True, "index": True}, "session_id": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string } def _get_span_table_schema(traces_table_name: str = "agno_traces") -> dict[str, Any]: """Get the span table schema with the correct foreign key reference. Args: traces_table_name: The name of the traces table to reference in the foreign key. Returns: The span table schema dictionary. """ return { "span_id": {"type": String, "primary_key": True, "nullable": False}, "trace_id": { "type": String, "nullable": False, "index": True, "foreign_key": f"{traces_table_name}.trace_id", }, "parent_span_id": {"type": String, "nullable": True, "index": True}, "name": {"type": String, "nullable": False}, "span_kind": {"type": String, "nullable": False}, "status_code": {"type": String, "nullable": False}, "status_message": {"type": String, "nullable": True}, "start_time": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string "end_time": {"type": String, "nullable": False}, # ISO 8601 datetime string "duration_ms": {"type": BigInteger, "nullable": False}, "attributes": {"type": JSON, "nullable": True}, "created_at": {"type": String, "nullable": False, "index": True}, # ISO 8601 datetime string } CULTURAL_KNOWLEDGE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False, "index": True}, "summary": {"type": String, "nullable": True}, "content": {"type": JSON, "nullable": True}, "metadata": {"type": JSON, "nullable": True}, "input": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True}, "updated_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": String, "nullable": True}, "team_id": {"type": String, "nullable": True}, } VERSIONS_TABLE_SCHEMA = { "table_name": {"type": String, "nullable": False, "primary_key": True}, "version": {"type": String, "nullable": False}, "created_at": {"type": String, "nullable": False, "index": True}, "updated_at": {"type": String, "nullable": True}, } COMPONENTS_TABLE_SCHEMA = { "component_id": {"type": String, "primary_key": True}, "component_type": {"type": String, "nullable": False, "index": True}, # agent|team|workflow "name": {"type": String, "nullable": False, "index": True}, "description": {"type": String, "nullable": True}, "current_version": {"type": BigInteger, "nullable": True, "index": True}, "metadata": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "deleted_at": {"type": BigInteger, "nullable": True}, } COMPONENT_CONFIGS_TABLE_SCHEMA = { "component_id": {"type": String, "primary_key": True, "nullable": False}, "version": {"type": BigInteger, "primary_key": True, "nullable": False}, "label": {"type": String, "nullable": True}, # stable|v1.2.0|pre-refactor "stage": {"type": String, "nullable": False, "default": "draft", "index": True}, # draft|published "config": {"type": JSON, "nullable": False}, "notes": {"type": String, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } COMPONENT_LINKS_TABLE_SCHEMA = { "parent_component_id": {"type": String, "primary_key": True, "nullable": False}, "parent_version": {"type": BigInteger, "primary_key": True, "nullable": False}, "link_kind": {"type": String, "primary_key": True, "nullable": False, "index": True}, "link_key": {"type": String, "primary_key": True, "nullable": False}, "child_component_id": {"type": String, "nullable": False}, "child_version": {"type": BigInteger, "nullable": True}, "position": {"type": BigInteger, "nullable": False}, "meta": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": True, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } LEARNINGS_TABLE_SCHEMA = { "learning_id": {"type": String, "primary_key": True, "nullable": False}, "learning_type": {"type": String, "nullable": False, "index": True}, "namespace": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "session_id": {"type": String, "nullable": True, "index": True}, "entity_id": {"type": String, "nullable": True, "index": True}, "entity_type": {"type": String, "nullable": True, "index": True}, "content": {"type": JSON, "nullable": False}, "metadata": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, } SCHEDULE_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "name": {"type": String, "nullable": False, "index": True}, "description": {"type": String, "nullable": True}, "method": {"type": String, "nullable": False}, "endpoint": {"type": String, "nullable": False}, "payload": {"type": JSON, "nullable": True}, "cron_expr": {"type": String, "nullable": False}, "timezone": {"type": String, "nullable": False}, "timeout_seconds": {"type": BigInteger, "nullable": False}, "max_retries": {"type": BigInteger, "nullable": False}, "retry_delay_seconds": {"type": BigInteger, "nullable": False}, "enabled": {"type": Boolean, "nullable": False, "default": True}, "next_run_at": {"type": BigInteger, "nullable": True, "index": True}, "locked_by": {"type": String, "nullable": True}, "locked_at": {"type": BigInteger, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, "__composite_indexes__": [ {"name": "enabled_next_run_at", "columns": ["enabled", "next_run_at"]}, ], } APPROVAL_TABLE_SCHEMA = { "id": {"type": String, "primary_key": True, "nullable": False}, "run_id": {"type": String, "nullable": False, "index": True}, "session_id": {"type": String, "nullable": False, "index": True}, "status": {"type": String, "nullable": False, "index": True}, "source_type": {"type": String, "nullable": False, "index": True}, "approval_type": {"type": String, "nullable": True, "index": True}, "pause_type": {"type": String, "nullable": False, "index": True}, "tool_name": {"type": String, "nullable": True}, "tool_args": {"type": JSON, "nullable": True}, "expires_at": {"type": BigInteger, "nullable": True}, "agent_id": {"type": String, "nullable": True, "index": True}, "team_id": {"type": String, "nullable": True, "index": True}, "workflow_id": {"type": String, "nullable": True, "index": True}, "user_id": {"type": String, "nullable": True, "index": True}, "schedule_id": {"type": String, "nullable": True, "index": True}, "schedule_run_id": {"type": String, "nullable": True, "index": True}, "source_name": {"type": String, "nullable": True}, "requirements": {"type": JSON, "nullable": True}, "context": {"type": JSON, "nullable": True}, "resolution_data": {"type": JSON, "nullable": True}, "resolved_by": {"type": String, "nullable": True}, "resolved_at": {"type": BigInteger, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, "updated_at": {"type": BigInteger, "nullable": True}, # Run status from the associated run. Updated when run completes/errors/cancels. # Values: "PAUSED", "COMPLETED", "RUNNING", "ERROR", "CANCELLED", or None. "run_status": {"type": String, "nullable": True, "index": True}, } def _get_schedule_runs_table_schema(schedules_table_name: str = "agno_schedules") -> dict[str, Any]: """Get the schedule runs table schema with a foreign key to the schedules table.""" return { "id": {"type": String, "primary_key": True, "nullable": False}, "schedule_id": { "type": String, "nullable": False, "index": True, "foreign_key": f"{schedules_table_name}.id", "ondelete": "CASCADE", }, "attempt": {"type": BigInteger, "nullable": False}, "triggered_at": {"type": BigInteger, "nullable": True}, "completed_at": {"type": BigInteger, "nullable": True}, "status": {"type": String, "nullable": False, "index": True}, "status_code": {"type": BigInteger, "nullable": True}, "run_id": {"type": String, "nullable": True}, "session_id": {"type": String, "nullable": True}, "error": {"type": String, "nullable": True}, "input": {"type": JSON, "nullable": True}, "output": {"type": JSON, "nullable": True}, "requirements": {"type": JSON, "nullable": True}, "created_at": {"type": BigInteger, "nullable": False, "index": True}, } def get_table_schema_definition( table_type: str, traces_table_name: str = "agno_traces", schedules_table_name: str = "agno_schedules", ) -> dict[str, Any]: """ Get the expected schema definition for the given table. Args: table_type (str): The type of table to get the schema for. traces_table_name (str): The name of the traces table (used for spans foreign key). schedules_table_name (str): The name of the schedules table (used for schedule_runs foreign key). Returns: Dict[str, Any]: Dictionary containing column definitions for the table """ # Handle tables with dynamic foreign key references if table_type == "spans": return _get_span_table_schema(traces_table_name) if table_type == "schedule_runs": return _get_schedule_runs_table_schema(schedules_table_name) schemas = { "sessions": SESSION_TABLE_SCHEMA, "evals": EVAL_TABLE_SCHEMA, "metrics": METRICS_TABLE_SCHEMA, "memories": USER_MEMORY_TABLE_SCHEMA, "knowledge": KNOWLEDGE_TABLE_SCHEMA, "traces": TRACE_TABLE_SCHEMA, "culture": CULTURAL_KNOWLEDGE_TABLE_SCHEMA, "versions": VERSIONS_TABLE_SCHEMA, "components": COMPONENTS_TABLE_SCHEMA, "component_configs": COMPONENT_CONFIGS_TABLE_SCHEMA, "component_links": COMPONENT_LINKS_TABLE_SCHEMA, "learnings": LEARNINGS_TABLE_SCHEMA, "schedules": SCHEDULE_TABLE_SCHEMA, "approvals": APPROVAL_TABLE_SCHEMA, } schema = schemas.get(table_type, {}) if not schema: raise ValueError(f"Unknown table type: {table_type}") return schema # type: ignore[return-value]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/sqlite/schemas.py", "license": "Apache License 2.0", "lines": 310, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/sqlite/sqlite.py
import time from datetime import date, datetime, timedelta, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Set, Tuple, Union, cast from uuid import uuid4 if TYPE_CHECKING: from agno.tracing.schemas import Span, Trace from agno.db.base import BaseDb, ComponentType, SessionType from agno.db.migrations.manager import MigrationManager from agno.db.schemas.culture import CulturalKnowledge from agno.db.schemas.evals import EvalFilterType, EvalRunRecord, EvalType from agno.db.schemas.knowledge import KnowledgeRow from agno.db.schemas.memory import UserMemory from agno.db.sqlite.schemas import get_table_schema_definition from agno.db.sqlite.utils import ( apply_sorting, bulk_upsert_metrics, calculate_date_metrics, deserialize_cultural_knowledge_from_db, fetch_all_sessions_data, get_dates_to_calculate_metrics_for, is_table_available, is_valid_table, serialize_cultural_knowledge_for_db, ) from agno.db.utils import deserialize_session_json_fields, serialize_session_json_fields from agno.run.base import RunStatus from agno.session import AgentSession, Session, TeamSession, WorkflowSession from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id try: from sqlalchemy import Column, MetaData, String, Table, func, or_, select, text from sqlalchemy.dialects import sqlite from sqlalchemy.engine import Engine, create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.schema import ForeignKey, Index, UniqueConstraint except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") class SqliteDb(BaseDb): def __init__( self, db_file: Optional[str] = None, db_engine: Optional[Engine] = None, db_url: Optional[str] = None, session_table: Optional[str] = None, culture_table: Optional[str] = None, memory_table: Optional[str] = None, metrics_table: Optional[str] = None, eval_table: Optional[str] = None, knowledge_table: Optional[str] = None, traces_table: Optional[str] = None, spans_table: Optional[str] = None, versions_table: Optional[str] = None, components_table: Optional[str] = None, component_configs_table: Optional[str] = None, component_links_table: Optional[str] = None, learnings_table: Optional[str] = None, schedules_table: Optional[str] = None, schedule_runs_table: Optional[str] = None, approvals_table: Optional[str] = None, id: Optional[str] = None, ): """ Interface for interacting with a SQLite database. The following order is used to determine the database connection: 1. Use the db_engine 2. Use the db_url 3. Use the db_file 4. Create a new database in the current directory Args: db_file (Optional[str]): The database file to connect to. db_engine (Optional[Engine]): The SQLAlchemy database engine to use. db_url (Optional[str]): The database URL to connect to. session_table (Optional[str]): Name of the table to store Agent, Team and Workflow sessions. culture_table (Optional[str]): Name of the table to store cultural notions. memory_table (Optional[str]): Name of the table to store user memories. metrics_table (Optional[str]): Name of the table to store metrics. eval_table (Optional[str]): Name of the table to store evaluation runs data. knowledge_table (Optional[str]): Name of the table to store knowledge documents data. traces_table (Optional[str]): Name of the table to store run traces. spans_table (Optional[str]): Name of the table to store span events. versions_table (Optional[str]): Name of the table to store schema versions. components_table (Optional[str]): Name of the table to store components. component_configs_table (Optional[str]): Name of the table to store component configurations. component_links_table (Optional[str]): Name of the table to store component links. learnings_table (Optional[str]): Name of the table to store learning records. schedules_table (Optional[str]): Name of the table to store cron schedules. schedule_runs_table (Optional[str]): Name of the table to store schedule run history. id (Optional[str]): ID of the database. Raises: ValueError: If none of the tables are provided. """ if id is None: seed = db_url or db_file or str(db_engine.url) if db_engine else "sqlite:///agno.db" id = generate_id(seed) super().__init__( id=id, session_table=session_table, culture_table=culture_table, memory_table=memory_table, metrics_table=metrics_table, eval_table=eval_table, knowledge_table=knowledge_table, traces_table=traces_table, spans_table=spans_table, versions_table=versions_table, components_table=components_table, component_configs_table=component_configs_table, component_links_table=component_links_table, learnings_table=learnings_table, schedules_table=schedules_table, schedule_runs_table=schedule_runs_table, approvals_table=approvals_table, ) _engine: Optional[Engine] = db_engine if _engine is None: if db_url is not None: _engine = create_engine(db_url) elif db_file is not None: db_path = Path(db_file).resolve() db_path.parent.mkdir(parents=True, exist_ok=True) db_file = str(db_path) _engine = create_engine(f"sqlite:///{db_path}") else: # If none of db_engine, db_url, or db_file are provided, create a db in the current directory default_db_path = Path("./agno.db").resolve() _engine = create_engine(f"sqlite:///{default_db_path}") db_file = str(default_db_path) log_debug(f"Created SQLite database: {default_db_path}") self.db_engine: Engine = _engine self.db_url: Optional[str] = db_url self.db_file: Optional[str] = db_file self.metadata: MetaData = MetaData() # Initialize database session self.Session: scoped_session = scoped_session(sessionmaker(bind=self.db_engine)) # -- Serialization methods -- def to_dict(self) -> Dict[str, Any]: base = super().to_dict() base.update( { "db_file": self.db_file, "db_url": self.db_url, "type": "sqlite", } ) return base @classmethod def from_dict(cls, data: Dict[str, Any]) -> "SqliteDb": return cls( db_file=data.get("db_file"), db_url=data.get("db_url"), session_table=data.get("session_table"), culture_table=data.get("culture_table"), memory_table=data.get("memory_table"), metrics_table=data.get("metrics_table"), eval_table=data.get("eval_table"), knowledge_table=data.get("knowledge_table"), traces_table=data.get("traces_table"), spans_table=data.get("spans_table"), versions_table=data.get("versions_table"), components_table=data.get("components_table"), component_configs_table=data.get("component_configs_table"), component_links_table=data.get("component_links_table"), learnings_table=data.get("learnings_table"), schedules_table=data.get("schedules_table"), schedule_runs_table=data.get("schedule_runs_table"), approvals_table=data.get("approvals_table"), id=data.get("id"), ) def close(self) -> None: """Close database connections and dispose of the connection pool. Should be called during application shutdown to properly release all database connections. """ if self.db_engine is not None: self.db_engine.dispose() # -- DB methods -- def table_exists(self, table_name: str) -> bool: """Check if a table with the given name exists in the SQLite database. Args: table_name: Name of the table to check Returns: bool: True if the table exists in the database, False otherwise """ with self.Session() as sess: return is_table_available(session=sess, table_name=table_name) def _create_all_tables(self): """Create all tables for the database.""" tables_to_create = [ (self.session_table_name, "sessions"), (self.memory_table_name, "memories"), (self.metrics_table_name, "metrics"), (self.eval_table_name, "evals"), (self.knowledge_table_name, "knowledge"), (self.versions_table_name, "versions"), (self.components_table_name, "components"), (self.component_configs_table_name, "component_configs"), (self.component_links_table_name, "component_links"), (self.learnings_table_name, "learnings"), (self.schedules_table_name, "schedules"), (self.schedule_runs_table_name, "schedule_runs"), (self.approvals_table_name, "approvals"), ] for table_name, table_type in tables_to_create: self._get_or_create_table(table_name=table_name, table_type=table_type, create_table_if_not_found=True) def _create_table(self, table_name: str, table_type: str) -> Table: """ Create a table with the appropriate schema based on the table type. Supports: - _unique_constraints: [{"name": "...", "columns": [...]}] - __primary_key__: ["col1", "col2", ...] - __foreign_keys__: [{"columns":[...], "ref_table":"...", "ref_columns":[...]}] - column-level foreign_key: "logical_table.column" (resolved via _resolve_* helpers) Args: table_name (str): Name of the table to create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object """ try: from sqlalchemy.schema import ForeignKeyConstraint, PrimaryKeyConstraint # Pass table names for foreign key resolution table_schema = get_table_schema_definition( table_type, traces_table_name=self.trace_table_name, schedules_table_name=self.schedules_table_name, ).copy() columns: List[Column] = [] indexes: List[str] = [] # Extract special schema keys before iterating columns schema_unique_constraints = table_schema.pop("_unique_constraints", []) schema_primary_key = table_schema.pop("__primary_key__", None) schema_foreign_keys = table_schema.pop("__foreign_keys__", []) schema_composite_indexes = table_schema.pop("__composite_indexes__", []) # Build columns for col_name, col_config in table_schema.items(): column_args = [col_name, col_config["type"]()] column_kwargs: Dict[str, Any] = {} # Column-level PK only if no composite PK is defined if col_config.get("primary_key", False) and schema_primary_key is None: column_kwargs["primary_key"] = True if "nullable" in col_config: column_kwargs["nullable"] = col_config["nullable"] if "default" in col_config: column_kwargs["default"] = col_config["default"] if col_config.get("index", False): indexes.append(col_name) if col_config.get("unique", False): column_kwargs["unique"] = True # Single-column FK if "foreign_key" in col_config: fk_ref = self._resolve_fk_reference(col_config["foreign_key"]) fk_kwargs: Dict[str, Any] = {} if "ondelete" in col_config: fk_kwargs["ondelete"] = col_config["ondelete"] column_args.append(ForeignKey(fk_ref, **fk_kwargs)) columns.append(Column(*column_args, **column_kwargs)) # type: ignore # Create the table object table = Table(table_name, self.metadata, *columns) # Composite PK if schema_primary_key is not None: missing = [c for c in schema_primary_key if c not in table.c] if missing: raise ValueError(f"Composite PK references missing columns in {table_name}: {missing}") pk_constraint_name = f"{table_name}_pkey" table.append_constraint(PrimaryKeyConstraint(*schema_primary_key, name=pk_constraint_name)) # Composite FKs for fk_config in schema_foreign_keys: fk_columns = fk_config["columns"] ref_table_logical = fk_config["ref_table"] ref_columns = fk_config["ref_columns"] if len(fk_columns) != len(ref_columns): raise ValueError( f"Composite FK in {table_name} has mismatched columns/ref_columns: {fk_columns} vs {ref_columns}" ) missing = [c for c in fk_columns if c not in table.c] if missing: raise ValueError(f"Composite FK references missing columns in {table_name}: {missing}") resolved_ref_table = self._resolve_table_name(ref_table_logical) fk_constraint_name = f"{table_name}_{'_'.join(fk_columns)}_fkey" ref_column_strings = [f"{resolved_ref_table}.{col}" for col in ref_columns] table.append_constraint( ForeignKeyConstraint( fk_columns, ref_column_strings, name=fk_constraint_name, ) ) # Multi-column unique constraints for constraint in schema_unique_constraints: constraint_name = f"{table_name}_{constraint['name']}" constraint_columns = constraint["columns"] missing = [c for c in constraint_columns if c not in table.c] if missing: raise ValueError(f"Unique constraint references missing columns in {table_name}: {missing}") table.append_constraint(UniqueConstraint(*constraint_columns, name=constraint_name)) # Indexes for idx_col in indexes: if idx_col not in table.c: raise ValueError(f"Index references missing column in {table_name}: {idx_col}") idx_name = f"idx_{table_name}_{idx_col}" Index(idx_name, table.c[idx_col]) # Correct way; do NOT append as constraint # Composite indexes for idx_config in schema_composite_indexes: idx_name = f"idx_{table_name}_{'_'.join(idx_config['columns'])}" idx_cols = [table.c[c] for c in idx_config["columns"]] Index(idx_name, *idx_cols) # Create table table_created = False if not self.table_exists(table_name): table.create(self.db_engine, checkfirst=True) log_debug(f"Successfully created table '{table_name}'") table_created = True else: log_debug(f"Table '{table_name}' already exists, skipping creation") # Create indexes (SQLite) for idx in table.indexes: try: # Check if index already exists with self.Session() as sess: exists_query = text("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = :index_name") exists = sess.execute(exists_query, {"index_name": idx.name}).scalar() is not None if exists: log_debug(f"Index {idx.name} already exists in table {table_name}, skipping creation") continue idx.create(self.db_engine) log_debug(f"Created index: {idx.name} for table {table_name}") except Exception as e: log_warning(f"Error creating index {idx.name}: {e}") # Store the schema version for the created table if table_name != self.versions_table_name and table_created: latest_schema_version = MigrationManager(self).latest_schema_version self.upsert_schema_version(table_name=table_name, version=latest_schema_version.public) return table except Exception as e: from traceback import print_exc print_exc() log_error(f"Could not create table '{table_name}': {e}") raise e def _resolve_fk_reference(self, fk_ref: str) -> str: """ Resolve a simple foreign key reference to the actual table name. Accepts: - "logical_table.column" -> "{resolved_table}.{column}" - already-qualified refs -> returned as-is """ parts = fk_ref.split(".") if len(parts) == 2: table, column = parts resolved_table = self._resolve_table_name(table) return f"{resolved_table}.{column}" return fk_ref def _resolve_table_name(self, logical_name: str) -> str: """ Resolve logical table name to configured table name. """ table_map = { "components": self.components_table_name, "component_configs": self.component_configs_table_name, "component_links": self.component_links_table_name, "traces": self.trace_table_name, "spans": self.span_table_name, "sessions": self.session_table_name, "memories": self.memory_table_name, "metrics": self.metrics_table_name, "evals": self.eval_table_name, "knowledge": self.knowledge_table_name, "culture": self.culture_table_name, "versions": self.versions_table_name, } return table_map.get(logical_name, logical_name) def _get_table(self, table_type: str, create_table_if_not_found: Optional[bool] = False) -> Optional[Table]: if table_type == "sessions": self.session_table = self._get_or_create_table( table_name=self.session_table_name, table_type=table_type, create_table_if_not_found=create_table_if_not_found, ) return self.session_table elif table_type == "memories": self.memory_table = self._get_or_create_table( table_name=self.memory_table_name, table_type="memories", create_table_if_not_found=create_table_if_not_found, ) return self.memory_table elif table_type == "metrics": self.metrics_table = self._get_or_create_table( table_name=self.metrics_table_name, table_type="metrics", create_table_if_not_found=create_table_if_not_found, ) return self.metrics_table elif table_type == "evals": self.eval_table = self._get_or_create_table( table_name=self.eval_table_name, table_type="evals", create_table_if_not_found=create_table_if_not_found, ) return self.eval_table elif table_type == "knowledge": self.knowledge_table = self._get_or_create_table( table_name=self.knowledge_table_name, table_type="knowledge", create_table_if_not_found=create_table_if_not_found, ) return self.knowledge_table elif table_type == "traces": self.traces_table = self._get_or_create_table( table_name=self.trace_table_name, table_type="traces", create_table_if_not_found=create_table_if_not_found, ) return self.traces_table elif table_type == "spans": # Ensure traces table exists first (spans has FK to traces) if create_table_if_not_found: self._get_table(table_type="traces", create_table_if_not_found=True) self.spans_table = self._get_or_create_table( table_name=self.span_table_name, table_type="spans", create_table_if_not_found=create_table_if_not_found, ) return self.spans_table elif table_type == "culture": self.culture_table = self._get_or_create_table( table_name=self.culture_table_name, table_type="culture", create_table_if_not_found=create_table_if_not_found, ) return self.culture_table elif table_type == "versions": self.versions_table = self._get_or_create_table( table_name=self.versions_table_name, table_type="versions", create_table_if_not_found=create_table_if_not_found, ) return self.versions_table elif table_type == "components": self.components_table = self._get_or_create_table( table_name=self.components_table_name, table_type="components", create_table_if_not_found=create_table_if_not_found, ) return self.components_table elif table_type == "component_configs": # Ensure components table exists first (configs references components) if create_table_if_not_found: self._get_table(table_type="components", create_table_if_not_found=True) self.component_configs_table = self._get_or_create_table( table_name=self.component_configs_table_name, table_type="component_configs", create_table_if_not_found=create_table_if_not_found, ) return self.component_configs_table elif table_type == "component_links": # Ensure components and component_configs tables exist first if create_table_if_not_found: self._get_table(table_type="components", create_table_if_not_found=True) self._get_table(table_type="component_configs", create_table_if_not_found=True) self.component_links_table = self._get_or_create_table( table_name=self.component_links_table_name, table_type="component_links", create_table_if_not_found=create_table_if_not_found, ) return self.component_links_table elif table_type == "learnings": self.learnings_table = self._get_or_create_table( table_name=self.learnings_table_name, table_type="learnings", create_table_if_not_found=create_table_if_not_found, ) return self.learnings_table elif table_type == "schedules": self.schedules_table = self._get_or_create_table( table_name=self.schedules_table_name, table_type="schedules", create_table_if_not_found=create_table_if_not_found, ) return self.schedules_table elif table_type == "schedule_runs": self.schedule_runs_table = self._get_or_create_table( table_name=self.schedule_runs_table_name, table_type="schedule_runs", create_table_if_not_found=create_table_if_not_found, ) return self.schedule_runs_table elif table_type == "approvals": self.approvals_table = self._get_or_create_table( table_name=self.approvals_table_name, table_type="approvals", create_table_if_not_found=create_table_if_not_found, ) return self.approvals_table else: raise ValueError(f"Unknown table type: '{table_type}'") def _get_or_create_table( self, table_name: str, table_type: str, create_table_if_not_found: Optional[bool] = False, ) -> Optional[Table]: """ Check if the table exists and is valid, else create it. Args: table_name (str): Name of the table to get or create table_type (str): Type of table (used to get schema definition) Returns: Table: SQLAlchemy Table object """ with self.Session() as sess, sess.begin(): table_is_available = is_table_available(session=sess, table_name=table_name) if not table_is_available: if not create_table_if_not_found: return None return self._create_table(table_name=table_name, table_type=table_type) # SQLite version of table validation (no schema) if not is_valid_table(db_engine=self.db_engine, table_name=table_name, table_type=table_type): raise ValueError(f"Table {table_name} has an invalid schema") try: table = Table(table_name, self.metadata, autoload_with=self.db_engine) return table except Exception as e: log_error(f"Error loading existing table {table_name}: {e}") raise e def get_latest_schema_version(self, table_name: str): """Get the latest version of the database schema.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return "2.0.0" with self.Session() as sess: stmt = select(table) # Latest version for the given table stmt = stmt.where(table.c.table_name == table_name) stmt = stmt.order_by(table.c.version.desc()).limit(1) result = sess.execute(stmt).fetchone() if result is None: return "2.0.0" version_dict = dict(result._mapping) return version_dict.get("version") or "2.0.0" def upsert_schema_version(self, table_name: str, version: str) -> None: """Upsert the schema version into the database.""" table = self._get_table(table_type="versions", create_table_if_not_found=True) if table is None: return current_datetime = datetime.now().isoformat() with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( table_name=table_name, version=version, created_at=current_datetime, # Store as ISO format string updated_at=current_datetime, ) # Update version if table_name already exists stmt = stmt.on_conflict_do_update( index_elements=["table_name"], set_=dict(version=version, updated_at=current_datetime), ) sess.execute(stmt) # -- Session methods -- def delete_session(self, session_id: str, user_id: Optional[str] = None) -> bool: """ Delete a session from the database. Args: session_id (str): ID of the session to delete user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return False with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id == session_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No session found to delete with session_id: {session_id}") return False else: log_debug(f"Successfully deleted session with session_id: {session_id}") return True except Exception as e: log_error(f"Error deleting session: {e}") raise e def delete_sessions(self, session_ids: List[str], user_id: Optional[str] = None) -> None: """Delete all given sessions from the database. Can handle multiple session types in the same run. Args: session_ids (List[str]): The IDs of the sessions to delete. user_id (Optional[str]): User ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="sessions") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.session_id.in_(session_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) log_debug(f"Successfully deleted {result.rowcount} sessions") except Exception as e: log_error(f"Error deleting sessions: {e}") raise e def get_session( self, session_id: str, session_type: SessionType, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Read a session from the database. Args: session_id (str): ID of the session to read. session_type (SessionType): Type of session to get. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.session_id == session_id) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if result is None: return None session_raw = deserialize_session_json_fields(dict(result._mapping)) if not session_raw or not deserialize: return session_raw if session_type == SessionType.AGENT: return AgentSession.from_dict(session_raw) elif session_type == SessionType.TEAM: return TeamSession.from_dict(session_raw) elif session_type == SessionType.WORKFLOW: return WorkflowSession.from_dict(session_raw) else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_debug(f"Exception reading from sessions table: {e}") raise e def get_sessions( self, session_type: Optional[SessionType] = None, user_id: Optional[str] = None, component_id: Optional[str] = None, session_name: Optional[str] = None, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[Session], Tuple[List[Dict[str, Any]], int]]: """ Get all sessions in the given table. Can filter by user_id and entity_id. Args: session_type (Optional[SessionType]): The type of session to get. user_id (Optional[str]): The ID of the user to filter by. component_id (Optional[str]): The ID of the agent / workflow to filter by. session_name (Optional[str]): The name of the session to filter by. start_timestamp (Optional[int]): The start timestamp to filter by. end_timestamp (Optional[int]): The end timestamp to filter by. limit (Optional[int]): The maximum number of sessions to return. Defaults to None. page (Optional[int]): The page number to return. Defaults to None. sort_by (Optional[str]): The field to sort by. Defaults to None. sort_order (Optional[str]): The sort order. Defaults to None. deserialize (Optional[bool]): Whether to serialize the sessions. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: List[Session]: - When deserialize=True: List of Session objects matching the criteria. - When deserialize=False: List of Session dictionaries matching the criteria. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if component_id is not None: if session_type == SessionType.AGENT: stmt = stmt.where(table.c.agent_id == component_id) elif session_type == SessionType.TEAM: stmt = stmt.where(table.c.team_id == component_id) elif session_type == SessionType.WORKFLOW: stmt = stmt.where(table.c.workflow_id == component_id) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) if session_name is not None: stmt = stmt.where(table.c.session_data.like(f"%{session_name}%")) if session_type is not None: stmt = stmt.where(table.c.session_type == session_type.value) # Getting total count count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) records = sess.execute(stmt).fetchall() if records is None: return [] if deserialize else ([], 0) sessions_raw = [deserialize_session_json_fields(dict(record._mapping)) for record in records] if not deserialize: return sessions_raw, total_count if not sessions_raw: return [] if session_type == SessionType.AGENT: return [AgentSession.from_dict(record) for record in sessions_raw] # type: ignore elif session_type == SessionType.TEAM: return [TeamSession.from_dict(record) for record in sessions_raw] # type: ignore elif session_type == SessionType.WORKFLOW: return [WorkflowSession.from_dict(record) for record in sessions_raw] # type: ignore else: raise ValueError(f"Invalid session type: {session_type}") except Exception as e: log_debug(f"Exception reading from sessions table: {e}") raise e def rename_session( self, session_id: str, session_type: SessionType, session_name: str, user_id: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Optional[Union[Session, Dict[str, Any]]]: """ Rename a session in the database. Args: session_id (str): The ID of the session to rename. session_type (SessionType): The type of session to rename. session_name (str): The new name for the session. user_id (Optional[str]): User ID to filter by. Defaults to None. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Union[Session, Dict[str, Any]]]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during renaming. """ try: # Get the current session as a deserialized object # Get the session record session = self.get_session(session_id, session_type, user_id=user_id, deserialize=True) if session is None: return None session = cast(Session, session) # Update the session name if session.session_data is None: session.session_data = {} session.session_data["session_name"] = session_name # Upsert the updated session back to the database return self.upsert_session(session, deserialize=deserialize) except Exception as e: log_error(f"Exception renaming session: {e}") raise e def upsert_session( self, session: Session, deserialize: Optional[bool] = True ) -> Optional[Union[Session, Dict[str, Any]]]: """ Insert or update a session in the database. Args: session (Session): The session data to upsert. deserialize (Optional[bool]): Whether to serialize the session. Defaults to True. Returns: Optional[Session]: - When deserialize=True: Session object - When deserialize=False: Session dictionary Raises: Exception: If an error occurs during upserting. """ try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: return None serialized_session = serialize_session_json_fields(session.to_dict()) if isinstance(session, AgentSession): with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( session_id=serialized_session.get("session_id"), session_type=SessionType.AGENT.value, agent_id=serialized_session.get("agent_id"), user_id=serialized_session.get("user_id"), agent_data=serialized_session.get("agent_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), runs=serialized_session.get("runs"), summary=serialized_session.get("summary"), created_at=serialized_session.get("created_at"), updated_at=serialized_session.get("created_at"), ) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( agent_id=serialized_session.get("agent_id"), user_id=serialized_session.get("user_id"), runs=serialized_session.get("runs"), summary=serialized_session.get("summary"), agent_data=serialized_session.get("agent_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), updated_at=int(time.time()), ), where=(table.c.user_id == serialized_session.get("user_id")) | (table.c.user_id.is_(None)), ) stmt = stmt.returning(*table.columns) # type: ignore result = sess.execute(stmt) row = result.fetchone() session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None if session_raw is None or not deserialize: return session_raw return AgentSession.from_dict(session_raw) elif isinstance(session, TeamSession): with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( session_id=serialized_session.get("session_id"), session_type=SessionType.TEAM.value, team_id=serialized_session.get("team_id"), user_id=serialized_session.get("user_id"), runs=serialized_session.get("runs"), summary=serialized_session.get("summary"), created_at=serialized_session.get("created_at"), updated_at=serialized_session.get("created_at"), team_data=serialized_session.get("team_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), ) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( team_id=serialized_session.get("team_id"), user_id=serialized_session.get("user_id"), summary=serialized_session.get("summary"), runs=serialized_session.get("runs"), team_data=serialized_session.get("team_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), updated_at=int(time.time()), ), where=(table.c.user_id == serialized_session.get("user_id")) | (table.c.user_id.is_(None)), ) stmt = stmt.returning(*table.columns) # type: ignore result = sess.execute(stmt) row = result.fetchone() session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None if session_raw is None or not deserialize: return session_raw return TeamSession.from_dict(session_raw) else: with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( session_id=serialized_session.get("session_id"), session_type=SessionType.WORKFLOW.value, workflow_id=serialized_session.get("workflow_id"), user_id=serialized_session.get("user_id"), runs=serialized_session.get("runs"), summary=serialized_session.get("summary"), created_at=serialized_session.get("created_at") or int(time.time()), updated_at=serialized_session.get("updated_at") or int(time.time()), workflow_data=serialized_session.get("workflow_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), ) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( workflow_id=serialized_session.get("workflow_id"), user_id=serialized_session.get("user_id"), summary=serialized_session.get("summary"), runs=serialized_session.get("runs"), workflow_data=serialized_session.get("workflow_data"), session_data=serialized_session.get("session_data"), metadata=serialized_session.get("metadata"), updated_at=int(time.time()), ), where=(table.c.user_id == serialized_session.get("user_id")) | (table.c.user_id.is_(None)), ) stmt = stmt.returning(*table.columns) # type: ignore result = sess.execute(stmt) row = result.fetchone() session_raw = deserialize_session_json_fields(dict(row._mapping)) if row else None if session_raw is None or not deserialize: return session_raw return WorkflowSession.from_dict(session_raw) except Exception as e: log_warning(f"Exception upserting into table: {e}") raise e def upsert_sessions( self, sessions: List[Session], deserialize: Optional[bool] = True, preserve_updated_at: bool = False, ) -> List[Union[Session, Dict[str, Any]]]: """ Bulk upsert multiple sessions for improved performance on large datasets. Args: sessions (List[Session]): List of sessions to upsert. deserialize (Optional[bool]): Whether to deserialize the sessions. Defaults to True. preserve_updated_at (bool): If True, preserve the updated_at from the session object. Returns: List[Union[Session, Dict[str, Any]]]: List of upserted sessions. Raises: Exception: If an error occurs during bulk upsert. """ if not sessions: return [] try: table = self._get_table(table_type="sessions", create_table_if_not_found=True) if table is None: log_info("Sessions table not available, falling back to individual upserts") return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] # Group sessions by type for batch processing agent_sessions = [] team_sessions = [] workflow_sessions = [] for session in sessions: if isinstance(session, AgentSession): agent_sessions.append(session) elif isinstance(session, TeamSession): team_sessions.append(session) elif isinstance(session, WorkflowSession): workflow_sessions.append(session) results: List[Union[Session, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): # Bulk upsert agent sessions if agent_sessions: agent_data = [] for session in agent_sessions: serialized_session = serialize_session_json_fields(session.to_dict()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time()) agent_data.append( { "session_id": serialized_session.get("session_id"), "session_type": SessionType.AGENT.value, "agent_id": serialized_session.get("agent_id"), "user_id": serialized_session.get("user_id"), "agent_data": serialized_session.get("agent_data"), "session_data": serialized_session.get("session_data"), "metadata": serialized_session.get("metadata"), "runs": serialized_session.get("runs"), "summary": serialized_session.get("summary"), "created_at": serialized_session.get("created_at"), "updated_at": updated_at, } ) if agent_data: stmt = sqlite.insert(table) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( agent_id=stmt.excluded.agent_id, user_id=stmt.excluded.user_id, agent_data=stmt.excluded.agent_data, session_data=stmt.excluded.session_data, metadata=stmt.excluded.metadata, runs=stmt.excluded.runs, summary=stmt.excluded.summary, updated_at=stmt.excluded.updated_at, ), ) sess.execute(stmt, agent_data) # Fetch the results for agent sessions agent_ids = [session.session_id for session in agent_sessions] select_stmt = select(table).where(table.c.session_id.in_(agent_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = deserialize_session_json_fields(dict(row._mapping)) if deserialize: deserialized_agent_session = AgentSession.from_dict(session_dict) if deserialized_agent_session is None: continue results.append(deserialized_agent_session) else: results.append(session_dict) # Bulk upsert team sessions if team_sessions: team_data = [] for session in team_sessions: serialized_session = serialize_session_json_fields(session.to_dict()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time()) team_data.append( { "session_id": serialized_session.get("session_id"), "session_type": SessionType.TEAM.value, "team_id": serialized_session.get("team_id"), "user_id": serialized_session.get("user_id"), "runs": serialized_session.get("runs"), "summary": serialized_session.get("summary"), "created_at": serialized_session.get("created_at"), "updated_at": updated_at, "team_data": serialized_session.get("team_data"), "session_data": serialized_session.get("session_data"), "metadata": serialized_session.get("metadata"), } ) if team_data: stmt = sqlite.insert(table) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( team_id=stmt.excluded.team_id, user_id=stmt.excluded.user_id, team_data=stmt.excluded.team_data, session_data=stmt.excluded.session_data, metadata=stmt.excluded.metadata, runs=stmt.excluded.runs, summary=stmt.excluded.summary, updated_at=stmt.excluded.updated_at, ), ) sess.execute(stmt, team_data) # Fetch the results for team sessions team_ids = [session.session_id for session in team_sessions] select_stmt = select(table).where(table.c.session_id.in_(team_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = deserialize_session_json_fields(dict(row._mapping)) if deserialize: deserialized_team_session = TeamSession.from_dict(session_dict) if deserialized_team_session is None: continue results.append(deserialized_team_session) else: results.append(session_dict) # Bulk upsert workflow sessions if workflow_sessions: workflow_data = [] for session in workflow_sessions: serialized_session = serialize_session_json_fields(session.to_dict()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = serialized_session.get("updated_at") if preserve_updated_at else int(time.time()) workflow_data.append( { "session_id": serialized_session.get("session_id"), "session_type": SessionType.WORKFLOW.value, "workflow_id": serialized_session.get("workflow_id"), "user_id": serialized_session.get("user_id"), "runs": serialized_session.get("runs"), "summary": serialized_session.get("summary"), "created_at": serialized_session.get("created_at"), "updated_at": updated_at, "workflow_data": serialized_session.get("workflow_data"), "session_data": serialized_session.get("session_data"), "metadata": serialized_session.get("metadata"), } ) if workflow_data: stmt = sqlite.insert(table) stmt = stmt.on_conflict_do_update( index_elements=["session_id"], set_=dict( workflow_id=stmt.excluded.workflow_id, user_id=stmt.excluded.user_id, workflow_data=stmt.excluded.workflow_data, session_data=stmt.excluded.session_data, metadata=stmt.excluded.metadata, runs=stmt.excluded.runs, summary=stmt.excluded.summary, updated_at=stmt.excluded.updated_at, ), ) sess.execute(stmt, workflow_data) # Fetch the results for workflow sessions workflow_ids = [session.session_id for session in workflow_sessions] select_stmt = select(table).where(table.c.session_id.in_(workflow_ids)) result = sess.execute(select_stmt).fetchall() for row in result: session_dict = deserialize_session_json_fields(dict(row._mapping)) if deserialize: deserialized_workflow_session = WorkflowSession.from_dict(session_dict) if deserialized_workflow_session is None: continue results.append(deserialized_workflow_session) else: results.append(session_dict) return results except Exception as e: log_error(f"Exception during bulk session upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for session in sessions if session is not None for result in [self.upsert_session(session, deserialize=deserialize)] if result is not None ] # -- Memory methods -- def delete_user_memory(self, memory_id: str, user_id: Optional[str] = None): """Delete a user memory from the database. Args: memory_id (str): The ID of the memory to delete. user_id (Optional[str]): The user ID to filter by. Defaults to None. Returns: bool: True if deletion was successful, False otherwise. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id == memory_id) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted user memory id: {memory_id}") else: log_debug(f"No user memory found with id: {memory_id}") except Exception as e: log_error(f"Error deleting user memory: {e}") raise e def delete_user_memories(self, memory_ids: List[str], user_id: Optional[str] = None) -> None: """Delete user memories from the database. Args: memory_ids (List[str]): The IDs of the memories to delete. user_id (Optional[str]): The user ID to filter by. Defaults to None. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.memory_id.in_(memory_ids)) if user_id is not None: delete_stmt = delete_stmt.where(table.c.user_id == user_id) result = sess.execute(delete_stmt) if result.rowcount == 0: log_debug(f"No user memories found with ids: {memory_ids}") except Exception as e: log_error(f"Error deleting user memories: {e}") raise e def get_all_memory_topics(self) -> List[str]: """Get all memory topics from the database. Returns: List[str]: List of memory topics. """ try: table = self._get_table(table_type="memories") if table is None: return [] with self.Session() as sess, sess.begin(): # Select topics from all results stmt = select(table.c.topics) result = sess.execute(stmt).fetchall() result = result[0][0] return list(set(result)) except Exception as e: log_debug(f"Exception reading from memory table: {e}") raise e def get_user_memory( self, memory_id: str, deserialize: Optional[bool] = True, user_id: Optional[str] = None, ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Get a memory from the database. Args: memory_id (str): The ID of the memory to get. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. user_id (Optional[str]): The user ID to filter by. Defaults to None. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: Memory dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.memory_id == memory_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) result = sess.execute(stmt).fetchone() if result is None: return None memory_raw = dict(result._mapping) if not memory_raw or not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_debug(f"Exception reading from memorytable: {e}") raise e def get_user_memories( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, topics: Optional[List[str]] = None, search_content: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: """Get all memories from the database as UserMemory objects. Args: user_id (Optional[str]): The ID of the user to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. topics (Optional[List[str]]): The topics to filter by. search_content (Optional[str]): The content to search for. limit (Optional[int]): The maximum number of memories to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to serialize the memories. Defaults to True. Returns: Union[List[UserMemory], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of UserMemory objects - When deserialize=False: List of UserMemory dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="memories") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if topics is not None: for topic in topics: stmt = stmt.where(func.cast(table.c.topics, String).like(f'%"{topic}"%')) if search_content is not None: stmt = stmt.where(table.c.memory.ilike(f"%{search_content}%")) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) memories_raw = [record._mapping for record in result] if not deserialize: return memories_raw, total_count return [UserMemory.from_dict(record) for record in memories_raw] except Exception as e: log_error(f"Error reading from memory table: {e}") raise e def get_user_memory_stats( self, limit: Optional[int] = None, page: Optional[int] = None, user_id: Optional[str] = None, ) -> Tuple[List[Dict[str, Any]], int]: """Get user memories stats. Args: limit (Optional[int]): The maximum number of user stats to return. page (Optional[int]): The page number. user_id (Optional[str]): User ID for filtering. Returns: Tuple[List[Dict[str, Any]], int]: A list of dictionaries containing user stats and total count. Example: ( [ { "user_id": "123", "total_memories": 10, "last_memory_updated_at": 1714560000, }, ], total_count: 1, ) """ try: table = self._get_table(table_type="memories") if table is None: return [], 0 with self.Session() as sess, sess.begin(): stmt = select( table.c.user_id, func.count(table.c.memory_id).label("total_memories"), func.max(table.c.updated_at).label("last_memory_updated_at"), ) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) else: stmt = stmt.where(table.c.user_id.is_not(None)) stmt = stmt.group_by(table.c.user_id) stmt = stmt.order_by(func.max(table.c.updated_at).desc()) count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Pagination if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [], 0 return [ { "user_id": record.user_id, # type: ignore "total_memories": record.total_memories, "last_memory_updated_at": record.last_memory_updated_at, } for record in result ], total_count except Exception as e: log_error(f"Error getting user memory stats: {e}") raise e def upsert_user_memory( self, memory: UserMemory, deserialize: Optional[bool] = True ) -> Optional[Union[UserMemory, Dict[str, Any]]]: """Upsert a user memory in the database. Args: memory (UserMemory): The user memory to upsert. deserialize (Optional[bool]): Whether to serialize the memory. Defaults to True. Returns: Optional[Union[UserMemory, Dict[str, Any]]]: - When deserialize=True: UserMemory object - When deserialize=False: UserMemory dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: return None if memory.memory_id is None: memory.memory_id = str(uuid4()) current_time = int(time.time()) with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( user_id=memory.user_id, agent_id=memory.agent_id, team_id=memory.team_id, memory_id=memory.memory_id, memory=memory.memory, topics=memory.topics, input=memory.input, feedback=memory.feedback, created_at=memory.created_at, updated_at=memory.created_at, ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["memory_id"], set_=dict( memory=memory.memory, topics=memory.topics, input=memory.input, agent_id=memory.agent_id, team_id=memory.team_id, feedback=memory.feedback, updated_at=current_time, # Preserve created_at on update - don't overwrite existing value created_at=table.c.created_at, ), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None memory_raw = row._mapping if not memory_raw or not deserialize: return memory_raw return UserMemory.from_dict(memory_raw) except Exception as e: log_error(f"Error upserting user memory: {e}") raise e def upsert_memories( self, memories: List[UserMemory], deserialize: Optional[bool] = True, preserve_updated_at: bool = False, ) -> List[Union[UserMemory, Dict[str, Any]]]: """ Bulk upsert multiple user memories for improved performance on large datasets. Args: memories (List[UserMemory]): List of memories to upsert. deserialize (Optional[bool]): Whether to deserialize the memories. Defaults to True. Returns: List[Union[UserMemory, Dict[str, Any]]]: List of upserted memories. Raises: Exception: If an error occurs during bulk upsert. """ if not memories: return [] try: table = self._get_table(table_type="memories", create_table_if_not_found=True) if table is None: log_info("Memories table not available, falling back to individual upserts") return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] # Prepare bulk data bulk_data = [] current_time = int(time.time()) for memory in memories: if memory.memory_id is None: memory.memory_id = str(uuid4()) # Use preserved updated_at if flag is set and value exists, otherwise use current time updated_at = memory.updated_at if preserve_updated_at else current_time bulk_data.append( { "user_id": memory.user_id, "agent_id": memory.agent_id, "team_id": memory.team_id, "memory_id": memory.memory_id, "memory": memory.memory, "topics": memory.topics, "input": memory.input, "feedback": memory.feedback, "created_at": memory.created_at, "updated_at": updated_at, } ) results: List[Union[UserMemory, Dict[str, Any]]] = [] with self.Session() as sess, sess.begin(): # Bulk upsert memories using SQLite ON CONFLICT DO UPDATE stmt = sqlite.insert(table) stmt = stmt.on_conflict_do_update( index_elements=["memory_id"], set_=dict( memory=stmt.excluded.memory, topics=stmt.excluded.topics, input=stmt.excluded.input, agent_id=stmt.excluded.agent_id, team_id=stmt.excluded.team_id, feedback=stmt.excluded.feedback, updated_at=stmt.excluded.updated_at, # Preserve created_at on update created_at=table.c.created_at, ), ) sess.execute(stmt, bulk_data) # Fetch results memory_ids = [memory.memory_id for memory in memories if memory.memory_id] select_stmt = select(table).where(table.c.memory_id.in_(memory_ids)) result = sess.execute(select_stmt).fetchall() for row in result: memory_dict = dict(row._mapping) if deserialize: results.append(UserMemory.from_dict(memory_dict)) else: results.append(memory_dict) return results except Exception as e: log_error(f"Exception during bulk memory upsert, falling back to individual upserts: {e}") # Fallback to individual upserts return [ result for memory in memories if memory is not None for result in [self.upsert_user_memory(memory, deserialize=deserialize)] if result is not None ] def clear_memories(self) -> None: """Delete all memories from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="memories") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: from agno.utils.log import log_warning log_warning(f"Exception deleting all memories: {e}") raise e # -- Metrics methods -- def _get_all_sessions_for_metrics_calculation( self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None ) -> List[Dict[str, Any]]: """ Get all sessions of all types (agent, team, workflow) as raw dictionaries. Args: start_timestamp (Optional[int]): The start timestamp to filter by. Defaults to None. end_timestamp (Optional[int]): The end timestamp to filter by. Defaults to None. Returns: List[Dict[str, Any]]: List of session dictionaries with session_type field. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="sessions") if table is None: return [] stmt = select( table.c.user_id, table.c.session_data, table.c.runs, table.c.created_at, table.c.session_type, ) if start_timestamp is not None: stmt = stmt.where(table.c.created_at >= start_timestamp) if end_timestamp is not None: stmt = stmt.where(table.c.created_at <= end_timestamp) with self.Session() as sess: result = sess.execute(stmt).fetchall() return [record._mapping for record in result] except Exception as e: log_error(f"Error reading from sessions table: {e}") raise e def _get_metrics_calculation_starting_date(self, table: Table) -> Optional[date]: """Get the first date for which metrics calculation is needed: 1. If there are metrics records, return the date of the first day without a complete metrics record. 2. If there are no metrics records, return the date of the first recorded session. 3. If there are no metrics records and no sessions records, return None. Args: table (Table): The table to get the starting date for. Returns: Optional[date]: The starting date for which metrics calculation is needed. """ with self.Session() as sess: stmt = select(table).order_by(table.c.date.desc()).limit(1) result = sess.execute(stmt).fetchone() # 1. Return the date of the first day without a complete metrics record. if result is not None: if result.completed: return result._mapping["date"] + timedelta(days=1) else: return result._mapping["date"] # 2. No metrics records. Return the date of the first recorded session. first_session, _ = self.get_sessions(sort_by="created_at", sort_order="asc", limit=1, deserialize=False) first_session_date = first_session[0]["created_at"] if first_session else None # type: ignore # 3. No metrics records and no sessions records. Return None. if not first_session_date: return None return datetime.fromtimestamp(first_session_date, tz=timezone.utc).date() def calculate_metrics(self) -> Optional[list[dict]]: """Calculate metrics for all dates without complete metrics. Returns: Optional[list[dict]]: The calculated metrics. Raises: Exception: If an error occurs during metrics calculation. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return None starting_date = self._get_metrics_calculation_starting_date(table) if starting_date is None: log_info("No session data found. Won't calculate metrics.") return None dates_to_process = get_dates_to_calculate_metrics_for(starting_date) if not dates_to_process: log_info("Metrics already calculated for all relevant dates.") return None start_timestamp = int( datetime.combine(dates_to_process[0], datetime.min.time()).replace(tzinfo=timezone.utc).timestamp() ) end_timestamp = int( datetime.combine(dates_to_process[-1] + timedelta(days=1), datetime.min.time()) .replace(tzinfo=timezone.utc) .timestamp() ) sessions = self._get_all_sessions_for_metrics_calculation( start_timestamp=start_timestamp, end_timestamp=end_timestamp ) all_sessions_data = fetch_all_sessions_data( sessions=sessions, dates_to_process=dates_to_process, start_timestamp=start_timestamp, ) if not all_sessions_data: log_info("No new session data found. Won't calculate metrics.") return None results = [] metrics_records = [] for date_to_process in dates_to_process: date_key = date_to_process.isoformat() sessions_for_date = all_sessions_data.get(date_key, {}) # Skip dates with no sessions if not any(len(sessions) > 0 for sessions in sessions_for_date.values()): continue metrics_record = calculate_date_metrics(date_to_process, sessions_for_date) metrics_records.append(metrics_record) if metrics_records: with self.Session() as sess, sess.begin(): results = bulk_upsert_metrics(session=sess, table=table, metrics_records=metrics_records) log_debug("Updated metrics calculations") return results except Exception as e: log_error(f"Error refreshing metrics: {e}") raise e def get_metrics( self, starting_date: Optional[date] = None, ending_date: Optional[date] = None, ) -> Tuple[List[dict], Optional[int]]: """Get all metrics matching the given date range. Args: starting_date (Optional[date]): The starting date to filter metrics by. ending_date (Optional[date]): The ending date to filter metrics by. Returns: Tuple[List[dict], Optional[int]]: A tuple containing the metrics and the timestamp of the latest update. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="metrics", create_table_if_not_found=True) if table is None: return [], None with self.Session() as sess, sess.begin(): stmt = select(table) if starting_date: stmt = stmt.where(table.c.date >= starting_date) if ending_date: stmt = stmt.where(table.c.date <= ending_date) result = sess.execute(stmt).fetchall() if not result: return [], None # Get the latest updated_at latest_stmt = select(func.max(table.c.updated_at)) latest_updated_at = sess.execute(latest_stmt).scalar() return [row._mapping for row in result], latest_updated_at except Exception as e: log_error(f"Error getting metrics: {e}") raise e # -- Knowledge methods -- def delete_knowledge_content(self, id: str): """Delete a knowledge row from the database. Args: id (str): The ID of the knowledge row to delete. Raises: Exception: If an error occurs during deletion. """ table = self._get_table(table_type="knowledge") if table is None: return try: with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.id == id) sess.execute(stmt) except Exception as e: log_error(f"Error deleting knowledge content: {e}") raise e def get_knowledge_content(self, id: str) -> Optional[KnowledgeRow]: """Get a knowledge row from the database. Args: id (str): The ID of the knowledge row to get. Returns: Optional[KnowledgeRow]: The knowledge row, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ table = self._get_table(table_type="knowledge") if table is None: return None try: with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None return KnowledgeRow.model_validate(result._mapping) except Exception as e: log_error(f"Error getting knowledge content: {e}") raise e def get_knowledge_contents( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, linked_to: Optional[str] = None, ) -> Tuple[List[KnowledgeRow], int]: """Get all knowledge contents from the database. Args: limit (Optional[int]): The maximum number of knowledge contents to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. linked_to (Optional[str]): Filter by linked_to value (knowledge instance name). Returns: Tuple[List[KnowledgeRow], int]: The knowledge contents and total count. Raises: Exception: If an error occurs during retrieval. """ table = self._get_table(table_type="knowledge") if table is None: return [], 0 try: with self.Session() as sess, sess.begin(): stmt = select(table) # Apply linked_to filter if provided if linked_to is not None: stmt = stmt.where(table.c.linked_to == linked_to) # Apply sorting if sort_by is not None: stmt = stmt.order_by(getattr(table.c, sort_by) * (1 if sort_order == "asc" else -1)) # Get total count before applying limit and pagination count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Apply pagination after count if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() return [KnowledgeRow.model_validate(record._mapping) for record in result], total_count except Exception as e: log_error(f"Error getting knowledge contents: {e}") raise e def upsert_knowledge_content(self, knowledge_row: KnowledgeRow): """Upsert knowledge content in the database. Args: knowledge_row (KnowledgeRow): The knowledge row to upsert. Returns: Optional[KnowledgeRow]: The upserted knowledge row, or None if the operation fails. """ try: table = self._get_table(table_type="knowledge", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): update_fields = { k: v for k, v in { "name": knowledge_row.name, "description": knowledge_row.description, "metadata": knowledge_row.metadata, "type": knowledge_row.type, "size": knowledge_row.size, "linked_to": knowledge_row.linked_to, "access_count": knowledge_row.access_count, "status": knowledge_row.status, "status_message": knowledge_row.status_message, "created_at": knowledge_row.created_at, "updated_at": knowledge_row.updated_at, "external_id": knowledge_row.external_id, }.items() # Filtering out None fields if updating if v is not None } stmt = ( sqlite.insert(table) .values(knowledge_row.model_dump()) .on_conflict_do_update(index_elements=["id"], set_=update_fields) ) sess.execute(stmt) return knowledge_row except Exception as e: log_error(f"Error upserting knowledge content: {e}") raise e # -- Eval methods -- def create_eval_run(self, eval_run: EvalRunRecord) -> Optional[EvalRunRecord]: """Create an EvalRunRecord in the database. Args: eval_run (EvalRunRecord): The eval run to create. Returns: Optional[EvalRunRecord]: The created eval run, or None if the operation fails. Raises: Exception: If an error occurs during creation. """ try: table = self._get_table(table_type="evals", create_table_if_not_found=True) if table is None: return None with self.Session() as sess, sess.begin(): current_time = int(time.time()) stmt = sqlite.insert(table).values( { "created_at": current_time, "updated_at": current_time, **eval_run.model_dump(), } ) sess.execute(stmt) sess.commit() log_debug(f"Created eval run with id '{eval_run.run_id}'") return eval_run except Exception as e: log_error(f"Error creating eval run: {e}") raise e def delete_eval_run(self, eval_run_id: str) -> None: """Delete an eval run from the database. Args: eval_run_id (str): The ID of the eval run to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id == eval_run_id) result = sess.execute(stmt) if result.rowcount == 0: log_warning(f"No eval run found with ID: {eval_run_id}") else: log_debug(f"Deleted eval run with ID: {eval_run_id}") except Exception as e: log_error(f"Error deleting eval run {eval_run_id}: {e}") raise e def delete_eval_runs(self, eval_run_ids: List[str]) -> None: """Delete multiple eval runs from the database. Args: eval_run_ids (List[str]): List of eval run IDs to delete. """ try: table = self._get_table(table_type="evals") if table is None: return with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.run_id.in_(eval_run_ids)) result = sess.execute(stmt) if result.rowcount == 0: log_debug(f"No eval runs found with IDs: {eval_run_ids}") else: log_debug(f"Deleted {result.rowcount} eval runs") except Exception as e: log_error(f"Error deleting eval runs {eval_run_ids}: {e}") raise e def get_eval_run( self, eval_run_id: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Get an eval run from the database. Args: eval_run_id (str): The ID of the eval run to get. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.run_id == eval_run_id) result = sess.execute(stmt).fetchone() if result is None: return None eval_run_raw = result._mapping if not eval_run_raw or not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Exception getting eval run {eval_run_id}: {e}") raise e def get_eval_runs( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, model_id: Optional[str] = None, filter_type: Optional[EvalFilterType] = None, eval_type: Optional[List[EvalType]] = None, deserialize: Optional[bool] = True, ) -> Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: """Get all eval runs from the database. Args: limit (Optional[int]): The maximum number of eval runs to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. workflow_id (Optional[str]): The ID of the workflow to filter by. model_id (Optional[str]): The ID of the model to filter by. eval_type (Optional[List[EvalType]]): The type(s) of eval to filter by. filter_type (Optional[EvalFilterType]): Filter by component type (agent, team, workflow). deserialize (Optional[bool]): Whether to serialize the eval runs. Defaults to True. create_table_if_not_found (Optional[bool]): Whether to create the table if it doesn't exist. Returns: Union[List[EvalRunRecord], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of EvalRunRecord objects - When deserialize=False: List of EvalRun dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="evals") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if model_id is not None: stmt = stmt.where(table.c.model_id == model_id) if eval_type is not None and len(eval_type) > 0: stmt = stmt.where(table.c.eval_type.in_(eval_type)) if filter_type is not None: if filter_type == EvalFilterType.AGENT: stmt = stmt.where(table.c.agent_id.is_not(None)) elif filter_type == EvalFilterType.TEAM: stmt = stmt.where(table.c.team_id.is_not(None)) elif filter_type == EvalFilterType.WORKFLOW: stmt = stmt.where(table.c.workflow_id.is_not(None)) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting - apply default sort by created_at desc if no sort parameters provided if sort_by is None: stmt = stmt.order_by(table.c.created_at.desc()) else: stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) eval_runs_raw = [row._mapping for row in result] if not deserialize: return eval_runs_raw, total_count return [EvalRunRecord.model_validate(row) for row in eval_runs_raw] except Exception as e: log_error(f"Exception getting eval runs: {e}") raise e def rename_eval_run( self, eval_run_id: str, name: str, deserialize: Optional[bool] = True ) -> Optional[Union[EvalRunRecord, Dict[str, Any]]]: """Upsert the name of an eval run in the database, returning raw dictionary. Args: eval_run_id (str): The ID of the eval run to update. name (str): The new name of the eval run. deserialize (Optional[bool]): Whether to serialize the eval run. Defaults to True. Returns: Optional[Union[EvalRunRecord, Dict[str, Any]]]: - When deserialize=True: EvalRunRecord object - When deserialize=False: EvalRun dictionary Raises: Exception: If an error occurs during update. """ try: table = self._get_table(table_type="evals") if table is None: return None with self.Session() as sess, sess.begin(): stmt = ( table.update().where(table.c.run_id == eval_run_id).values(name=name, updated_at=int(time.time())) ) sess.execute(stmt) eval_run_raw = self.get_eval_run(eval_run_id=eval_run_id, deserialize=deserialize) log_debug(f"Renamed eval run with id '{eval_run_id}' to '{name}'") if not eval_run_raw or not deserialize: return eval_run_raw return EvalRunRecord.model_validate(eval_run_raw) except Exception as e: log_error(f"Error renaming eval run {eval_run_id}: {e}") raise e # -- Trace methods -- def _get_traces_base_query(self, table: Table, spans_table: Optional[Table] = None): """Build base query for traces with aggregated span counts. Args: table: The traces table. spans_table: The spans table (optional). Returns: SQLAlchemy select statement with total_spans and error_count calculated dynamically. """ from sqlalchemy import case, func, literal if spans_table is not None: # JOIN with spans table to calculate total_spans and error_count return ( select( table, func.coalesce(func.count(spans_table.c.span_id), 0).label("total_spans"), func.coalesce(func.sum(case((spans_table.c.status_code == "ERROR", 1), else_=0)), 0).label( "error_count" ), ) .select_from(table.outerjoin(spans_table, table.c.trace_id == spans_table.c.trace_id)) .group_by(table.c.trace_id) ) else: # Fallback if spans table doesn't exist return select(table, literal(0).label("total_spans"), literal(0).label("error_count")) def _get_trace_component_level_expr(self, workflow_id_col, team_id_col, agent_id_col, name_col): """Build a SQL CASE expression that returns the component level for a trace. Component levels (higher = more important): - 3: Workflow root (.run or .arun with workflow_id) - 2: Team root (.run or .arun with team_id) - 1: Agent root (.run or .arun with agent_id) - 0: Child span (not a root) Args: workflow_id_col: SQL column/expression for workflow_id team_id_col: SQL column/expression for team_id agent_id_col: SQL column/expression for agent_id name_col: SQL column/expression for name Returns: SQLAlchemy CASE expression returning the component level as an integer. """ from sqlalchemy import and_, case, or_ is_root_name = or_(name_col.contains(".run"), name_col.contains(".arun")) return case( # Workflow root (level 3) (and_(workflow_id_col.isnot(None), is_root_name), 3), # Team root (level 2) (and_(team_id_col.isnot(None), is_root_name), 2), # Agent root (level 1) (and_(agent_id_col.isnot(None), is_root_name), 1), # Child span or unknown (level 0) else_=0, ) def upsert_trace(self, trace: "Trace") -> None: """Create or update a single trace record in the database. Uses INSERT ... ON CONFLICT DO UPDATE (upsert) to handle concurrent inserts atomically and avoid race conditions. Args: trace: The Trace object to store (one per trace_id). """ from sqlalchemy import case try: table = self._get_table(table_type="traces", create_table_if_not_found=True) if table is None: return trace_dict = trace.to_dict() trace_dict.pop("total_spans", None) trace_dict.pop("error_count", None) with self.Session() as sess, sess.begin(): # Use upsert to handle concurrent inserts atomically # On conflict, update fields while preserving existing non-null context values # and keeping the earliest start_time insert_stmt = sqlite.insert(table).values(trace_dict) # Build component level expressions for comparing trace priority new_level = self._get_trace_component_level_expr( insert_stmt.excluded.workflow_id, insert_stmt.excluded.team_id, insert_stmt.excluded.agent_id, insert_stmt.excluded.name, ) existing_level = self._get_trace_component_level_expr( table.c.workflow_id, table.c.team_id, table.c.agent_id, table.c.name, ) # Build the ON CONFLICT DO UPDATE clause # Use MIN for start_time, MAX for end_time to capture full trace duration # SQLite stores timestamps as ISO strings, so string comparison works for ISO format # Duration is calculated as: (MAX(end_time) - MIN(start_time)) in milliseconds # SQLite doesn't have epoch extraction, so we calculate duration using julianday upsert_stmt = insert_stmt.on_conflict_do_update( index_elements=["trace_id"], set_={ "end_time": func.max(table.c.end_time, insert_stmt.excluded.end_time), "start_time": func.min(table.c.start_time, insert_stmt.excluded.start_time), # Calculate duration in milliseconds using julianday (SQLite-specific) # julianday returns days, so multiply by 86400000 to get milliseconds "duration_ms": ( func.julianday(func.max(table.c.end_time, insert_stmt.excluded.end_time)) - func.julianday(func.min(table.c.start_time, insert_stmt.excluded.start_time)) ) * 86400000, "status": insert_stmt.excluded.status, # Update name only if new trace is from a higher-level component # Priority: workflow (3) > team (2) > agent (1) > child spans (0) "name": case( (new_level > existing_level, insert_stmt.excluded.name), else_=table.c.name, ), # Preserve existing non-null context values using COALESCE "run_id": func.coalesce(insert_stmt.excluded.run_id, table.c.run_id), "session_id": func.coalesce(insert_stmt.excluded.session_id, table.c.session_id), "user_id": func.coalesce(insert_stmt.excluded.user_id, table.c.user_id), "agent_id": func.coalesce(insert_stmt.excluded.agent_id, table.c.agent_id), "team_id": func.coalesce(insert_stmt.excluded.team_id, table.c.team_id), "workflow_id": func.coalesce(insert_stmt.excluded.workflow_id, table.c.workflow_id), }, ) sess.execute(upsert_stmt) except Exception as e: log_error(f"Error creating trace: {e}") # Don't raise - tracing should not break the main application flow def get_trace( self, trace_id: Optional[str] = None, run_id: Optional[str] = None, ): """Get a single trace by trace_id or other filters. Args: trace_id: The unique trace identifier. run_id: Filter by run ID (returns first match). Returns: Optional[Trace]: The trace if found, None otherwise. Note: If multiple filters are provided, trace_id takes precedence. For other filters, the most recent trace is returned. """ try: from agno.tracing.schemas import Trace table = self._get_table(table_type="traces") if table is None: return None # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build query with aggregated span counts stmt = self._get_traces_base_query(table, spans_table) if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) elif run_id: stmt = stmt.where(table.c.run_id == run_id) else: log_debug("get_trace called without any filter parameters") return None # Order by most recent and get first result stmt = stmt.order_by(table.c.start_time.desc()).limit(1) result = sess.execute(stmt).fetchone() if result: return Trace.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting trace: {e}") return None def get_traces( self, run_id: Optional[str] = None, session_id: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List, int]: """Get traces matching the provided filters with pagination. Args: run_id: Filter by run ID. session_id: Filter by session ID. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. status: Filter by status (OK, ERROR, UNSET). start_time: Filter traces starting after this datetime. end_time: Filter traces ending before this datetime. limit: Maximum number of traces to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Trace], int]: Tuple of (list of matching traces, total count). """ try: from sqlalchemy import func from agno.tracing.schemas import Trace log_debug( 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}" ) table = self._get_table(table_type="traces") if table is None: log_debug(" Traces table not found") return [], 0 # Get spans table for JOIN spans_table = self._get_table(table_type="spans") with self.Session() as sess: # Build base query with aggregated span counts base_stmt = self._get_traces_base_query(table, spans_table) # Apply filters if run_id: base_stmt = base_stmt.where(table.c.run_id == run_id) if session_id: base_stmt = base_stmt.where(table.c.session_id == session_id) if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if status: base_stmt = base_stmt.where(table.c.status == status) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.start_time >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.end_time <= end_time.isoformat()) # Apply advanced filter expression if filter_expr: try: from agno.db.filter_converter import TRACE_COLUMNS, filter_expr_to_sqlalchemy base_stmt = base_stmt.where( filter_expr_to_sqlalchemy(filter_expr, table, allowed_columns=TRACE_COLUMNS) ) except ValueError: # Re-raise ValueError for proper 400 response at API layer raise except (KeyError, TypeError) as e: raise ValueError(f"Invalid filter expression: {e}") from e # Get total count count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(table.c.start_time.desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() traces = [Trace.from_dict(dict(row._mapping)) for row in results] return traces, total_count except Exception as e: log_error(f"Error getting traces: {e}") return [], 0 def get_trace_stats( self, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, start_time: Optional[datetime] = None, end_time: Optional[datetime] = None, limit: Optional[int] = 20, page: Optional[int] = 1, filter_expr: Optional[Dict[str, Any]] = None, ) -> tuple[List[Dict[str, Any]], int]: """Get trace statistics grouped by session. Args: user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. start_time: Filter sessions with traces created after this datetime. end_time: Filter sessions with traces created before this datetime. limit: Maximum number of sessions to return per page. page: Page number (1-indexed). filter_expr: Advanced filter expression dict (from FilterExpr.to_dict()). Returns: tuple[List[Dict], int]: Tuple of (list of session stats dicts, total count). """ try: from sqlalchemy import func table = self._get_table(table_type="traces") if table is None: log_debug("Traces table not found") return [], 0 with self.Session() as sess: # Build base query grouped by session_id base_stmt = ( select( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id, func.count(table.c.trace_id).label("total_traces"), func.min(table.c.created_at).label("first_trace_at"), func.max(table.c.created_at).label("last_trace_at"), ) .where(table.c.session_id.isnot(None)) # Only sessions with session_id .group_by( table.c.session_id, table.c.user_id, table.c.agent_id, table.c.team_id, table.c.workflow_id ) ) # Apply filters if user_id is not None: base_stmt = base_stmt.where(table.c.user_id == user_id) if workflow_id: base_stmt = base_stmt.where(table.c.workflow_id == workflow_id) if team_id: base_stmt = base_stmt.where(table.c.team_id == team_id) if agent_id: base_stmt = base_stmt.where(table.c.agent_id == agent_id) if start_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at >= start_time.isoformat()) if end_time: # Convert datetime to ISO string for comparison base_stmt = base_stmt.where(table.c.created_at <= end_time.isoformat()) # Apply advanced filter expression if filter_expr: try: from agno.db.filter_converter import TRACE_COLUMNS, filter_expr_to_sqlalchemy base_stmt = base_stmt.where( filter_expr_to_sqlalchemy(filter_expr, table, allowed_columns=TRACE_COLUMNS) ) except ValueError: # Re-raise ValueError for proper 400 response at API layer raise except (KeyError, TypeError) as e: raise ValueError(f"Invalid filter expression: {e}") from e # Get total count of sessions count_stmt = select(func.count()).select_from(base_stmt.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Apply pagination and ordering offset = (page - 1) * limit if page and limit else 0 paginated_stmt = base_stmt.order_by(func.max(table.c.created_at).desc()).limit(limit).offset(offset) results = sess.execute(paginated_stmt).fetchall() # Convert to list of dicts with datetime objects from datetime import datetime stats_list = [] for row in results: # Convert ISO strings to datetime objects first_trace_at_str = row.first_trace_at last_trace_at_str = row.last_trace_at # Parse ISO format strings to datetime objects first_trace_at = datetime.fromisoformat(first_trace_at_str.replace("Z", "+00:00")) last_trace_at = datetime.fromisoformat(last_trace_at_str.replace("Z", "+00:00")) stats_list.append( { "session_id": row.session_id, "user_id": row.user_id, "agent_id": row.agent_id, "team_id": row.team_id, "workflow_id": row.workflow_id, "total_traces": row.total_traces, "first_trace_at": first_trace_at, "last_trace_at": last_trace_at, } ) return stats_list, total_count except Exception as e: log_error(f"Error getting trace stats: {e}") return [], 0 # -- Span methods -- def create_span(self, span: "Span") -> None: """Create a single span in the database. Args: span: The Span object to store. """ try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating span: {e}") def create_spans(self, spans: List) -> None: """Create multiple spans in the database as a batch. Args: spans: List of Span objects to store. """ if not spans: return try: table = self._get_table(table_type="spans", create_table_if_not_found=True) if table is None: return with self.Session() as sess, sess.begin(): for span in spans: stmt = sqlite.insert(table).values(span.to_dict()) sess.execute(stmt) except Exception as e: log_error(f"Error creating spans batch: {e}") def get_span(self, span_id: str): """Get a single span by its span_id. Args: span_id: The unique span identifier. Returns: Optional[Span]: The span if found, None otherwise. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return None with self.Session() as sess: stmt = table.select().where(table.c.span_id == span_id) result = sess.execute(stmt).fetchone() if result: return Span.from_dict(dict(result._mapping)) return None except Exception as e: log_error(f"Error getting span: {e}") return None def get_spans( self, trace_id: Optional[str] = None, parent_span_id: Optional[str] = None, ) -> List: """Get spans matching the provided filters. Args: trace_id: Filter by trace ID. parent_span_id: Filter by parent span ID. Returns: List[Span]: List of matching spans. """ try: from agno.tracing.schemas import Span table = self._get_table(table_type="spans") if table is None: return [] with self.Session() as sess: stmt = table.select() # Apply filters if trace_id: stmt = stmt.where(table.c.trace_id == trace_id) if parent_span_id: stmt = stmt.where(table.c.parent_span_id == parent_span_id) results = sess.execute(stmt).fetchall() return [Span.from_dict(dict(row._mapping)) for row in results] except Exception as e: log_error(f"Error getting spans: {e}") return [] # -- Migrations -- def migrate_table_from_v1_to_v2(self, v1_db_schema: str, v1_table_name: str, v1_table_type: str): """Migrate all content in the given table to the right v2 table""" from agno.db.migrations.v1_to_v2 import ( get_all_table_content, parse_agent_sessions, parse_memories, parse_team_sessions, parse_workflow_sessions, ) # Get all content from the old table old_content: list[dict[str, Any]] = get_all_table_content( db=self, db_schema=v1_db_schema, table_name=v1_table_name, ) if not old_content: log_info(f"No content to migrate from table {v1_table_name}") return # Parse the content into the new format memories: List[UserMemory] = [] sessions: Sequence[Union[AgentSession, TeamSession, WorkflowSession]] = [] if v1_table_type == "agent_sessions": sessions = parse_agent_sessions(old_content) elif v1_table_type == "team_sessions": sessions = parse_team_sessions(old_content) elif v1_table_type == "workflow_sessions": sessions = parse_workflow_sessions(old_content) elif v1_table_type == "memories": memories = parse_memories(old_content) else: raise ValueError(f"Invalid table type: {v1_table_type}") # Insert the new content into the new table if v1_table_type == "agent_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Agent sessions to table: {self.session_table_name}") elif v1_table_type == "team_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Team sessions to table: {self.session_table_name}") elif v1_table_type == "workflow_sessions": for session in sessions: self.upsert_session(session) log_info(f"Migrated {len(sessions)} Workflow sessions to table: {self.session_table_name}") elif v1_table_type == "memories": for memory in memories: self.upsert_user_memory(memory) log_info(f"Migrated {len(memories)} memories to table: {self.memory_table}") # -- Culture methods -- def clear_cultural_knowledge(self) -> None: """Delete all cultural artifacts from the database. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): sess.execute(table.delete()) except Exception as e: from agno.utils.log import log_warning log_warning(f"Exception deleting all cultural artifacts: {e}") raise e def delete_cultural_knowledge(self, id: str) -> None: """Delete a cultural artifact from the database. Args: id (str): The ID of the cultural artifact to delete. Raises: Exception: If an error occurs during deletion. """ try: table = self._get_table(table_type="culture") if table is None: return with self.Session() as sess, sess.begin(): delete_stmt = table.delete().where(table.c.id == id) result = sess.execute(delete_stmt) success = result.rowcount > 0 if success: log_debug(f"Successfully deleted cultural artifact id: {id}") else: log_debug(f"No cultural artifact found with id: {id}") except Exception as e: log_error(f"Error deleting cultural artifact: {e}") raise e def get_cultural_knowledge( self, id: str, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Get a cultural artifact from the database. Args: id (str): The ID of the cultural artifact to get. deserialize (Optional[bool]): Whether to serialize the cultural artifact. Defaults to True. Returns: Optional[CulturalKnowledge]: The cultural artifact, or None if it doesn't exist. Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return None with self.Session() as sess, sess.begin(): stmt = select(table).where(table.c.id == id) result = sess.execute(stmt).fetchone() if result is None: return None db_row = dict(result._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge_from_db(db_row) except Exception as e: log_error(f"Exception reading from cultural artifacts table: {e}") raise e def get_all_cultural_knowledge( self, name: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, deserialize: Optional[bool] = True, ) -> Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: """Get all cultural artifacts from the database as CulturalNotion objects. Args: name (Optional[str]): The name of the cultural artifact to filter by. agent_id (Optional[str]): The ID of the agent to filter by. team_id (Optional[str]): The ID of the team to filter by. limit (Optional[int]): The maximum number of cultural artifacts to return. page (Optional[int]): The page number. sort_by (Optional[str]): The column to sort by. sort_order (Optional[str]): The order to sort by. deserialize (Optional[bool]): Whether to serialize the cultural artifacts. Defaults to True. Returns: Union[List[CulturalKnowledge], Tuple[List[Dict[str, Any]], int]]: - When deserialize=True: List of CulturalNotion objects - When deserialize=False: List of CulturalNotion dictionaries and total count Raises: Exception: If an error occurs during retrieval. """ try: table = self._get_table(table_type="culture") if table is None: return [] if deserialize else ([], 0) with self.Session() as sess, sess.begin(): stmt = select(table) # Filtering if name is not None: stmt = stmt.where(table.c.name == name) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) # Get total count after applying filtering count_stmt = select(func.count()).select_from(stmt.alias()) total_count = sess.execute(count_stmt).scalar() # Sorting stmt = apply_sorting(stmt, table, sort_by, sort_order) # Paginating if limit is not None: stmt = stmt.limit(limit) if page is not None: stmt = stmt.offset((page - 1) * limit) result = sess.execute(stmt).fetchall() if not result: return [] if deserialize else ([], 0) db_rows = [dict(record._mapping) for record in result] if not deserialize: return db_rows, total_count return [deserialize_cultural_knowledge_from_db(row) for row in db_rows] except Exception as e: log_error(f"Error reading from cultural artifacts table: {e}") raise e def upsert_cultural_knowledge( self, cultural_knowledge: CulturalKnowledge, deserialize: Optional[bool] = True ) -> Optional[Union[CulturalKnowledge, Dict[str, Any]]]: """Upsert a cultural artifact into the database. Args: cultural_knowledge (CulturalKnowledge): The cultural artifact to upsert. deserialize (Optional[bool]): Whether to serialize the cultural artifact. Defaults to True. Returns: Optional[Union[CulturalNotion, Dict[str, Any]]]: - When deserialize=True: CulturalNotion object - When deserialize=False: CulturalNotion dictionary Raises: Exception: If an error occurs during upsert. """ try: table = self._get_table(table_type="culture", create_table_if_not_found=True) if table is None: return None if cultural_knowledge.id is None: cultural_knowledge.id = str(uuid4()) # Serialize content, categories, and notes into a JSON string for DB storage (SQLite requires strings) content_json_str = serialize_cultural_knowledge_for_db(cultural_knowledge) with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( id=cultural_knowledge.id, name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_json_str, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, created_at=cultural_knowledge.created_at, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ) stmt = stmt.on_conflict_do_update( # type: ignore index_elements=["id"], set_=dict( name=cultural_knowledge.name, summary=cultural_knowledge.summary, content=content_json_str, metadata=cultural_knowledge.metadata, input=cultural_knowledge.input, updated_at=int(time.time()), agent_id=cultural_knowledge.agent_id, team_id=cultural_knowledge.team_id, ), ).returning(table) result = sess.execute(stmt) row = result.fetchone() if row is None: return None db_row: Dict[str, Any] = dict(row._mapping) if not db_row or not deserialize: return db_row return deserialize_cultural_knowledge_from_db(db_row) except Exception as e: log_error(f"Error upserting cultural knowledge: {e}") raise e # --- Components --- def get_component( self, component_id: str, component_type: Optional[ComponentType] = None, ) -> Optional[Dict[str, Any]]: """Get a component by ID. Args: component_id: The component ID. component_type: Optional type filter (agent|team|workflow). Returns: Component dictionary or None if not found. """ try: table = self._get_table(table_type="components") if table is None: return None with self.Session() as sess: stmt = select(table).where( table.c.component_id == component_id, table.c.deleted_at.is_(None), ) if component_type is not None: stmt = stmt.where(table.c.component_type == component_type.value) result = sess.execute(stmt).fetchone() return dict(result._mapping) if result else None except Exception as e: log_error(f"Error getting component: {e}") raise def upsert_component( self, component_id: str, component_type: Optional[ComponentType] = None, name: Optional[str] = None, description: Optional[str] = None, current_version: Optional[int] = None, metadata: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: """Create or update a component. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). Required for create, optional for update. name: Display name. description: Optional description. current_version: Optional current version. metadata: Optional metadata dict. Returns: Created/updated component dictionary. Raises: ValueError: If creating and component_type is not provided. """ try: table = self._get_table(table_type="components", create_table_if_not_found=True) if table is None: raise ValueError("Components table not found") with self.Session() as sess, sess.begin(): existing = sess.execute(select(table).where(table.c.component_id == component_id)).fetchone() if existing is None: # Create new component if component_type is None: raise ValueError("component_type is required when creating a new component") sess.execute( table.insert().values( component_id=component_id, component_type=component_type.value if hasattr(component_type, "value") else component_type, name=name or component_id, description=description, current_version=None, metadata=metadata, created_at=int(time.time()), ) ) log_debug(f"Created component {component_id}") elif existing.deleted_at is not None: # Reactivate soft-deleted if component_type is None: raise ValueError("component_type is required when reactivating a deleted component") sess.execute( table.update() .where(table.c.component_id == component_id) .values( component_type=component_type.value if hasattr(component_type, "value") else component_type, name=name or component_id, description=description, current_version=None, metadata=metadata, updated_at=int(time.time()), deleted_at=None, ) ) log_debug(f"Reactivated component {component_id}") else: # Update existing updates: Dict[str, Any] = {"updated_at": int(time.time())} if component_type is not None: updates["component_type"] = ( component_type.value if hasattr(component_type, "value") else component_type ) if name is not None: updates["name"] = name if description is not None: updates["description"] = description if current_version is not None: updates["current_version"] = current_version if metadata is not None: updates["metadata"] = metadata sess.execute(table.update().where(table.c.component_id == component_id).values(**updates)) log_debug(f"Updated component {component_id}") result = self.get_component(component_id) if result is None: raise ValueError(f"Failed to get component {component_id} after upsert") return result except Exception as e: log_error(f"Error upserting component: {e}") raise def delete_component( self, component_id: str, hard_delete: bool = False, ) -> bool: """Delete a component and all its configs/links. Args: component_id: The component ID. hard_delete: If True, permanently delete. Otherwise soft-delete. Returns: True if deleted, False if not found. """ try: components_table = self._get_table(table_type="components") configs_table = self._get_table(table_type="component_configs") links_table = self._get_table(table_type="component_links") if components_table is None: return False with self.Session() as sess, sess.begin(): if hard_delete: # Delete links where this component is parent or child if links_table is not None: sess.execute(links_table.delete().where(links_table.c.parent_component_id == component_id)) sess.execute(links_table.delete().where(links_table.c.child_component_id == component_id)) # Delete configs if configs_table is not None: sess.execute(configs_table.delete().where(configs_table.c.component_id == component_id)) # Delete component result = sess.execute( components_table.delete().where(components_table.c.component_id == component_id) ) else: # Soft delete now = int(time.time()) result = sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(deleted_at=now) ) return result.rowcount > 0 except Exception as e: log_error(f"Error deleting component: {e}") raise def list_components( self, component_type: Optional[ComponentType] = None, include_deleted: bool = False, limit: int = 20, offset: int = 0, exclude_component_ids: Optional[Set[str]] = None, ) -> Tuple[List[Dict[str, Any]], int]: """List components with pagination. Args: component_type: Filter by type (agent|team|workflow). include_deleted: Include soft-deleted components. limit: Maximum number of items to return. offset: Number of items to skip. exclude_component_ids: Component IDs to exclude from results. Returns: Tuple of (list of component dicts, total count). """ try: table = self._get_table(table_type="components") if table is None: return [], 0 with self.Session() as sess: # Build base where clause where_clauses = [] if component_type is not None: where_clauses.append(table.c.component_type == component_type.value) if not include_deleted: where_clauses.append(table.c.deleted_at.is_(None)) if exclude_component_ids: where_clauses.append(table.c.component_id.notin_(exclude_component_ids)) # Get total count count_stmt = select(func.count()).select_from(table) for clause in where_clauses: count_stmt = count_stmt.where(clause) total_count = sess.execute(count_stmt).scalar() or 0 # Get paginated results stmt = select(table).order_by( table.c.created_at.desc(), table.c.component_id, ) for clause in where_clauses: stmt = stmt.where(clause) stmt = stmt.limit(limit).offset(offset) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total_count except Exception as e: log_error(f"Error listing components: {e}") raise def create_component_with_config( self, component_id: str, component_type: ComponentType, name: Optional[str], config: Dict[str, Any], description: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, label: Optional[str] = None, stage: str = "draft", notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """Create a component with its initial config atomically. Args: component_id: Unique identifier. component_type: Type (agent|team|workflow). name: Display name. config: The config data. description: Optional description. metadata: Optional metadata dict. label: Optional config label. stage: "draft" or "published". notes: Optional notes. links: Optional list of links. Each must have child_version set. Returns: Tuple of (component dict, config dict). Raises: ValueError: If component already exists, invalid stage, or link missing child_version. """ if stage not in {"draft", "published"}: raise ValueError(f"Invalid stage: {stage}") # Validate links have child_version if links: for link in links: if link.get("child_version") is None: raise ValueError(f"child_version is required for link to {link['child_component_id']}") try: components_table = self._get_table(table_type="components", create_table_if_not_found=True) configs_table = self._get_table(table_type="component_configs", create_table_if_not_found=True) links_table = self._get_table(table_type="component_links", create_table_if_not_found=True) if components_table is None: raise ValueError("Components table not found") if configs_table is None: raise ValueError("Component configs table not found") with self.Session() as sess, sess.begin(): # Check if component already exists existing = sess.execute( select(components_table.c.component_id).where(components_table.c.component_id == component_id) ).scalar_one_or_none() if existing is not None: raise ValueError(f"Component {component_id} already exists") # Check label uniqueness if label is not None: existing_label = sess.execute( select(configs_table.c.version).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) ).first() if existing_label: raise ValueError(f"Label '{label}' already exists for {component_id}") now = int(time.time()) version = 1 # Create component sess.execute( components_table.insert().values( component_id=component_id, component_type=component_type.value, name=name, description=description, metadata=metadata, current_version=version if stage == "published" else None, created_at=now, ) ) # Create initial config sess.execute( configs_table.insert().values( component_id=component_id, version=version, label=label, stage=stage, config=config, notes=notes, created_at=now, ) ) # Create links if provided if links and links_table is not None: for link in links: sess.execute( links_table.insert().values( parent_component_id=component_id, parent_version=version, link_kind=link["link_kind"], link_key=link["link_key"], child_component_id=link["child_component_id"], child_version=link["child_version"], position=link["position"], meta=link.get("meta"), created_at=now, ) ) # Fetch and return both component = self.get_component(component_id) config_result = self.get_config(component_id, version=version) if component is None: raise ValueError(f"Failed to get component {component_id} after creation") if config_result is None: raise ValueError(f"Failed to get config for {component_id} after creation") return component, config_result except Exception as e: log_error(f"Error creating component with config: {e}") raise # --- Config --- def get_config( self, component_id: str, version: Optional[int] = None, label: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Get a config by component ID and version or label. Args: component_id: The component ID. version: Specific version number. If None, uses current or latest draft. label: Config label to lookup. Ignored if version is provided. Returns: Config dictionary or None if not found. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return None with self.Session() as sess: # Always verify component exists and is not deleted component_row = ( sess.execute( select(components_table.c.current_version, components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ) .mappings() .one_or_none() ) if component_row is None: return None current_version = component_row["current_version"] if version is not None: stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) elif label is not None: stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) elif current_version is not None: # Use the current published version stmt = select(configs_table).where( configs_table.c.component_id == component_id, configs_table.c.version == current_version, ) else: # No current_version set (draft only) - get the latest version stmt = ( select(configs_table) .where(configs_table.c.component_id == component_id) .order_by(configs_table.c.version.desc()) .limit(1) ) result = sess.execute(stmt).fetchone() return dict(result._mapping) if result else None except Exception as e: log_error(f"Error getting config: {e}") raise def upsert_config( self, component_id: str, config: Optional[Dict[str, Any]] = None, version: Optional[int] = None, label: Optional[str] = None, stage: Optional[str] = None, notes: Optional[str] = None, links: Optional[List[Dict[str, Any]]] = None, ) -> Dict[str, Any]: """Create or update a config version for a component. Rules: - Draft configs can be edited freely - Published configs are immutable - Publishing a config automatically sets it as current_version Args: component_id: The component ID. config: The config data. Required for create, optional for update. version: If None, creates new version. If provided, updates that version. label: Optional human-readable label. stage: "draft" or "published". Defaults to "draft" for new configs. notes: Optional notes. links: Optional list of links. Each link must have child_version set. Returns: Created/updated config dictionary. Raises: ValueError: If component doesn't exist, version not found, label conflict, or attempting to update a published config. """ if stage is not None and stage not in {"draft", "published"}: raise ValueError(f"Invalid stage: {stage}") try: configs_table = self._get_table(table_type="component_configs", create_table_if_not_found=True) components_table = self._get_table(table_type="components") links_table = self._get_table(table_type="component_links", create_table_if_not_found=True) if components_table is None: raise ValueError("Components table not found") if configs_table is None: raise ValueError("Component configs table not found") with self.Session() as sess, sess.begin(): # Verify component exists and is not deleted component = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).fetchone() if component is None: raise ValueError(f"Component {component_id} not found") # Label uniqueness check if label is not None: label_query = select(configs_table.c.version).where( configs_table.c.component_id == component_id, configs_table.c.label == label, ) if version is not None: label_query = label_query.where(configs_table.c.version != version) if sess.execute(label_query).first(): raise ValueError(f"Label '{label}' already exists for {component_id}") # Validate links have child_version if links: for link in links: if link.get("child_version") is None: raise ValueError(f"child_version is required for link to {link['child_component_id']}") if version is None: if config is None: raise ValueError("config is required when creating a new version") # Default to draft for new configs if stage is None: stage = "draft" max_version = sess.execute( select(configs_table.c.version) .where(configs_table.c.component_id == component_id) .order_by(configs_table.c.version.desc()) .limit(1) ).scalar() final_version = (max_version or 0) + 1 sess.execute( configs_table.insert().values( component_id=component_id, version=final_version, label=label, stage=stage, config=config, notes=notes, created_at=int(time.time()), ) ) else: existing = sess.execute( select(configs_table.c.version, configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ).fetchone() if existing is None: raise ValueError(f"Config {component_id} v{version} not found") # Published configs are immutable if existing.stage == "published": raise ValueError(f"Cannot update published config {component_id} v{version}") # Build update dict with only provided fields updates: Dict[str, Any] = {"updated_at": int(time.time())} if label is not None: updates["label"] = label if stage is not None: updates["stage"] = stage if config is not None: updates["config"] = config if notes is not None: updates["notes"] = notes sess.execute( configs_table.update() .where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) .values(**updates) ) final_version = version if links is not None and links_table is not None: sess.execute( links_table.delete().where( links_table.c.parent_component_id == component_id, links_table.c.parent_version == final_version, ) ) for link in links: sess.execute( links_table.insert().values( parent_component_id=component_id, parent_version=final_version, link_kind=link["link_kind"], link_key=link["link_key"], child_component_id=link["child_component_id"], child_version=link["child_version"], position=link["position"], meta=link.get("meta"), created_at=int(time.time()), ) ) # Determine final stage (could be from update or create) final_stage = stage if stage is not None else (existing.stage if version is not None else "draft") if final_stage == "published": sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(current_version=final_version, updated_at=int(time.time())) ) result = self.get_config(component_id, version=final_version) if result is None: raise ValueError(f"Failed to get config {component_id} v{final_version} after upsert") return result except Exception as e: log_error(f"Error upserting config: {e}") raise def delete_config( self, component_id: str, version: int, ) -> bool: """Delete a specific config version. Only draft configs can be deleted. Published configs are immutable. Cannot delete the current version. Args: component_id: The component ID. version: The version to delete. Returns: True if deleted, False if not found. Raises: ValueError: If attempting to delete a published or current config. """ try: configs_table = self._get_table(table_type="component_configs") links_table = self._get_table(table_type="component_links") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return False with self.Session() as sess, sess.begin(): # Get config stage and check if it's current config_row = sess.execute( select(configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ).fetchone() if config_row is None: return False # Check if it's current version current = sess.execute( select(components_table.c.current_version).where(components_table.c.component_id == component_id) ).fetchone() if current and current.current_version == version: raise ValueError(f"Cannot delete current config {component_id} v{version}") # Delete associated links if links_table is not None: sess.execute( links_table.delete().where( links_table.c.parent_component_id == component_id, links_table.c.parent_version == version, ) ) # Delete the config sess.execute( configs_table.delete().where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ) return True except Exception as e: log_error(f"Error deleting config: {e}") raise def list_configs( self, component_id: str, include_config: bool = False, ) -> List[Dict[str, Any]]: """List all config versions for a component. Args: component_id: The component ID. include_config: If True, include full config blob. Otherwise just metadata. Returns: List of config dictionaries, newest first. Returns empty list if component not found or deleted. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return [] with self.Session() as sess: # Verify component exists and is not deleted exists = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).fetchone() if exists is None: return [] # Select columns based on include_config flag if include_config: stmt = select(configs_table) else: stmt = select( configs_table.c.component_id, configs_table.c.version, configs_table.c.label, configs_table.c.stage, configs_table.c.notes, configs_table.c.created_at, configs_table.c.updated_at, ) stmt = stmt.where(configs_table.c.component_id == component_id).order_by(configs_table.c.version.desc()) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results] except Exception as e: log_error(f"Error listing configs: {e}") raise def set_current_version( self, component_id: str, version: int, ) -> bool: """Set a specific published version as current. Only published configs can be set as current. This is used for rollback scenarios where you want to switch to a previous published version. Args: component_id: The component ID. version: The version to set as current (must be published). Returns: True if successful, False if component or version not found. Raises: ValueError: If attempting to set a draft config as current. """ try: configs_table = self._get_table(table_type="component_configs") components_table = self._get_table(table_type="components") if configs_table is None or components_table is None: return False with self.Session() as sess, sess.begin(): # Verify component exists and is not deleted component_exists = sess.execute( select(components_table.c.component_id).where( components_table.c.component_id == component_id, components_table.c.deleted_at.is_(None), ) ).fetchone() if component_exists is None: return False # Verify version exists and get stage stage = sess.execute( select(configs_table.c.stage).where( configs_table.c.component_id == component_id, configs_table.c.version == version, ) ).fetchone() if stage is None: return False # Only published configs can be set as current if stage.stage != "published": raise ValueError( f"Cannot set draft config {component_id} v{version} as current. " "Only published configs can be current." ) # Update pointer sess.execute( components_table.update() .where(components_table.c.component_id == component_id) .values(current_version=version, updated_at=int(time.time())) ) log_debug(f"Set {component_id} current version to {version}") return True except Exception as e: log_error(f"Error setting current version: {e}") raise # --- Component Links --- def get_links( self, component_id: str, version: int, link_kind: Optional[str] = None, ) -> List[Dict[str, Any]]: """Get links for a config version. Args: component_id: The component ID. version: The config version. link_kind: Optional filter by link kind (member|step). Returns: List of link dictionaries, ordered by position. """ try: table = self._get_table(table_type="component_links") if table is None: return [] with self.Session() as sess: stmt = ( select(table) .where( table.c.parent_component_id == component_id, table.c.parent_version == version, ) .order_by(table.c.position) ) if link_kind is not None: stmt = stmt.where(table.c.link_kind == link_kind) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results] except Exception as e: log_error(f"Error getting links: {e}") raise def get_dependents( self, component_id: str, version: Optional[int] = None, ) -> List[Dict[str, Any]]: """Find all components that reference this component. Args: component_id: The component ID to find dependents of. version: Optional specific version. If None, finds links to any version. Returns: List of link dictionaries showing what depends on this component. """ try: table = self._get_table(table_type="component_links") if table is None: return [] with self.Session() as sess: stmt = select(table).where(table.c.child_component_id == component_id) if version is not None: stmt = stmt.where(table.c.child_version == version) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results] except Exception as e: log_error(f"Error getting dependents: {e}") raise def resolve_version( self, component_id: str, version: Optional[int], ) -> Optional[int]: """Resolve a version number, handling NULL (current) case. Args: component_id: The component ID. version: Version number or None for current. Returns: Resolved version number or None if component not found. """ if version is not None: return version try: components_table = self._get_table(table_type="components") if components_table is None: return None with self.Session() as sess: result = sess.execute( select(components_table.c.current_version).where(components_table.c.component_id == component_id) ).scalar() return result except Exception as e: log_error(f"Error resolving version: {e}") raise def load_component_graph( self, component_id: str, version: Optional[int] = None, ) -> Optional[Dict[str, Any]]: """Load a component with its full resolved graph. Args: component_id: The component ID. version: Specific version or None for current. Returns: Dictionary with component, config, links, and resolved children. """ try: # Get component component = self.get_component(component_id) if component is None: return None # Resolve version resolved_version = self.resolve_version(component_id, version) if resolved_version is None: return None # Get config config = self.get_config(component_id, version=resolved_version) if config is None: return None # Get links links = self.get_links(component_id, resolved_version) # Resolve children recursively children = [] resolved_versions: Dict[str, Optional[int]] = {component_id: resolved_version} for link in links: child_version = self.resolve_version( link["child_component_id"], link["child_version"], ) resolved_versions[link["child_component_id"]] = child_version child_graph = self.load_component_graph( link["child_component_id"], version=child_version, ) if child_graph: # Merge nested resolved versions resolved_versions.update(child_graph.get("resolved_versions", {})) children.append( { "link": link, "graph": child_graph, } ) return { "component": component, "config": config, "children": children, "resolved_versions": resolved_versions, } except Exception as e: log_error(f"Error loading component graph: {e}") raise # -- Learning methods -- def get_learning( self, learning_type: str, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, ) -> Optional[Dict[str, Any]]: """Retrieve a learning record. Args: learning_type: Type of learning ('user_profile', 'session_context', etc.) user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). Returns: Dict with 'content' key containing the learning data, or None. """ try: table = self._get_table(table_type="learnings") if table is None: return None with self.Session() as sess: stmt = select(table).where(table.c.learning_type == learning_type) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if session_id is not None: stmt = stmt.where(table.c.session_id == session_id) if namespace is not None: stmt = stmt.where(table.c.namespace == namespace) if entity_id is not None: stmt = stmt.where(table.c.entity_id == entity_id) if entity_type is not None: stmt = stmt.where(table.c.entity_type == entity_type) result = sess.execute(stmt).fetchone() if result is None: return None row = dict(result._mapping) return {"content": row.get("content")} except Exception as e: log_debug(f"Error retrieving learning: {e}") return None def upsert_learning( self, id: str, learning_type: str, content: Dict[str, Any], user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, ) -> None: """Insert or update a learning record. Args: id: Unique identifier for the learning. learning_type: Type of learning ('user_profile', 'session_context', etc.) content: The learning content as a dict. user_id: Associated user ID. agent_id: Associated agent ID. team_id: Associated team ID. workflow_id: Associated workflow ID. session_id: Associated session ID. namespace: Namespace for scoping ('user', 'global', or custom). entity_id: Associated entity ID (for entity-specific learnings). entity_type: Entity type ('person', 'company', etc.). metadata: Optional metadata. """ try: table = self._get_table(table_type="learnings", create_table_if_not_found=True) if table is None: return current_time = int(time.time()) with self.Session() as sess, sess.begin(): stmt = sqlite.insert(table).values( learning_id=id, learning_type=learning_type, namespace=namespace, user_id=user_id, agent_id=agent_id, team_id=team_id, workflow_id=workflow_id, session_id=session_id, entity_id=entity_id, entity_type=entity_type, content=content, metadata=metadata, created_at=current_time, updated_at=current_time, ) stmt = stmt.on_conflict_do_update( index_elements=["learning_id"], set_=dict( content=content, metadata=metadata, updated_at=current_time, ), ) sess.execute(stmt) log_debug(f"Upserted learning: {id}") except Exception as e: log_debug(f"Error upserting learning: {e}") def delete_learning(self, id: str) -> bool: """Delete a learning record. Args: id: The learning ID to delete. Returns: True if deleted, False otherwise. """ try: table = self._get_table(table_type="learnings") if table is None: return False with self.Session() as sess, sess.begin(): stmt = table.delete().where(table.c.learning_id == id) result = sess.execute(stmt) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting learning: {e}") return False def get_learnings( self, learning_type: Optional[str] = None, user_id: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, session_id: Optional[str] = None, namespace: Optional[str] = None, entity_id: Optional[str] = None, entity_type: Optional[str] = None, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: """Get multiple learning records. Args: learning_type: Filter by learning type. user_id: Filter by user ID. agent_id: Filter by agent ID. team_id: Filter by team ID. workflow_id: Filter by workflow ID. session_id: Filter by session ID. namespace: Filter by namespace ('user', 'global', or custom). entity_id: Filter by entity ID (for entity-specific learnings). entity_type: Filter by entity type ('person', 'company', etc.). limit: Maximum number of records to return. Returns: List of learning records. """ try: table = self._get_table(table_type="learnings") if table is None: return [] with self.Session() as sess: stmt = select(table) if learning_type is not None: stmt = stmt.where(table.c.learning_type == learning_type) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) if session_id is not None: stmt = stmt.where(table.c.session_id == session_id) if namespace is not None: stmt = stmt.where(table.c.namespace == namespace) if entity_id is not None: stmt = stmt.where(table.c.entity_id == entity_id) if entity_type is not None: stmt = stmt.where(table.c.entity_type == entity_type) stmt = stmt.order_by(table.c.updated_at.desc()) if limit is not None: stmt = stmt.limit(limit) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results] except Exception as e: log_debug(f"Error getting learnings: {e}") return [] # -- Schedule methods -- def get_schedule(self, schedule_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == schedule_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule: {e}") return None def get_schedule_by_name(self, name: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.name == name)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule by name: {e}") return None def get_schedules( self, enabled: Optional[bool] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="schedules") if table is None: return [], 0 with self.Session() as sess: # Build base query with filters base_query = select(table) if enabled is not None: base_query = base_query.where(table.c.enabled == enabled) # Get total count count_stmt = select(func.count()).select_from(base_query.alias()) total_count = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit # Get paginated results stmt = base_query.order_by(table.c.created_at.desc()).limit(limit).offset(offset) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total_count except Exception as e: log_debug(f"Error listing schedules: {e}") return [], 0 def create_schedule(self, schedule_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="schedules", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create schedules table") with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**schedule_data)) return schedule_data except Exception as e: log_error(f"Error creating schedule: {e}") raise def update_schedule(self, schedule_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None kwargs["updated_at"] = int(time.time()) with self.Session() as sess, sess.begin(): sess.execute(table.update().where(table.c.id == schedule_id).values(**kwargs)) return self.get_schedule(schedule_id) except Exception as e: log_debug(f"Error updating schedule: {e}") return None def delete_schedule(self, schedule_id: str) -> bool: try: table = self._get_table(table_type="schedules") if table is None: return False runs_table = self._get_table(table_type="schedule_runs") with self.Session() as sess, sess.begin(): if runs_table is not None: sess.execute(runs_table.delete().where(runs_table.c.schedule_id == schedule_id)) result = sess.execute(table.delete().where(table.c.id == schedule_id)) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting schedule: {e}") return False def claim_due_schedule(self, worker_id: str, lock_grace_seconds: int = 300) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedules") if table is None: return None now = int(time.time()) stale_lock_threshold = now - lock_grace_seconds with self.Session() as sess, sess.begin(): # Find a due, enabled schedule that is either unlocked or has a stale lock stmt = ( select(table) .where( table.c.enabled == True, # noqa: E712 table.c.next_run_at <= now, or_( table.c.locked_by.is_(None), table.c.locked_at <= stale_lock_threshold, ), ) .order_by(table.c.next_run_at.asc()) .limit(1) ) row = sess.execute(stmt).fetchone() if row is None: return None schedule = dict(row._mapping) # Atomically claim it result = sess.execute( table.update() .where( table.c.id == schedule["id"], or_( table.c.locked_by.is_(None), table.c.locked_at <= stale_lock_threshold, ), ) .values(locked_by=worker_id, locked_at=now) ) if result.rowcount == 0: return None schedule["locked_by"] = worker_id schedule["locked_at"] = now return schedule except Exception as e: log_debug(f"Error claiming schedule: {e}") return None def release_schedule(self, schedule_id: str, next_run_at: Optional[int] = None) -> bool: try: table = self._get_table(table_type="schedules") if table is None: return False updates: Dict[str, Any] = {"locked_by": None, "locked_at": None, "updated_at": int(time.time())} if next_run_at is not None: updates["next_run_at"] = next_run_at with self.Session() as sess, sess.begin(): result = sess.execute(table.update().where(table.c.id == schedule_id).values(**updates)) return result.rowcount > 0 except Exception as e: log_debug(f"Error releasing schedule: {e}") return False def create_schedule_run(self, run_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="schedule_runs", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create schedule_runs table") with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**run_data)) return run_data except Exception as e: log_error(f"Error creating schedule run: {e}") raise def update_schedule_run(self, schedule_run_id: str, **kwargs: Any) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedule_runs") if table is None: return None with self.Session() as sess, sess.begin(): sess.execute(table.update().where(table.c.id == schedule_run_id).values(**kwargs)) return self.get_schedule_run(schedule_run_id) except Exception as e: log_debug(f"Error updating schedule run: {e}") return None def get_schedule_run(self, run_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="schedule_runs") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == run_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting schedule run: {e}") return None def get_schedule_runs( self, schedule_id: str, limit: int = 20, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="schedule_runs") if table is None: return [], 0 with self.Session() as sess: # Get total count count_stmt = select(func.count()).select_from(table).where(table.c.schedule_id == schedule_id) total_count = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit # Get paginated results stmt = ( select(table) .where(table.c.schedule_id == schedule_id) .order_by(table.c.created_at.desc()) .limit(limit) .offset(offset) ) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total_count except Exception as e: log_debug(f"Error getting schedule runs: {e}") return [], 0 # -- Approval methods -- def create_approval(self, approval_data: Dict[str, Any]) -> Dict[str, Any]: try: table = self._get_table(table_type="approvals", create_table_if_not_found=True) if table is None: raise RuntimeError("Failed to get or create approvals table") data = {**approval_data} now = int(time.time()) data.setdefault("created_at", now) data.setdefault("updated_at", now) with self.Session() as sess, sess.begin(): sess.execute(table.insert().values(**data)) return data except Exception as e: log_error(f"Error creating approval: {e}") raise def get_approval(self, approval_id: str) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="approvals") if table is None: return None with self.Session() as sess: result = sess.execute(select(table).where(table.c.id == approval_id)).fetchone() return dict(result._mapping) if result else None except Exception as e: log_debug(f"Error getting approval: {e}") return None def get_approvals( self, status: Optional[str] = None, source_type: Optional[str] = None, approval_type: Optional[str] = None, pause_type: Optional[str] = None, agent_id: Optional[str] = None, team_id: Optional[str] = None, workflow_id: Optional[str] = None, user_id: Optional[str] = None, schedule_id: Optional[str] = None, run_id: Optional[str] = None, limit: int = 100, page: int = 1, ) -> Tuple[List[Dict[str, Any]], int]: try: table = self._get_table(table_type="approvals") if table is None: return [], 0 with self.Session() as sess: stmt = select(table) count_stmt = select(func.count()).select_from(table) if status is not None: stmt = stmt.where(table.c.status == status) count_stmt = count_stmt.where(table.c.status == status) if source_type is not None: stmt = stmt.where(table.c.source_type == source_type) count_stmt = count_stmt.where(table.c.source_type == source_type) if approval_type is not None: stmt = stmt.where(table.c.approval_type == approval_type) count_stmt = count_stmt.where(table.c.approval_type == approval_type) if pause_type is not None: stmt = stmt.where(table.c.pause_type == pause_type) count_stmt = count_stmt.where(table.c.pause_type == pause_type) if agent_id is not None: stmt = stmt.where(table.c.agent_id == agent_id) count_stmt = count_stmt.where(table.c.agent_id == agent_id) if team_id is not None: stmt = stmt.where(table.c.team_id == team_id) count_stmt = count_stmt.where(table.c.team_id == team_id) if workflow_id is not None: stmt = stmt.where(table.c.workflow_id == workflow_id) count_stmt = count_stmt.where(table.c.workflow_id == workflow_id) if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) count_stmt = count_stmt.where(table.c.user_id == user_id) if schedule_id is not None: stmt = stmt.where(table.c.schedule_id == schedule_id) count_stmt = count_stmt.where(table.c.schedule_id == schedule_id) if run_id is not None: stmt = stmt.where(table.c.run_id == run_id) count_stmt = count_stmt.where(table.c.run_id == run_id) total = sess.execute(count_stmt).scalar() or 0 # Calculate offset from page offset = (page - 1) * limit stmt = stmt.order_by(table.c.created_at.desc()).limit(limit).offset(offset) results = sess.execute(stmt).fetchall() return [dict(row._mapping) for row in results], total except Exception as e: log_debug(f"Error listing approvals: {e}") return [], 0 def update_approval( self, approval_id: str, expected_status: Optional[str] = None, **kwargs: Any ) -> Optional[Dict[str, Any]]: try: table = self._get_table(table_type="approvals") if table is None: return None kwargs["updated_at"] = int(time.time()) with self.Session() as sess, sess.begin(): stmt = table.update().where(table.c.id == approval_id) if expected_status is not None: stmt = stmt.where(table.c.status == expected_status) result = sess.execute(stmt.values(**kwargs)) if result.rowcount == 0: return None return self.get_approval(approval_id) except Exception as e: log_debug(f"Error updating approval: {e}") return None def delete_approval(self, approval_id: str) -> bool: try: table = self._get_table(table_type="approvals") if table is None: return False with self.Session() as sess, sess.begin(): result = sess.execute(table.delete().where(table.c.id == approval_id)) return result.rowcount > 0 except Exception as e: log_debug(f"Error deleting approval: {e}") return False def get_pending_approval_count(self, user_id: Optional[str] = None) -> int: try: table = self._get_table(table_type="approvals") if table is None: return 0 with self.Session() as sess: stmt = select(func.count()).select_from(table).where(table.c.status == "pending") if user_id is not None: stmt = stmt.where(table.c.user_id == user_id) return sess.execute(stmt).scalar() or 0 except Exception as e: log_debug(f"Error counting approvals: {e}") return 0 def update_approval_run_status(self, run_id: str, run_status: RunStatus) -> int: """Update run_status on all approvals for a given run_id. Args: run_id: The run ID to match. run_status: The new run status. Returns: Number of approvals updated. """ try: table = self._get_table(table_type="approvals") if table is None: return 0 with self.Session() as sess, sess.begin(): stmt = ( table.update() .where(table.c.run_id == run_id) .values(run_status=run_status.value, updated_at=int(time.time())) ) result = sess.execute(stmt) return result.rowcount except Exception as e: log_debug(f"Error updating approval run_status: {e}") return 0
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/sqlite/sqlite.py", "license": "Apache License 2.0", "lines": 4104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/sqlite/utils.py
import json import time from datetime import date, datetime, timedelta, timezone from typing import Any, Dict, List, Optional from uuid import uuid4 from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession from agno.db.schemas.culture import CulturalKnowledge from agno.db.sqlite.schemas import get_table_schema_definition from agno.utils.log import log_debug, log_error, log_warning try: from sqlalchemy import Table, func from sqlalchemy.dialects import sqlite from sqlalchemy.engine import Engine from sqlalchemy.inspection import inspect from sqlalchemy.orm import Session from sqlalchemy.sql.expression import text except ImportError: raise ImportError("`sqlalchemy` not installed. Please install it using `pip install sqlalchemy`") # -- DB util methods -- def apply_sorting(stmt, table: Table, sort_by: Optional[str] = None, sort_order: Optional[str] = None): """Apply sorting to the given SQLAlchemy statement. Args: stmt: The SQLAlchemy statement to modify table: The table being queried sort_by: The field to sort by sort_order: The sort order ('asc' or 'desc') Returns: The modified statement with sorting applied Note: For 'updated_at' sorting, uses COALESCE(updated_at, created_at) to fall back to created_at when updated_at is NULL. This ensures pre-2.0 records (which may have NULL updated_at) are sorted correctly by their creation time. """ if sort_by is None: return stmt if not hasattr(table.c, sort_by): log_debug(f"Invalid sort field: '{sort_by}'. Will not apply any sorting.") return stmt # For updated_at, use COALESCE to fall back to created_at if updated_at is NULL # This handles pre-2.0 records that may have NULL updated_at values if sort_by == "updated_at" and hasattr(table.c, "created_at"): sort_column = func.coalesce(table.c.updated_at, table.c.created_at) else: sort_column = getattr(table.c, sort_by) if sort_order and sort_order == "asc": return stmt.order_by(sort_column.asc()) else: return stmt.order_by(sort_column.desc()) def is_table_available(session: Session, table_name: str, db_schema: Optional[str] = None) -> bool: """ Check if a table with the given name exists. Note: db_schema parameter is ignored in SQLite but kept for API compatibility. Returns: bool: True if the table exists, False otherwise. """ try: # SQLite uses sqlite_master instead of information_schema exists_query = text("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = :table") exists = session.execute(exists_query, {"table": table_name}).scalar() is not None if not exists: log_debug(f"Table {table_name} {'exists' if exists else 'does not exist'}") return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False async def ais_table_available(session: AsyncSession, table_name: str, db_schema: Optional[str] = None) -> bool: """ Check if a table with the given name exists. Note: db_schema parameter is ignored in SQLite but kept for API compatibility. Returns: bool: True if the table exists, False otherwise. """ try: exists_query = text("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = :table") exists = (await session.execute(exists_query, {"table": table_name})).scalar() is not None if not exists: log_debug(f"Table {table_name} {'exists' if exists else 'does not exist'}") return exists except Exception as e: log_error(f"Error checking if table exists: {e}") return False def is_valid_table(db_engine: Engine, table_name: str, table_type: str) -> bool: """ Check if the existing table has the expected column names. Args: db_engine (Engine): Database engine table_name (str): Name of the table to validate table_type (str): Type of table to get expected schema Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns (no schema parameter for SQLite) inspector = inspect(db_engine) existing_columns_info = inspector.get_columns(table_name) # No schema parameter existing_columns = set(col["name"] for col in existing_columns_info) # Check if all expected columns exist missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {table_name}") return False return True except Exception as e: log_error(f"Error validating table schema for {table_name}: {e}") return False async def ais_valid_table(db_engine: AsyncEngine, table_name: str, table_type: str) -> bool: """ Check if the existing table has the expected column names. Args: db_engine (Engine): Database engine table_name (str): Name of the table to validate table_type (str): Type of table to get expected schema Returns: bool: True if table has all expected columns, False otherwise """ try: expected_table_schema = get_table_schema_definition(table_type) expected_columns = {col_name for col_name in expected_table_schema.keys() if not col_name.startswith("_")} # Get existing columns from the async engine async with db_engine.connect() as conn: existing_columns = await conn.run_sync(_get_table_columns, table_name) missing_columns = expected_columns - existing_columns if missing_columns: log_warning(f"Missing columns {missing_columns} in table {table_name}") return False return True except Exception as e: log_error(f"Error validating table schema for {table_name}: {e}") return False def _get_table_columns(conn, table_name: str) -> set[str]: """Helper function to get table columns using sync inspector.""" inspector = inspect(conn) columns_info = inspector.get_columns(table_name) return {col["name"] for col in columns_info} # -- Metrics util methods -- def bulk_upsert_metrics(session: Session, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database. Args: table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] stmt = sqlite.insert(table) # Columns to update in case of conflict update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] } stmt = stmt.on_conflict_do_update(index_elements=["date", "aggregation_period"], set_=update_columns).returning( # type: ignore table ) result = session.execute(stmt, metrics_records) results = [row._mapping for row in result.fetchall()] session.commit() return results # type: ignore async def abulk_upsert_metrics(session: AsyncSession, table: Table, metrics_records: list[dict]) -> list[dict]: """Bulk upsert metrics into the database. Args: table (Table): The table to upsert into. metrics_records (list[dict]): The metrics records to upsert. Returns: list[dict]: The upserted metrics records. """ if not metrics_records: return [] results = [] stmt = sqlite.insert(table) # Columns to update in case of conflict update_columns = { col.name: stmt.excluded[col.name] for col in table.columns if col.name not in ["id", "date", "created_at", "aggregation_period"] } stmt = stmt.on_conflict_do_update(index_elements=["date", "aggregation_period"], set_=update_columns).returning( # type: ignore table ) result = await session.execute(stmt, metrics_records) results = [dict(row._mapping) for row in result.fetchall()] await session.commit() return results # type: ignore def calculate_date_metrics(date_to_process: date, sessions_data: dict) -> dict: """Calculate metrics for the given single date. Args: date_to_process (date): The date to calculate metrics for. sessions_data (dict): The sessions data to calculate metrics for. Returns: dict: The calculated metrics. """ metrics = { "users_count": 0, "agent_sessions_count": 0, "team_sessions_count": 0, "workflow_sessions_count": 0, "agent_runs_count": 0, "team_runs_count": 0, "workflow_runs_count": 0, } token_metrics = { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "audio_total_tokens": 0, "audio_input_tokens": 0, "audio_output_tokens": 0, "cache_read_tokens": 0, "cache_write_tokens": 0, "reasoning_tokens": 0, } model_counts: Dict[str, int] = {} session_types = [ ("agent", "agent_sessions_count", "agent_runs_count"), ("team", "team_sessions_count", "team_runs_count"), ("workflow", "workflow_sessions_count", "workflow_runs_count"), ] all_user_ids = set() for session_type, sessions_count_key, runs_count_key in session_types: sessions = sessions_data.get(session_type, []) or [] metrics[sessions_count_key] = len(sessions) for session in sessions: if session.get("user_id"): all_user_ids.add(session["user_id"]) # Parse runs from JSON string if runs := session.get("runs", []): runs = json.loads(runs) if isinstance(runs, str) else runs metrics[runs_count_key] += len(runs) for run in runs: if model_id := run.get("model"): model_provider = run.get("model_provider", "") model_counts[f"{model_id}:{model_provider}"] = ( model_counts.get(f"{model_id}:{model_provider}", 0) + 1 ) # Parse session_data from JSON string session_data = session.get("session_data", {}) if isinstance(session_data, str): session_data = json.loads(session_data) session_metrics = session_data.get("session_metrics", {}) for field in token_metrics: token_metrics[field] += session_metrics.get(field, 0) model_metrics = [] for model, count in model_counts.items(): model_id, model_provider = model.rsplit(":", 1) model_metrics.append({"model_id": model_id, "model_provider": model_provider, "count": count}) metrics["users_count"] = len(all_user_ids) current_time = int(time.time()) return { "id": str(uuid4()), "date": date_to_process, "completed": date_to_process < datetime.now(timezone.utc).date(), "token_metrics": token_metrics, "model_metrics": model_metrics, "created_at": current_time, "updated_at": current_time, "aggregation_period": "daily", **metrics, } def fetch_all_sessions_data( sessions: List[Dict[str, Any]], dates_to_process: list[date], start_timestamp: int ) -> Optional[dict]: """Return all session data for the given dates, for all session types. Args: dates_to_process (list[date]): The dates to fetch session data for. Returns: dict: A dictionary with dates as keys and session data as values, for all session types. Example: { "2000-01-01": { "agent": [<session1>, <session2>, ...], "team": [...], "workflow": [...], } } """ if not dates_to_process: return None all_sessions_data: Dict[str, Dict[str, List[Dict[str, Any]]]] = { date_to_process.isoformat(): {"agent": [], "team": [], "workflow": []} for date_to_process in dates_to_process } for session in sessions: session_date = ( datetime.fromtimestamp(session.get("created_at", start_timestamp), tz=timezone.utc).date().isoformat() ) if session_date in all_sessions_data: all_sessions_data[session_date][session["session_type"]].append(session) return all_sessions_data def get_dates_to_calculate_metrics_for(starting_date: date) -> list[date]: """Return the list of dates to calculate metrics for. Args: starting_date (date): The starting date to calculate metrics for. Returns: list[date]: The list of dates to calculate metrics for. """ today = datetime.now(timezone.utc).date() days_diff = (today - starting_date).days + 1 if days_diff <= 0: return [] return [starting_date + timedelta(days=x) for x in range(days_diff)] # -- Cultural Knowledge util methods -- def serialize_cultural_knowledge_for_db(cultural_knowledge: CulturalKnowledge) -> str: """Serialize a CulturalKnowledge object for database storage. Converts the model's separate content, categories, and notes fields into a single JSON string for the database content column. SQLite requires JSON to be stored as strings. Args: cultural_knowledge (CulturalKnowledge): The cultural knowledge object to serialize. Returns: str: A JSON string containing content, categories, and notes. """ content_dict: Dict[str, Any] = {} if cultural_knowledge.content is not None: content_dict["content"] = cultural_knowledge.content if cultural_knowledge.categories is not None: content_dict["categories"] = cultural_knowledge.categories if cultural_knowledge.notes is not None: content_dict["notes"] = cultural_knowledge.notes return json.dumps(content_dict) if content_dict else None # type: ignore def deserialize_cultural_knowledge_from_db(db_row: Dict[str, Any]) -> CulturalKnowledge: """Deserialize a database row to a CulturalKnowledge object. The database stores content as a JSON dict containing content, categories, and notes. This method extracts those fields and converts them back to the model format. Args: db_row (Dict[str, Any]): The database row as a dictionary. Returns: CulturalKnowledge: The cultural knowledge object. """ # Extract content, categories, and notes from the JSON content field content_json = db_row.get("content", {}) or {} if isinstance(content_json, str): content_json = json.loads(content_json) if content_json else {} return CulturalKnowledge.from_dict( { "id": db_row.get("id"), "name": db_row.get("name"), "summary": db_row.get("summary"), "content": content_json.get("content"), "categories": content_json.get("categories"), "notes": content_json.get("notes"), "metadata": db_row.get("metadata"), "input": db_row.get("input"), "created_at": db_row.get("created_at"), "updated_at": db_row.get("updated_at"), "agent_id": db_row.get("agent_id"), "team_id": db_row.get("team_id"), } )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/sqlite/utils.py", "license": "Apache License 2.0", "lines": 351, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/db/utils.py
"""Logic shared across different database implementations""" import json from datetime import date, datetime from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID from agno.metrics import ModelMetrics, RunMetrics, SessionMetrics from agno.models.message import Message from agno.utils.log import log_error, log_warning if TYPE_CHECKING: from agno.db.base import BaseDb def get_sort_value(record: Dict[str, Any], sort_by: str) -> Any: """Get the sort value for a record, with fallback to created_at for updated_at. When sorting by 'updated_at', this function falls back to 'created_at' if 'updated_at' is None. This ensures pre-2.0 records (which may have NULL updated_at values) are sorted correctly by their creation time. Args: record: The record dictionary to get the sort value from sort_by: The field to sort by Returns: The value to use for sorting """ value = record.get(sort_by) # For updated_at, fall back to created_at if updated_at is None if value is None and sort_by == "updated_at": value = record.get("created_at") return value class CustomJSONEncoder(json.JSONEncoder): """Custom encoder to handle non JSON serializable types.""" def default(self, obj): if isinstance(obj, UUID): return str(obj) elif isinstance(obj, (date, datetime)): return obj.isoformat() elif isinstance(obj, Message): return obj.to_dict() elif isinstance(obj, (RunMetrics, SessionMetrics, ModelMetrics)): return obj.to_dict() elif isinstance(obj, type): return str(obj) return super().default(obj) def json_serializer(obj: Any) -> str: """Custom JSON serializer for SQLAlchemy engine. This function is used as the json_serializer parameter when creating SQLAlchemy engines for PostgreSQL. It handles non-JSON-serializable types like datetime, date, UUID, etc. Args: obj: The object to serialize to JSON. Returns: JSON string representation of the object. """ return json.dumps(obj, cls=CustomJSONEncoder) def serialize_session_json_fields(session: dict) -> dict: """Serialize all JSON fields in the given Session dictionary. Uses CustomJSONEncoder to handle non-JSON-serializable types like datetime, date, UUID, Message, Metrics, etc. Args: data (dict): The dictionary to serialize JSON fields in. Returns: dict: The dictionary with JSON fields serialized. """ if session.get("session_data") is not None: session["session_data"] = json.dumps(session["session_data"], cls=CustomJSONEncoder) if session.get("agent_data") is not None: session["agent_data"] = json.dumps(session["agent_data"], cls=CustomJSONEncoder) if session.get("team_data") is not None: session["team_data"] = json.dumps(session["team_data"], cls=CustomJSONEncoder) if session.get("workflow_data") is not None: session["workflow_data"] = json.dumps(session["workflow_data"], cls=CustomJSONEncoder) if session.get("metadata") is not None: session["metadata"] = json.dumps(session["metadata"], cls=CustomJSONEncoder) if session.get("chat_history") is not None: session["chat_history"] = json.dumps(session["chat_history"], cls=CustomJSONEncoder) if session.get("summary") is not None: session["summary"] = json.dumps(session["summary"], cls=CustomJSONEncoder) if session.get("runs") is not None: session["runs"] = json.dumps(session["runs"], cls=CustomJSONEncoder) return session def deserialize_session_json_fields(session: dict) -> dict: """Deserialize JSON fields in the given Session dictionary. Args: session (dict): The dictionary to deserialize. Returns: dict: The dictionary with JSON string fields deserialized to objects. """ from agno.utils.log import log_warning if session.get("agent_data") is not None and isinstance(session["agent_data"], str): try: session["agent_data"] = json.loads(session["agent_data"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse agent_data as JSON, keeping as string: {e}") if session.get("team_data") is not None and isinstance(session["team_data"], str): try: session["team_data"] = json.loads(session["team_data"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse team_data as JSON, keeping as string: {e}") if session.get("workflow_data") is not None and isinstance(session["workflow_data"], str): try: session["workflow_data"] = json.loads(session["workflow_data"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse workflow_data as JSON, keeping as string: {e}") if session.get("metadata") is not None and isinstance(session["metadata"], str): try: session["metadata"] = json.loads(session["metadata"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse metadata as JSON, keeping as string: {e}") if session.get("chat_history") is not None and isinstance(session["chat_history"], str): try: session["chat_history"] = json.loads(session["chat_history"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse chat_history as JSON, keeping as string: {e}") if session.get("summary") is not None and isinstance(session["summary"], str): try: session["summary"] = json.loads(session["summary"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse summary as JSON, keeping as string: {e}") if session.get("session_data") is not None and isinstance(session["session_data"], str): try: session["session_data"] = json.loads(session["session_data"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse session_data as JSON, keeping as string: {e}") # Handle runs field with session type checking if session.get("runs") is not None and isinstance(session["runs"], str): try: session["runs"] = json.loads(session["runs"]) except (json.JSONDecodeError, TypeError) as e: log_warning(f"Warning: Could not parse runs as JSON, keeping as string: {e}") return session def db_from_dict(db_data: Dict[str, Any]) -> Optional[Union["BaseDb"]]: """ Create a database instance from a dictionary. Args: db_data: Dictionary containing database configuration Returns: Database instance or None if creation fails """ db_type = db_data.get("type") if db_type == "postgres": try: from agno.db.postgres import PostgresDb return PostgresDb.from_dict(db_data) except Exception as e: log_error(f"Error reconstructing PostgresDb from dictionary: {e}") return None elif db_type == "sqlite": try: from agno.db.sqlite import SqliteDb return SqliteDb.from_dict(db_data) except Exception as e: log_error(f"Error reconstructing SqliteDb from dictionary: {e}") return None else: log_warning(f"Unknown database type: {db_type}") return None
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/db/utils.py", "license": "Apache License 2.0", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/chunking/markdown.py
import os import re import tempfile from typing import List, Union try: from unstructured.chunking.title import chunk_by_title # type: ignore from unstructured.partition.md import partition_md # type: ignore except ImportError: raise ImportError("`unstructured` not installed. Please install it using `pip install unstructured markdown`") from agno.knowledge.chunking.strategy import ChunkingStrategy from agno.knowledge.document.base import Document class MarkdownChunking(ChunkingStrategy): """A chunking strategy that splits markdown based on structure like headers, paragraphs and sections Args: chunk_size: Maximum size of each chunk in characters overlap: Number of characters to overlap between chunks split_on_headings: Controls heading-based splitting behavior: - False: Use size-based chunking (default) - True: Split on all headings (H1-H6) - int: Split on headings at or above this level (1-6) e.g., 2 splits on H1 and H2, keeping H3-H6 content together """ def __init__(self, chunk_size: int = 5000, overlap: int = 0, split_on_headings: Union[bool, int] = False): self.chunk_size = chunk_size self.overlap = overlap self.split_on_headings = split_on_headings # Validate split_on_headings parameter # Note: In Python, isinstance(False, int) is True, so we exclude booleans explicitly if isinstance(split_on_headings, int) and not isinstance(split_on_headings, bool): if not (1 <= split_on_headings <= 6): raise ValueError("split_on_headings must be between 1 and 6 when using integer value") def _split_large_section(self, section: str) -> List[str]: """ Split a large section into smaller chunks while preserving the heading context. Each sub-chunk will include the original heading for context. Args: section: The section content to split (may start with a heading) Returns: List of chunks, each respecting chunk_size """ if len(section) <= self.chunk_size: return [section] # Extract heading and content from the section lines = section.split("\n") if lines and re.match(r"^#{1,6}\s+", lines[0]): heading = lines[0] content_lines = lines[1:] else: heading = "" content_lines = lines content = "\n".join(content_lines).strip() # If just heading and small content, return as-is if not content or len(section) <= self.chunk_size: return [section] # Split content by paragraphs paragraphs = re.split(r"\n\n+", content) chunks: List[str] = [] current_chunk_content: List[str] = [] # Account for heading size in each chunk heading_size = len(heading) + 2 if heading else 0 # +2 for "\n\n" for para in paragraphs: para = para.strip() if not para: continue current_size = sum(len(p) for p in current_chunk_content) + len(current_chunk_content) * 2 # \n\n para_size = len(para) # Check if adding this paragraph would exceed chunk_size if current_chunk_content and (heading_size + current_size + para_size + 2) > self.chunk_size: # Save current chunk chunk_text = ( heading + "\n\n" + "\n\n".join(current_chunk_content) if heading else "\n\n".join(current_chunk_content) ) chunks.append(chunk_text.strip()) current_chunk_content = [] # If single paragraph exceeds chunk_size, split it further if para_size + heading_size > self.chunk_size: # Save any accumulated content first if current_chunk_content: chunk_text = ( heading + "\n\n" + "\n\n".join(current_chunk_content) if heading else "\n\n".join(current_chunk_content) ) chunks.append(chunk_text.strip()) current_chunk_content = [] # Split the large paragraph by sentences or fixed size available_size = self.chunk_size - heading_size words = para.split() current_words: List[str] = [] current_word_len = 0 for word in words: if current_word_len + len(word) + 1 > available_size and current_words: chunk_text = heading + "\n\n" + " ".join(current_words) if heading else " ".join(current_words) chunks.append(chunk_text.strip()) current_words = [] current_word_len = 0 current_words.append(word) current_word_len += len(word) + 1 if current_words: current_chunk_content.append(" ".join(current_words)) else: current_chunk_content.append(para) # add the remaining content if current_chunk_content: chunk_text = ( heading + "\n\n" + "\n\n".join(current_chunk_content) if heading else "\n\n".join(current_chunk_content) ) chunks.append(chunk_text.strip()) return chunks if chunks else [section] def _split_by_headings(self, content: str) -> List[str]: """ Split markdown content by headings, keeping each heading with its content. Returns a list of sections where each section starts with a heading. When split_on_headings is an int, only splits on headings at or above that level. For example, split_on_headings=2 splits on H1 and H2, keeping H3-H6 content together. """ # Determine which heading levels to split on if isinstance(self.split_on_headings, int) and not isinstance(self.split_on_headings, bool): # Split on headings at or above this level (1 to split_on_headings) max_heading_level = self.split_on_headings heading_pattern = rf"^#{{{1},{max_heading_level}}}\s+.+$" else: # split_on_headings is True: split on all headings (# to ######) heading_pattern = r"^#{1,6}\s+.+$" # Split content while keeping the delimiter (heading) # Use non-capturing group for the pattern to avoid extra capture groups parts = re.split(f"({heading_pattern})", content, flags=re.MULTILINE) sections = [] current_section = "" for part in parts: if not part or not part.strip(): continue # Check if this part is a heading if re.match(heading_pattern, part.strip(), re.MULTILINE): # Save previous section if exists if current_section.strip(): sections.append(current_section.strip()) # Start new section with this heading current_section = part else: # Add content to current section current_section += "\n\n" + part if current_section else part # Don't forget the last section if current_section.strip(): sections.append(current_section.strip()) return sections if sections else [content] def _partition_markdown_content(self, content: str) -> List[str]: """ Partition markdown content and return a list of text chunks. Falls back to paragraph splitting if the markdown chunking fails. """ # When split_on_headings is True or an int, use regex-based splitting to preserve headings if self.split_on_headings: return self._split_by_headings(content) try: # Create a temporary file with the markdown content. # This is the recommended usage of the unstructured library. with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False, encoding="utf-8") as temp_file: temp_file.write(content) temp_file_path = temp_file.name try: elements = partition_md(filename=temp_file_path) if not elements: raw_paragraphs = content.split("\n\n") return [self.clean_text(para) for para in raw_paragraphs] chunked_elements = chunk_by_title( elements=elements, max_characters=self.chunk_size, new_after_n_chars=int(self.chunk_size * 0.8), combine_text_under_n_chars=self.chunk_size, overlap=0, ) # Generate the final text chunks text_chunks = [] for chunk_group in chunked_elements: if isinstance(chunk_group, list): chunk_text = "\n\n".join([elem.text for elem in chunk_group if hasattr(elem, "text")]) else: chunk_text = chunk_group.text if hasattr(chunk_group, "text") else str(chunk_group) if chunk_text.strip(): text_chunks.append(chunk_text.strip()) if text_chunks: return text_chunks raw_paragraphs = content.split("\n\n") return [self.clean_text(para) for para in raw_paragraphs] # Always clean up the temporary file finally: os.unlink(temp_file_path) # Fallback to simple paragraph splitting if the markdown chunking fails except Exception: raw_paragraphs = content.split("\n\n") return [self.clean_text(para) for para in raw_paragraphs] def chunk(self, document: Document) -> List[Document]: """Split markdown document into chunks based on markdown structure""" # If content is empty, return as-is if not document.content: return [document] # When split_on_headings is enabled, always split by headings regardless of size # Only skip chunking for small content when using size-based chunking if not self.split_on_headings and len(document.content) <= self.chunk_size: return [document] # Split using markdown chunking logic, or fallback to paragraphs sections = self._partition_markdown_content(document.content) chunks: List[Document] = [] current_chunk = [] current_size = 0 chunk_meta_data = document.meta_data chunk_number = 1 for section in sections: section = section.strip() section_size = len(section) # When split_on_headings is True or an int, each section becomes its own chunk # But if section exceeds chunk_size, split it further if self.split_on_headings: # Split large sections to respect chunk_size sub_chunks = self._split_large_section(section) for sub_chunk in sub_chunks: meta_data = chunk_meta_data.copy() meta_data["chunk"] = chunk_number chunk_id = self._generate_chunk_id(document, chunk_number, sub_chunk) meta_data["chunk_size"] = len(sub_chunk) chunks.append(Document(id=chunk_id, name=document.name, meta_data=meta_data, content=sub_chunk)) chunk_number += 1 elif current_size + section_size <= self.chunk_size: current_chunk.append(section) current_size += section_size else: meta_data = chunk_meta_data.copy() meta_data["chunk"] = chunk_number chunk_content = "\n\n".join(current_chunk) chunk_id = self._generate_chunk_id(document, chunk_number, chunk_content) meta_data["chunk_size"] = len(chunk_content) if current_chunk: chunks.append(Document(id=chunk_id, name=document.name, meta_data=meta_data, content=chunk_content)) chunk_number += 1 current_chunk = [section] current_size = section_size # Handle remaining content (only when not split_on_headings) if current_chunk and not self.split_on_headings: meta_data = chunk_meta_data.copy() meta_data["chunk"] = chunk_number chunk_content = "\n\n".join(current_chunk) chunk_id = self._generate_chunk_id(document, chunk_number, chunk_content) meta_data["chunk_size"] = len(chunk_content) chunks.append(Document(id=chunk_id, name=document.name, meta_data=meta_data, content=chunk_content)) # Handle overlap if specified if self.overlap > 0: overlapped_chunks = [] for i in range(len(chunks)): if i > 0: # Add overlap from previous chunk prev_text = chunks[i - 1].content[-self.overlap :] meta_data = chunk_meta_data.copy() meta_data["chunk"] = chunks[i].meta_data["chunk"] chunk_id = chunks[i].id meta_data["chunk_size"] = len(prev_text + chunks[i].content) if prev_text: overlapped_chunks.append( Document( id=chunk_id, name=document.name, meta_data=meta_data, content=prev_text + chunks[i].content, ) ) else: overlapped_chunks.append(chunks[i]) else: overlapped_chunks.append(chunks[i]) chunks = overlapped_chunks return chunks
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/chunking/markdown.py", "license": "Apache License 2.0", "lines": 273, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/chunking/row.py
from typing import List from agno.knowledge.chunking.strategy import ChunkingStrategy from agno.knowledge.document.base import Document class RowChunking(ChunkingStrategy): def __init__(self, skip_header: bool = False, clean_rows: bool = True): self.skip_header = skip_header self.clean_rows = clean_rows def chunk(self, document: Document) -> List[Document]: if not document or not document.content: return [] if not isinstance(document.content, str): raise ValueError("Document content must be a string") rows = document.content.splitlines() if self.skip_header and rows: rows = rows[1:] start_index = 2 else: start_index = 1 chunks = [] for i, row in enumerate(rows): if self.clean_rows: chunk_content = " ".join(row.split()) # Normalize internal whitespace else: chunk_content = row.strip() if chunk_content: # Skip empty rows meta_data = document.meta_data.copy() row_number = start_index + i meta_data["row_number"] = row_number # Preserve logical row numbering chunk_id = self._generate_chunk_id(document, row_number, chunk_content, prefix="row") chunks.append(Document(id=chunk_id, name=document.name, meta_data=meta_data, content=chunk_content)) return chunks
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/chunking/row.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/chunking/semantic.py
from typing import Any, Dict, List, Literal, Optional, Union try: import numpy as np except ImportError: raise ImportError("`numpy` not installed. Please install using `pip install numpy`") try: from chonkie import SemanticChunker from chonkie.embeddings.base import BaseEmbeddings except ImportError: raise ImportError( "`chonkie` is required for semantic chunking. " 'Please install it using `pip install "chonkie[semantic]"` to use SemanticChunking.' ) from agno.knowledge.chunking.strategy import ChunkingStrategy from agno.knowledge.document.base import Document from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_debug def _get_chonkie_embedder_wrapper(embedder: Embedder): """Create a wrapper that adapts Agno Embedder to chonkie's BaseEmbeddings interface.""" class _ChonkieEmbedderWrapper(BaseEmbeddings): """Wrapper to make Agno Embedders compatible with chonkie.""" def __init__(self, agno_embedder: Embedder): super().__init__() self._embedder = agno_embedder def embed(self, text: str): embedding = self._embedder.get_embedding(text) # type: ignore[attr-defined] return np.array(embedding, dtype=np.float32) def get_tokenizer(self): """Return a simple token counter function.""" return lambda text: len(text.split()) @property def dimension(self) -> int: return getattr(self._embedder, "dimensions") return _ChonkieEmbedderWrapper(embedder) class SemanticChunking(ChunkingStrategy): """Chunking strategy that splits text into semantic chunks using chonkie. Args: embedder: The embedder to use for generating embeddings. Can be: - A string model identifier (e.g., "minishlab/potion-base-32M") for chonkie's built-in models - A chonkie BaseEmbeddings instance (used directly) - An Agno Embedder (wrapped for chonkie compatibility) chunk_size: Maximum tokens allowed per chunk. similarity_threshold: Threshold for semantic similarity (0-1). similarity_window: Number of sentences to consider for similarity calculation. min_sentences_per_chunk: Minimum number of sentences per chunk. min_characters_per_sentence: Minimum number of characters per sentence. delimiters: Delimiters to use for sentence splitting. include_delimiters: Whether to include delimiter in prev/next sentence or None. skip_window: Number of groups to skip when merging (0=disabled). filter_window: Window length for the Savitzky-Golay filter. filter_polyorder: Polynomial order for the Savitzky-Golay filter. filter_tolerance: Tolerance for the Savitzky-Golay filter. chunker_params: Additional parameters to pass to chonkie's SemanticChunker. """ def __init__( self, embedder: Optional[Union[str, Embedder, BaseEmbeddings]] = None, chunk_size: int = 5000, similarity_threshold: float = 0.5, similarity_window: int = 3, min_sentences_per_chunk: int = 1, min_characters_per_sentence: int = 24, delimiters: Optional[List[str]] = None, include_delimiters: Literal["prev", "next", None] = "prev", skip_window: int = 0, filter_window: int = 5, filter_polyorder: int = 3, filter_tolerance: float = 0.2, chunker_params: Optional[Dict[str, Any]] = None, ): if embedder is None: from agno.knowledge.embedder.openai import OpenAIEmbedder embedder = OpenAIEmbedder() # type: ignore log_debug("Embedder not provided, using OpenAIEmbedder as default.") self.embedder = embedder self.chunk_size = chunk_size self.similarity_threshold = similarity_threshold self.similarity_window = similarity_window self.min_sentences_per_chunk = min_sentences_per_chunk self.min_characters_per_sentence = min_characters_per_sentence self.delimiters = delimiters if delimiters is not None else [". ", "! ", "? ", "\n"] self.include_delimiters = include_delimiters self.skip_window = skip_window self.filter_window = filter_window self.filter_polyorder = filter_polyorder self.filter_tolerance = filter_tolerance self.chunker_params = chunker_params self.chunker: Optional[SemanticChunker] = None def _initialize_chunker(self): """Lazily initialize the chunker with chonkie dependency.""" if self.chunker is not None: return # Determine embedding model based on type: # - str: pass directly to chonkie (uses chonkie's built-in models) # - BaseEmbeddings: pass directly to chonkie # - Agno Embedder: wrap for chonkie compatibility embedding_model: Union[str, BaseEmbeddings] if isinstance(self.embedder, str): embedding_model = self.embedder elif isinstance(self.embedder, BaseEmbeddings): embedding_model = self.embedder elif isinstance(self.embedder, Embedder): embedding_model = _get_chonkie_embedder_wrapper(self.embedder) else: raise ValueError("Invalid embedder type. Must be a string, BaseEmbeddings, or Embedder instance.") _chunker_params: Dict[str, Any] = { "embedding_model": embedding_model, "chunk_size": self.chunk_size, "threshold": self.similarity_threshold, "similarity_window": self.similarity_window, "min_sentences_per_chunk": self.min_sentences_per_chunk, "min_characters_per_sentence": self.min_characters_per_sentence, "delim": self.delimiters, "include_delim": self.include_delimiters, "skip_window": self.skip_window, "filter_window": self.filter_window, "filter_polyorder": self.filter_polyorder, "filter_tolerance": self.filter_tolerance, } if self.chunker_params: _chunker_params.update(self.chunker_params) self.chunker = SemanticChunker(**_chunker_params) def chunk(self, document: Document) -> List[Document]: """Split document into semantic chunks using chonkie""" if not document.content: return [document] # Ensure chunker is initialized (will raise ImportError if chonkie is missing) self._initialize_chunker() # Use chonkie to split into semantic chunks if self.chunker is None: raise RuntimeError("Chunker failed to initialize") chunks = self.chunker.chunk(self.clean_text(document.content)) # Convert chunks to Documents chunked_documents: List[Document] = [] for i, chunk in enumerate(chunks, 1): meta_data = document.meta_data.copy() meta_data["chunk"] = i chunk_id = self._generate_chunk_id(document, i, chunk.text) meta_data["chunk_size"] = len(chunk.text) chunked_documents.append(Document(id=chunk_id, name=document.name, meta_data=meta_data, content=chunk.text)) return chunked_documents
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/chunking/semantic.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/chunking/strategy.py
import hashlib from abc import ABC, abstractmethod from enum import Enum from typing import List, Optional from agno.knowledge.document.base import Document class ChunkingStrategy(ABC): """Base class for chunking strategies""" @abstractmethod def chunk(self, document: Document) -> List[Document]: raise NotImplementedError def _generate_chunk_id( self, document: Document, chunk_number: int, content: Optional[str] = None, prefix: Optional[str] = None ) -> Optional[str]: """Generate a deterministic ID for the chunk.""" suffix = f"_{prefix}_{chunk_number}" if prefix else f"_{chunk_number}" if document.id: return f"{document.id}{suffix}" elif document.name: return f"{document.name}{suffix}" else: # Hash the chunk content for a deterministic ID when no identifier exists hash_source = content if content else document.content if hash_source: content_hash = hashlib.md5(hash_source.encode("utf-8")).hexdigest()[:12] # nosec B324 return f"chunk_{content_hash}{suffix}" return None async def achunk(self, document: Document) -> List[Document]: """Async version of chunk. Override for truly async implementations.""" return self.chunk(document) def clean_text(self, text: str) -> str: """Clean the text by replacing multiple newlines with a single newline""" import re # Replace multiple newlines with a single newline cleaned_text = re.sub(r"\n+", "\n", text) # Replace multiple spaces with a single space cleaned_text = re.sub(r"\s+", " ", cleaned_text) # Replace multiple tabs with a single tab cleaned_text = re.sub(r"\t+", "\t", cleaned_text) # Replace multiple carriage returns with a single carriage return cleaned_text = re.sub(r"\r+", "\r", cleaned_text) # Replace multiple form feeds with a single form feed cleaned_text = re.sub(r"\f+", "\f", cleaned_text) # Replace multiple vertical tabs with a single vertical tab cleaned_text = re.sub(r"\v+", "\v", cleaned_text) return cleaned_text class ChunkingStrategyType(str, Enum): """Enumeration of available chunking strategies.""" AGENTIC_CHUNKER = "AgenticChunker" CODE_CHUNKER = "CodeChunker" DOCUMENT_CHUNKER = "DocumentChunker" RECURSIVE_CHUNKER = "RecursiveChunker" SEMANTIC_CHUNKER = "SemanticChunker" FIXED_SIZE_CHUNKER = "FixedSizeChunker" ROW_CHUNKER = "RowChunker" MARKDOWN_CHUNKER = "MarkdownChunker" @classmethod def from_string(cls, strategy_name: str) -> "ChunkingStrategyType": """Convert a string to a ChunkingStrategyType.""" strategy_name_clean = strategy_name.strip() # Try exact enum value match first for enum_member in cls: if enum_member.value == strategy_name_clean: return enum_member raise ValueError(f"Unsupported chunking strategy: {strategy_name}. Valid options: {[e.value for e in cls]}") class ChunkingStrategyFactory: """Factory for creating chunking strategy instances.""" @classmethod def create_strategy( cls, strategy_type: ChunkingStrategyType, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs, ) -> ChunkingStrategy: """Create an instance of the chunking strategy with the given parameters.""" strategy_map = { ChunkingStrategyType.AGENTIC_CHUNKER: cls._create_agentic_chunking, ChunkingStrategyType.CODE_CHUNKER: cls._create_code_chunking, ChunkingStrategyType.DOCUMENT_CHUNKER: cls._create_document_chunking, ChunkingStrategyType.RECURSIVE_CHUNKER: cls._create_recursive_chunking, ChunkingStrategyType.SEMANTIC_CHUNKER: cls._create_semantic_chunking, ChunkingStrategyType.FIXED_SIZE_CHUNKER: cls._create_fixed_chunking, ChunkingStrategyType.ROW_CHUNKER: cls._create_row_chunking, ChunkingStrategyType.MARKDOWN_CHUNKER: cls._create_markdown_chunking, } return strategy_map[strategy_type](chunk_size=chunk_size, overlap=overlap, **kwargs) @classmethod def _create_agentic_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.agentic import AgenticChunking # AgenticChunking accepts max_chunk_size (not chunk_size) and no overlap if chunk_size is not None: kwargs["max_chunk_size"] = chunk_size # Remove overlap since AgenticChunking doesn't support it return AgenticChunking(**kwargs) @classmethod def _create_code_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.code import CodeChunking # CodeChunking accepts chunk_size but not overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size # Remove overlap since CodeChunking doesn't support it return CodeChunking(**kwargs) @classmethod def _create_document_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.document import DocumentChunking # DocumentChunking accepts both chunk_size and overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size if overlap is not None: kwargs["overlap"] = overlap return DocumentChunking(**kwargs) @classmethod def _create_recursive_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.recursive import RecursiveChunking # RecursiveChunking accepts both chunk_size and overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size if overlap is not None: kwargs["overlap"] = overlap return RecursiveChunking(**kwargs) @classmethod def _create_semantic_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.semantic import SemanticChunking # SemanticChunking accepts chunk_size but not overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size # Remove overlap since SemanticChunking doesn't support it return SemanticChunking(**kwargs) @classmethod def _create_fixed_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.fixed import FixedSizeChunking # FixedSizeChunking accepts both chunk_size and overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size if overlap is not None: kwargs["overlap"] = overlap return FixedSizeChunking(**kwargs) @classmethod def _create_row_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.row import RowChunking # RowChunking doesn't accept chunk_size or overlap, only skip_header and clean_rows return RowChunking(**kwargs) @classmethod def _create_markdown_chunking( cls, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> ChunkingStrategy: from agno.knowledge.chunking.markdown import MarkdownChunking # MarkdownChunking accepts both chunk_size and overlap if chunk_size is not None: kwargs["chunk_size"] = chunk_size if overlap is not None: kwargs["overlap"] = overlap return MarkdownChunking(**kwargs)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/chunking/strategy.py", "license": "Apache License 2.0", "lines": 167, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/content.py
from dataclasses import dataclass from enum import Enum from typing import Any, Dict, List, Optional, Union from agno.knowledge.reader import Reader from agno.knowledge.remote_content.remote_content import RemoteContent class ContentStatus(str, Enum): """Enumeration of possible content processing statuses.""" PROCESSING = "processing" COMPLETED = "completed" FAILED = "failed" @dataclass class FileData: content: Optional[Union[str, bytes]] = None type: Optional[str] = None filename: Optional[str] = None size: Optional[int] = None @dataclass class ContentAuth: password: Optional[str] = None @dataclass class Content: id: Optional[str] = None name: Optional[str] = None description: Optional[str] = None path: Optional[str] = None url: Optional[str] = None auth: Optional[ContentAuth] = None file_data: Optional[FileData] = None metadata: Optional[Dict[str, Any]] = None topics: Optional[List[str]] = None remote_content: Optional[RemoteContent] = None reader: Optional[Reader] = None size: Optional[int] = None file_type: Optional[str] = None content_hash: Optional[str] = None status: Optional[ContentStatus] = None status_message: Optional[str] = None created_at: Optional[int] = None updated_at: Optional[int] = None external_id: Optional[str] = None @classmethod def from_dict(cls, data: Dict[str, Any]) -> "Content": return cls( id=data.get("id"), name=data.get("name"), description=data.get("description"), path=data.get("path"), url=data.get("url"), auth=data.get("auth"), file_data=data.get("file_data"), metadata=data.get("metadata"), topics=data.get("topics"), remote_content=data.get("remote_content"), reader=data.get("reader"), size=data.get("size"), file_type=data.get("file_type"), content_hash=data.get("content_hash"), status=data.get("status"), status_message=data.get("status_message"), created_at=data.get("created_at"), updated_at=data.get("updated_at"), external_id=data.get("external_id"), )
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/content.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/document/base.py
from dataclasses import dataclass, field from typing import Any, Dict, List, Optional from agno.knowledge.embedder import Embedder @dataclass class Document: """Dataclass for managing a document""" content: str id: Optional[str] = None name: Optional[str] = None meta_data: Dict[str, Any] = field(default_factory=dict) embedder: Optional["Embedder"] = None embedding: Optional[List[float]] = None usage: Optional[Dict[str, Any]] = None reranking_score: Optional[float] = None content_id: Optional[str] = None content_origin: Optional[str] = None size: Optional[int] = None def embed(self, embedder: Optional[Embedder] = None) -> None: """Embed the document using the provided embedder""" _embedder = embedder or self.embedder if _embedder is None: raise ValueError("No embedder provided") self.embedding, self.usage = _embedder.get_embedding_and_usage(self.content) async def async_embed(self, embedder: Optional[Embedder] = None) -> None: """Embed the document using the provided embedder""" _embedder = embedder or self.embedder if _embedder is None: raise ValueError("No embedder provided") self.embedding, self.usage = await _embedder.async_get_embedding_and_usage(self.content) def to_dict(self) -> Dict[str, Any]: """Returns a dictionary representation of the document""" fields = {"name", "meta_data", "content"} return { field: getattr(self, field) for field in fields if getattr(self, field) is not None or field == "content" # content is always included } @classmethod def from_dict(cls, document: Dict[str, Any]) -> "Document": """Returns a Document object from a dictionary representation""" return cls(**document) @classmethod def from_json(cls, document: str) -> "Document": """Returns a Document object from a json string representation""" import json return cls(**json.loads(document))
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/document/base.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/embedder/aws_bedrock.py
import json from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Literal, Optional, Tuple from agno.exceptions import AgnoError, ModelProviderError from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_error, log_warning try: from boto3 import client as AwsClient from boto3.session import Session from botocore.exceptions import ClientError except ImportError: log_error("`boto3` not installed. Please install it via `pip install boto3`.") raise try: import aioboto3 except ImportError: log_warning("`aioboto3` not installed. Async methods will not be available. Install via `pip install aioboto3`.") aioboto3 = None # Type aliases for clarity InputType = Literal["search_document", "search_query", "classification", "clustering"] EmbeddingType = Literal["float", "int8", "uint8", "binary", "ubinary"] TruncateV3 = Literal["NONE", "START", "END"] TruncateV4 = Literal["NONE", "LEFT", "RIGHT"] OutputDimension = Literal[256, 512, 1024, 1536] @dataclass class AwsBedrockEmbedder(Embedder): """ AWS Bedrock embedder supporting Cohere Embed v3 and v4 models. To use this embedder, you need to either: 1. Set the following environment variables: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_REGION 2. Or provide a boto3 Session object Args: id (str): The model ID to use. Default is 'cohere.embed-multilingual-v3'. - v3 models: 'cohere.embed-multilingual-v3', 'cohere.embed-english-v3' - v4 model: 'cohere.embed-v4:0' dimensions (Optional[int]): The dimensions of the embeddings. - v3: Fixed at 1024 - v4: Configurable via output_dimension (256, 512, 1024, 1536). Default 1536. input_type (str): Prepends special tokens to differentiate types. Options: 'search_document', 'search_query', 'classification', 'clustering'. Default is 'search_query'. truncate (Optional[str]): How to handle inputs longer than the maximum token length. - v3: 'NONE', 'START', 'END' - v4: 'NONE', 'LEFT', 'RIGHT' embedding_types (Optional[List[str]]): Types of embeddings to return. Options: 'float', 'int8', 'uint8', 'binary', 'ubinary'. Default is ['float']. output_dimension (Optional[int]): (v4 only) Vector length. Options: 256, 512, 1024, 1536. Default is 1536 if unspecified. max_tokens (Optional[int]): (v4 only) Truncation budget per input object. The model supports up to ~128,000 tokens. aws_region (Optional[str]): The AWS region to use. aws_access_key_id (Optional[str]): The AWS access key ID to use. aws_secret_access_key (Optional[str]): The AWS secret access key to use. session (Optional[Session]): A boto3 Session object to use for authentication. request_params (Optional[Dict[str, Any]]): Additional parameters to pass to the API requests. client_params (Optional[Dict[str, Any]]): Additional parameters to pass to the boto3 client. """ id: str = "cohere.embed-multilingual-v3" dimensions: int = 1024 # v3: 1024, v4: 1536 default (set in __post_init__) input_type: InputType = "search_query" truncate: Optional[str] = None # v3: 'NONE'|'START'|'END', v4: 'NONE'|'LEFT'|'RIGHT' embedding_types: Optional[List[EmbeddingType]] = None # 'float', 'int8', 'uint8', etc. # v4-specific parameters output_dimension: Optional[OutputDimension] = None # 256, 512, 1024, 1536 max_tokens: Optional[int] = None # Up to 128000 for v4 aws_region: Optional[str] = None aws_access_key_id: Optional[str] = None aws_secret_access_key: Optional[str] = None session: Optional[Session] = None request_params: Optional[Dict[str, Any]] = None client_params: Optional[Dict[str, Any]] = None client: Optional[AwsClient] = None def __post_init__(self): if self.enable_batch: log_warning("AwsBedrockEmbedder does not support batch embeddings, setting enable_batch to False") self.enable_batch = False # Set appropriate default dimensions based on model version if self._is_v4_model(): # v4 default is 1536, but can be overridden by output_dimension if self.output_dimension: self.dimensions = self.output_dimension else: self.dimensions = 1536 else: # v3 models are fixed at 1024 self.dimensions = 1024 def _is_v4_model(self) -> bool: """Check if the current model is a Cohere Embed v4 model.""" return "embed-v4" in self.id.lower() def get_client(self) -> AwsClient: """ Returns an AWS Bedrock client. Credentials are resolved in the following order: 1. Explicit session parameter 2. Explicit aws_access_key_id and aws_secret_access_key parameters 3. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) 4. Default boto3 credential chain (~/.aws/credentials, SSO, IAM role, etc.) Returns: AwsClient: An instance of the AWS Bedrock client. """ if self.client is not None: return self.client if self.session: self.client = self.session.client("bedrock-runtime") return self.client # Try explicit credentials or environment variables self.aws_access_key_id = self.aws_access_key_id or getenv("AWS_ACCESS_KEY_ID") self.aws_secret_access_key = self.aws_secret_access_key or getenv("AWS_SECRET_ACCESS_KEY") self.aws_region = self.aws_region or getenv("AWS_REGION") if self.aws_access_key_id and self.aws_secret_access_key: # Use explicit credentials self.client = AwsClient( service_name="bedrock-runtime", region_name=self.aws_region, aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, **(self.client_params or {}), ) else: # Fall back to default credential chain (SSO, credentials file, IAM role, etc.) self.client = AwsClient( service_name="bedrock-runtime", region_name=self.aws_region, **(self.client_params or {}), ) return self.client def get_async_client(self): """ Returns an async AWS Bedrock client using aioboto3. Credentials are resolved in the following order: 1. Explicit session parameter 2. Explicit aws_access_key_id and aws_secret_access_key parameters 3. Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) 4. Default credential chain (~/.aws/credentials, SSO, IAM role, etc.) Returns: An aioboto3 bedrock-runtime client context manager. """ if aioboto3 is None: raise AgnoError( message="aioboto3 not installed. Please install it via `pip install aioboto3`.", status_code=400, ) if self.session: # Convert boto3 session to aioboto3 session aio_session = aioboto3.Session( aws_access_key_id=self.session.get_credentials().access_key, aws_secret_access_key=self.session.get_credentials().secret_key, aws_session_token=self.session.get_credentials().token, region_name=self.session.region_name, ) else: # Try explicit credentials or environment variables self.aws_access_key_id = self.aws_access_key_id or getenv("AWS_ACCESS_KEY_ID") self.aws_secret_access_key = self.aws_secret_access_key or getenv("AWS_SECRET_ACCESS_KEY") self.aws_region = self.aws_region or getenv("AWS_REGION") if self.aws_access_key_id and self.aws_secret_access_key: # Use explicit credentials aio_session = aioboto3.Session( aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, region_name=self.aws_region, ) else: # Fall back to default credential chain (SSO, credentials file, IAM role, etc.) aio_session = aioboto3.Session(region_name=self.aws_region) return aio_session.client("bedrock-runtime", **(self.client_params or {})) def _format_request_body(self, text: str) -> str: """ Format the request body for the embedder. Args: text (str): The text to embed. Returns: str: The formatted request body as a JSON string. """ request_body: Dict[str, Any] = { "texts": [text], "input_type": self.input_type, } if self.truncate: request_body["truncate"] = self.truncate if self.embedding_types: request_body["embedding_types"] = self.embedding_types # v4-specific parameters if self._is_v4_model(): if self.output_dimension: request_body["output_dimension"] = self.output_dimension if self.max_tokens: request_body["max_tokens"] = self.max_tokens # Add additional request parameters if provided if self.request_params: request_body.update(self.request_params) return json.dumps(request_body) def _format_multimodal_request_body( self, texts: Optional[List[str]] = None, images: Optional[List[str]] = None, inputs: Optional[List[Dict[str, Any]]] = None, ) -> str: """ Format a multimodal request body for v4 models. Args: texts: List of text strings to embed (text-only mode) images: List of base64 data URIs for images (image-only mode) inputs: List of interleaved content items for mixed modality Returns: str: The formatted request body as a JSON string. """ if not self._is_v4_model(): raise AgnoError( message="Multimodal embeddings are only supported with Cohere Embed v4 models.", status_code=400, ) request_body: Dict[str, Any] = { "input_type": self.input_type, } # Set the appropriate input field if inputs: request_body["inputs"] = inputs elif images: request_body["images"] = images elif texts: request_body["texts"] = texts else: raise AgnoError( message="At least one of texts, images, or inputs must be provided.", status_code=400, ) if self.truncate: request_body["truncate"] = self.truncate if self.embedding_types: request_body["embedding_types"] = self.embedding_types if self.output_dimension: request_body["output_dimension"] = self.output_dimension if self.max_tokens: request_body["max_tokens"] = self.max_tokens if self.request_params: request_body.update(self.request_params) return json.dumps(request_body) def _extract_embeddings(self, response_body: Dict[str, Any]) -> List[float]: """ Extract embeddings from the response body, handling both v3 and v4 formats. Args: response_body: The parsed response body from the API. Returns: List[float]: The embedding vector. """ try: if "embeddings" in response_body: embeddings = response_body["embeddings"] # Handle list format (single embedding type or v3 default) if isinstance(embeddings, list): return embeddings[0] if embeddings else [] # Handle dict format (multiple embedding types requested) if isinstance(embeddings, dict): # Prefer float embeddings if "float" in embeddings: return embeddings["float"][0] # Fallback to first available type for embedding_type in embeddings: if embeddings[embedding_type]: return embeddings[embedding_type][0] log_warning("No embeddings found in response") return [] except Exception as e: log_warning(f"Error extracting embeddings: {e}") return [] def response(self, text: str) -> Dict[str, Any]: """ Get embeddings from AWS Bedrock for the given text. Args: text (str): The text to embed. Returns: Dict[str, Any]: The response from the API. """ try: body = self._format_request_body(text) response = self.get_client().invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads(response["body"].read().decode("utf-8")) return response_body except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e def get_embedding(self, text: str) -> List[float]: """ Get embeddings for the given text. Args: text (str): The text to embed. Returns: List[float]: The embedding vector. """ response = self.response(text=text) return self._extract_embeddings(response) def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: """ Get embeddings and usage information for the given text. Args: text (str): The text to embed. Returns: Tuple[List[float], Optional[Dict[str, Any]]]: The embedding vector and usage information. """ response = self.response(text=text) embedding = self._extract_embeddings(response) usage = response.get("usage") return embedding, usage def get_image_embedding(self, image_data_uri: str) -> List[float]: """ Get embeddings for an image (v4 only). Args: image_data_uri (str): Base64 data URI of the image (e.g., "data:image/png;base64,...") Returns: List[float]: The embedding vector. """ if not self._is_v4_model(): raise AgnoError( message="Image embeddings are only supported with Cohere Embed v4 models.", status_code=400, ) try: body = self._format_multimodal_request_body(images=[image_data_uri]) response = self.get_client().invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads(response["body"].read().decode("utf-8")) return self._extract_embeddings(response_body) except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e def get_multimodal_embedding( self, content: List[Dict[str, str]], ) -> List[float]: """ Get embeddings for interleaved text and image content (v4 only). Args: content: List of content parts, each being either: - {"type": "text", "text": "..."} - {"type": "image_url", "image_url": "data:image/png;base64,..."} Returns: List[float]: The embedding vector. Example: embedder.get_multimodal_embedding([ {"type": "text", "text": "Product description"}, {"type": "image_url", "image_url": "data:image/png;base64,..."} ]) """ if not self._is_v4_model(): raise AgnoError( message="Multimodal embeddings are only supported with Cohere Embed v4 models.", status_code=400, ) try: inputs = [{"content": content}] body = self._format_multimodal_request_body(inputs=inputs) response = self.get_client().invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads(response["body"].read().decode("utf-8")) return self._extract_embeddings(response_body) except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e async def async_get_embedding(self, text: str) -> List[float]: """ Async version of get_embedding() using native aioboto3 async client. """ try: body = self._format_request_body(text) async with self.get_async_client() as client: response = await client.invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads((await response["body"].read()).decode("utf-8")) return self._extract_embeddings(response_body) except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: """ Async version of get_embedding_and_usage() using native aioboto3 async client. """ try: body = self._format_request_body(text) async with self.get_async_client() as client: response = await client.invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads((await response["body"].read()).decode("utf-8")) embedding = self._extract_embeddings(response_body) usage = response_body.get("usage") return embedding, usage except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e async def async_get_image_embedding(self, image_data_uri: str) -> List[float]: """ Async version of get_image_embedding() (v4 only). """ if not self._is_v4_model(): raise AgnoError( message="Image embeddings are only supported with Cohere Embed v4 models.", status_code=400, ) try: body = self._format_multimodal_request_body(images=[image_data_uri]) async with self.get_async_client() as client: response = await client.invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads((await response["body"].read()).decode("utf-8")) return self._extract_embeddings(response_body) except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e async def async_get_multimodal_embedding( self, content: List[Dict[str, str]], ) -> List[float]: """ Async version of get_multimodal_embedding() (v4 only). """ if not self._is_v4_model(): raise AgnoError( message="Multimodal embeddings are only supported with Cohere Embed v4 models.", status_code=400, ) try: inputs = [{"content": content}] body = self._format_multimodal_request_body(inputs=inputs) async with self.get_async_client() as client: response = await client.invoke_model( modelId=self.id, body=body, contentType="application/json", accept="application/json", ) response_body = json.loads((await response["body"].read()).decode("utf-8")) return self._extract_embeddings(response_body) except ClientError as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e.response), model_name="AwsBedrockEmbedder", model_id=self.id) from e except Exception as e: log_error(f"Unexpected error calling Bedrock API: {str(e)}") raise ModelProviderError(message=str(e), model_name="AwsBedrockEmbedder", model_id=self.id) from e
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/aws_bedrock.py", "license": "Apache License 2.0", "lines": 485, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/azure_openai.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Tuple from typing_extensions import Literal from agno.knowledge.embedder.base import Embedder from agno.utils.log import logger try: from openai import AsyncAzureOpenAI as AsyncAzureOpenAIClient from openai import AzureOpenAI as AzureOpenAIClient from openai.types.create_embedding_response import CreateEmbeddingResponse except ImportError: raise ImportError("`openai` not installed") @dataclass class AzureOpenAIEmbedder(Embedder): id: str = "text-embedding-3-small" # This has to match the model that you deployed at the provided URL dimensions: int = 1536 encoding_format: Literal["float", "base64"] = "float" user: Optional[str] = None api_key: Optional[str] = getenv("AZURE_EMBEDDER_OPENAI_API_KEY") api_version: str = getenv("AZURE_EMBEDDER_OPENAI_API_VERSION", "2024-10-21") azure_endpoint: Optional[str] = getenv("AZURE_EMBEDDER_OPENAI_ENDPOINT") azure_deployment: Optional[str] = getenv("AZURE_EMBEDDER_DEPLOYMENT") base_url: Optional[str] = None azure_ad_token: Optional[str] = None azure_ad_token_provider: Optional[Any] = None organization: Optional[str] = None request_params: Optional[Dict[str, Any]] = None client_params: Optional[Dict[str, Any]] = None openai_client: Optional[AzureOpenAIClient] = None async_client: Optional[AsyncAzureOpenAIClient] = None @property def client(self) -> AzureOpenAIClient: if self.openai_client: return self.openai_client _client_params: Dict[str, Any] = {} if self.api_key: _client_params["api_key"] = self.api_key if self.api_version: _client_params["api_version"] = self.api_version if self.organization: _client_params["organization"] = self.organization if self.azure_endpoint: _client_params["azure_endpoint"] = self.azure_endpoint if self.azure_deployment: _client_params["azure_deployment"] = self.azure_deployment if self.base_url: _client_params["base_url"] = self.base_url if self.azure_ad_token: _client_params["azure_ad_token"] = self.azure_ad_token if self.azure_ad_token_provider: _client_params["azure_ad_token_provider"] = self.azure_ad_token_provider if self.client_params: _client_params.update(self.client_params) return AzureOpenAIClient(**_client_params) @property def aclient(self) -> AsyncAzureOpenAIClient: if self.async_client: return self.async_client _client_params: Dict[str, Any] = {} if self.api_key: _client_params["api_key"] = self.api_key if self.api_version: _client_params["api_version"] = self.api_version if self.organization: _client_params["organization"] = self.organization if self.azure_endpoint: _client_params["azure_endpoint"] = self.azure_endpoint if self.azure_deployment: _client_params["azure_deployment"] = self.azure_deployment if self.base_url: _client_params["base_url"] = self.base_url if self.azure_ad_token: _client_params["azure_ad_token"] = self.azure_ad_token if self.azure_ad_token_provider: _client_params["azure_ad_token_provider"] = self.azure_ad_token_provider if self.client_params: _client_params.update(self.client_params) self.async_client = AsyncAzureOpenAIClient(**_client_params) return self.async_client def _response(self, text: str) -> CreateEmbeddingResponse: _request_params: Dict[str, Any] = { "input": text, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: _request_params["user"] = self.user if self.id.startswith("text-embedding-3"): _request_params["dimensions"] = self.dimensions if self.request_params: _request_params.update(self.request_params) return self.client.embeddings.create(**_request_params) def get_embedding(self, text: str) -> List[float]: response: CreateEmbeddingResponse = self._response(text=text) try: return response.data[0].embedding except Exception as e: logger.warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: response: CreateEmbeddingResponse = self._response(text=text) embedding = response.data[0].embedding usage = response.usage return embedding, usage.model_dump() async def _aresponse(self, text: str) -> CreateEmbeddingResponse: """Async version of _response method.""" _request_params: Dict[str, Any] = { "input": text, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: _request_params["user"] = self.user if self.id.startswith("text-embedding-3"): _request_params["dimensions"] = self.dimensions if self.request_params: _request_params.update(self.request_params) return await self.aclient.embeddings.create(**_request_params) async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding using the native Azure OpenAI async client.""" response: CreateEmbeddingResponse = await self._aresponse(text=text) try: return response.data[0].embedding except Exception as e: logger.warning(e) return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version of get_embedding_and_usage using the native Azure OpenAI async client.""" response: CreateEmbeddingResponse = await self._aresponse(text=text) embedding = response.data[0].embedding usage = response.usage return embedding, usage.model_dump() async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """ Get embeddings and usage for multiple texts in batches. Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings = [] all_usage = [] logger.info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size}") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] req: Dict[str, Any] = { "input": batch_texts, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: req["user"] = self.user if self.id.startswith("text-embedding-3"): req["dimensions"] = self.dimensions if self.request_params: req.update(self.request_params) try: response: CreateEmbeddingResponse = await self.aclient.embeddings.create(**req) batch_embeddings = [data.embedding for data in response.data] all_embeddings.extend(batch_embeddings) # For each embedding in the batch, add the same usage information usage_dict = response.usage.model_dump() if response.usage else None all_usage.extend([usage_dict] * len(batch_embeddings)) except Exception as e: logger.warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: logger.warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/azure_openai.py", "license": "Apache License 2.0", "lines": 178, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/base.py
from dataclasses import dataclass from typing import Dict, List, Optional, Tuple @dataclass class Embedder: """Base class for managing embedders""" dimensions: Optional[int] = 1536 enable_batch: bool = False batch_size: int = 100 # Number of texts to process in each API call def get_embedding(self, text: str) -> List[float]: raise NotImplementedError def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: raise NotImplementedError async def async_get_embedding(self, text: str) -> List[float]: raise NotImplementedError async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: raise NotImplementedError
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/base.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/embedder/cohere.py
import time from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_debug, log_error, log_info, log_warning try: from cohere import AsyncClient as AsyncCohereClient from cohere import Client as CohereClient from cohere.types.embed_response import EmbeddingsByTypeEmbedResponse, EmbeddingsFloatsEmbedResponse except ImportError: raise ImportError("`cohere` not installed. Please install using `pip install cohere`.") @dataclass class CohereEmbedder(Embedder): id: str = "embed-english-v3.0" input_type: str = "search_query" embedding_types: Optional[List[str]] = None api_key: Optional[str] = None request_params: Optional[Dict[str, Any]] = None client_params: Optional[Dict[str, Any]] = None cohere_client: Optional[CohereClient] = None async_client: Optional[AsyncCohereClient] = None exponential_backoff: bool = False # Enable exponential backoff on rate limits @property def client(self) -> CohereClient: if self.cohere_client: return self.cohere_client client_params: Dict[str, Any] = {} if self.api_key: client_params["api_key"] = self.api_key if self.client_params: client_params.update(self.client_params) self.cohere_client = CohereClient(**client_params) return self.cohere_client @property def aclient(self) -> AsyncCohereClient: """Lazy init for Cohere async client.""" if self.async_client: return self.async_client params: Dict[str, Any] = {} if self.api_key: params["api_key"] = self.api_key if self.client_params: params.update(self.client_params) self.async_client = AsyncCohereClient(**params) return self.async_client def response(self, text: str) -> Union[EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse]: request_params: Dict[str, Any] = {} if self.id: request_params["model"] = self.id if self.input_type: request_params["input_type"] = self.input_type if self.embedding_types: request_params["embedding_types"] = self.embedding_types if self.request_params: request_params.update(self.request_params) return self.client.embed(texts=[text], **request_params) def _get_batch_request_params(self) -> Dict[str, Any]: """Get request parameters for batch embedding calls.""" request_params: Dict[str, Any] = {} if self.id: request_params["model"] = self.id if self.input_type: request_params["input_type"] = self.input_type if self.embedding_types: request_params["embedding_types"] = self.embedding_types if self.request_params: request_params.update(self.request_params) return request_params def _is_rate_limit_error(self, error: Exception) -> bool: """Check if the error is a rate limiting error.""" if hasattr(error, "status_code") and error.status_code == 429: return True error_str = str(error).lower() return any( phrase in error_str for phrase in ["rate limit", "too many requests", "429", "trial key", "api calls / minute"] ) def _exponential_backoff_sleep(self, attempt: int, base_delay: float = 1.0) -> None: """Sleep with exponential backoff.""" delay = base_delay * (2**attempt) + (time.time() % 1) # Add jitter log_debug(f"Rate limited, waiting {delay:.2f} seconds before retry (attempt {attempt + 1})") time.sleep(delay) async def _async_rate_limit_backoff_sleep(self, attempt: int) -> None: """Async version of rate-limit-aware backoff for APIs with per-minute limits.""" import asyncio # For 40 req/min APIs like Cohere Trial, we need longer waits if attempt == 0: delay = 15.0 # Wait 15 seconds (1/4 of minute window) elif attempt == 1: delay = 30.0 # Wait 30 seconds (1/2 of minute window) else: delay = 60.0 # Wait full minute for window reset # Add small jitter delay += time.time() % 3 log_debug( f"Async rate limit backoff, waiting {delay:.1f} seconds for rate limit window reset (attempt {attempt + 1})" ) await asyncio.sleep(delay) async def _async_batch_with_retry( self, texts: List[str], max_retries: int = 3 ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """Execute async batch embedding with rate-limit-aware backoff for rate limiting.""" log_debug(f"Starting async batch retry for {len(texts)} texts with max_retries={max_retries}") for attempt in range(max_retries + 1): try: request_params = self._get_batch_request_params() response: Union[ EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse ] = await self.aclient.embed(texts=texts, **request_params) # Extract embeddings from response if isinstance(response, EmbeddingsFloatsEmbedResponse): batch_embeddings = response.embeddings elif isinstance(response, EmbeddingsByTypeEmbedResponse): batch_embeddings = response.embeddings.float_ if response.embeddings.float_ else [] else: log_warning("No embeddings found in response") batch_embeddings = [] # Extract usage information usage = response.meta.billed_units if response.meta else None usage_dict = usage.model_dump() if usage else None all_usage = [usage_dict] * len(batch_embeddings) log_debug(f"Async batch embedding succeeded on attempt {attempt + 1}") return batch_embeddings, all_usage except Exception as e: if self._is_rate_limit_error(e): if not self.exponential_backoff: log_warning( "Rate limit detected. To enable automatic backoff retry, set enable_backoff=True when creating the embedder." ) raise e log_info(f"Async rate limit detected on attempt {attempt + 1}") if attempt < max_retries: await self._async_rate_limit_backoff_sleep(attempt) continue else: log_warning(f"Async max retries ({max_retries}) reached for rate limiting") raise e else: log_debug(f"Async non-rate-limit error on attempt {attempt + 1}: {e}") raise e # This should never be reached, but just in case log_error("Could not create embeddings. End of retry loop reached.") return [], [] def get_embedding(self, text: str) -> List[float]: response: Union[EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse] = self.response(text=text) try: if isinstance(response, EmbeddingsFloatsEmbedResponse): return response.embeddings[0] elif isinstance(response, EmbeddingsByTypeEmbedResponse): return response.embeddings.float_[0] if response.embeddings.float_ else [] else: log_warning("No embeddings found") return [] except Exception as e: log_warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: response: Union[EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse] = self.response(text=text) embedding: List[float] = [] if isinstance(response, EmbeddingsFloatsEmbedResponse): embedding = response.embeddings[0] elif isinstance(response, EmbeddingsByTypeEmbedResponse): embedding = response.embeddings.float_[0] if response.embeddings.float_ else [] usage = response.meta.billed_units if response.meta else None if usage: return embedding, usage.model_dump() return embedding, None async def async_get_embedding(self, text: str) -> List[float]: request_params: Dict[str, Any] = {} if self.id: request_params["model"] = self.id if self.input_type: request_params["input_type"] = self.input_type if self.embedding_types: request_params["embedding_types"] = self.embedding_types if self.request_params: request_params.update(self.request_params) try: response: Union[EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse] = await self.aclient.embed( texts=[text], **request_params ) if isinstance(response, EmbeddingsFloatsEmbedResponse): return response.embeddings[0] elif isinstance(response, EmbeddingsByTypeEmbedResponse): return response.embeddings.float_[0] if response.embeddings.float_ else [] else: log_warning("No embeddings found") return [] except Exception as e: log_warning(e) return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: request_params: Dict[str, Any] = {} if self.id: request_params["model"] = self.id if self.input_type: request_params["input_type"] = self.input_type if self.embedding_types: request_params["embedding_types"] = self.embedding_types if self.request_params: request_params.update(self.request_params) response: Union[EmbeddingsFloatsEmbedResponse, EmbeddingsByTypeEmbedResponse] = await self.aclient.embed( texts=[text], **request_params ) embedding: List[float] = [] if isinstance(response, EmbeddingsFloatsEmbedResponse): embedding = response.embeddings[0] elif isinstance(response, EmbeddingsByTypeEmbedResponse): embedding = response.embeddings.float_[0] if response.embeddings.float_ else [] usage = response.meta.billed_units if response.meta else None if usage: return embedding, usage.model_dump() return embedding, None async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """ Get embeddings and usage for multiple texts in batches (async version). Args: texts: List of text strings to embed Returns: s, List of usage dictionaries) """ all_embeddings = [] all_usage = [] log_info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size} (async)") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] try: # Use retry logic for batch processing batch_embeddings, batch_usage = await self._async_batch_with_retry(batch_texts) all_embeddings.extend(batch_embeddings) all_usage.extend(batch_usage) except Exception as e: log_warning(f"Async batch embedding failed after retries: {e}") # Check if this is a rate limit error and backoff is disabled if self._is_rate_limit_error(e) and not self.exponential_backoff: log_warning("Rate limit hit and backoff is disabled. Failing immediately.") raise e # Only fall back to individual calls for non-rate-limit errors # For rate limit errors, we should reduce batch size instead if self._is_rate_limit_error(e): log_warning("Rate limit hit even after retries. Consider reducing batch_size or upgrading API key.") # Try with smaller batch size if len(batch_texts) > 1: smaller_batch_size = max(1, len(batch_texts) // 2) log_info(f"Retrying with smaller batch size: {smaller_batch_size}") for j in range(0, len(batch_texts), smaller_batch_size): small_batch = batch_texts[j : j + smaller_batch_size] try: small_embeddings, small_usage = await self._async_batch_with_retry(small_batch) all_embeddings.extend(small_embeddings) all_usage.extend(small_usage) except Exception as e3: log_error(f"Failed even with reduced batch size: {e3}") # Fall back to empty results for this batch all_embeddings.extend([[] for _ in small_batch]) all_usage.extend([None for _ in small_batch]) else: # Single item already failed, add empty result log_debug("Single item failed, adding empty result") all_embeddings.append([]) all_usage.append(None) else: # For non-rate-limit errors, fall back to individual calls log_debug("Non-rate-limit error, falling back to individual calls") for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: log_warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/cohere.py", "license": "Apache License 2.0", "lines": 276, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/fastembed.py
from dataclasses import dataclass from typing import Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import logger try: import numpy as np except ImportError: raise ImportError("numpy not installed, use `pip install numpy`") try: from fastembed import TextEmbedding # type: ignore except ImportError: raise ImportError("fastembed not installed, use pip install fastembed") @dataclass class FastEmbedEmbedder(Embedder): """Using BAAI/bge-small-en-v1.5 model, more models available: https://qdrant.github.io/fastembed/examples/Supported_Models/""" id: str = "BAAI/bge-small-en-v1.5" dimensions: Optional[int] = 384 fastembed_client: Optional[TextEmbedding] = None @property def client(self) -> TextEmbedding: if self.fastembed_client is None: self.fastembed_client = TextEmbedding(model_name=self.id) return self.fastembed_client def get_embedding(self, text: str) -> List[float]: embeddings = self.client.embed(text) embedding_list = list(embeddings)[0] if isinstance(embedding_list, np.ndarray): return embedding_list.tolist() try: return list(embedding_list) except Exception as e: logger.warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: embedding = self.get_embedding(text=text) # Currently, FastEmbed does not provide usage information usage = None return embedding, usage async def async_get_embedding(self, text: str) -> List[float]: """Async version using thread executor for CPU-bound operations.""" import asyncio loop = asyncio.get_event_loop() # Run the CPU-bound operation in a thread executor return await loop.run_in_executor(None, self.get_embedding, text) async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version using thread executor for CPU-bound operations.""" import asyncio loop = asyncio.get_event_loop() # Run the CPU-bound operation in a thread executor return await loop.run_in_executor(None, self.get_embedding_and_usage, text)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/fastembed.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/embedder/google.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_error, log_info, log_warning try: from google import genai from google.genai import Client as GeminiClient from google.genai.types import EmbedContentResponse except ImportError: raise ImportError("`google-genai` not installed. Please install it using `pip install google-genai`") @dataclass class GeminiEmbedder(Embedder): id: str = "gemini-embedding-001" task_type: str = "RETRIEVAL_QUERY" title: Optional[str] = None dimensions: Optional[int] = 1536 api_key: Optional[str] = None request_params: Optional[Dict[str, Any]] = None client_params: Optional[Dict[str, Any]] = None gemini_client: Optional[GeminiClient] = None # Vertex AI parameters vertexai: bool = False project_id: Optional[str] = None location: Optional[str] = None @property def client(self): if self.gemini_client: return self.gemini_client _client_params: Dict[str, Any] = {} vertexai = self.vertexai or getenv("GOOGLE_GENAI_USE_VERTEXAI", "false").lower() == "true" if not vertexai: self.api_key = self.api_key or getenv("GOOGLE_API_KEY") if not self.api_key: log_error("GOOGLE_API_KEY not set. Please set the GOOGLE_API_KEY environment variable.") _client_params["api_key"] = self.api_key else: log_info("Using Vertex AI API for embeddings") _client_params["vertexai"] = True _client_params["project"] = self.project_id or getenv("GOOGLE_CLOUD_PROJECT") _client_params["location"] = self.location or getenv("GOOGLE_CLOUD_LOCATION") _client_params = {k: v for k, v in _client_params.items() if v is not None} if self.client_params: _client_params.update(self.client_params) self.gemini_client = genai.Client(**_client_params) return self.gemini_client @property def aclient(self) -> GeminiClient: """Returns the same client instance since Google GenAI Client supports both sync and async operations.""" return self.client def _response(self, text: str) -> EmbedContentResponse: # If a user provides a model id with the `models/` prefix, we need to remove it _id = self.id if _id.startswith("models/"): _id = _id.split("/")[-1] _request_params: Dict[str, Any] = {"contents": text, "model": _id, "config": {}} if self.dimensions: _request_params["config"]["output_dimensionality"] = self.dimensions if self.task_type: _request_params["config"]["task_type"] = self.task_type if self.title: _request_params["config"]["title"] = self.title if not _request_params["config"]: del _request_params["config"] if self.request_params: _request_params.update(self.request_params) return self.client.models.embed_content(**_request_params) def get_embedding(self, text: str) -> List[float]: response = self._response(text=text) try: if response.embeddings and len(response.embeddings) > 0: values = response.embeddings[0].values if values is not None: return values log_info("No embeddings found in response") return [] except Exception as e: log_error(f"Error extracting embeddings: {e}") return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: response = self._response(text=text) usage = None if response.metadata and hasattr(response.metadata, "billable_character_count"): usage = {"billable_character_count": response.metadata.billable_character_count} try: if response.embeddings and len(response.embeddings) > 0: values = response.embeddings[0].values if values is not None: return values, usage log_info("No embeddings found in response") return [], usage except Exception as e: log_error(f"Error extracting embeddings: {e}") return [], usage async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding using client.aio.""" # If a user provides a model id with the `models/` prefix, we need to remove it _id = self.id if _id.startswith("models/"): _id = _id.split("/")[-1] _request_params: Dict[str, Any] = {"contents": text, "model": _id, "config": {}} if self.dimensions: _request_params["config"]["output_dimensionality"] = self.dimensions if self.task_type: _request_params["config"]["task_type"] = self.task_type if self.title: _request_params["config"]["title"] = self.title if not _request_params["config"]: del _request_params["config"] if self.request_params: _request_params.update(self.request_params) try: response = await self.aclient.aio.models.embed_content(**_request_params) if response.embeddings and len(response.embeddings) > 0: values = response.embeddings[0].values if values is not None: return values log_info("No embeddings found in response") return [] except Exception as e: log_error(f"Error extracting embeddings: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict[str, Any]]]: """Async version of get_embedding_and_usage using client.aio.""" # If a user provides a model id with the `models/` prefix, we need to remove it _id = self.id if _id.startswith("models/"): _id = _id.split("/")[-1] _request_params: Dict[str, Any] = {"contents": text, "model": _id, "config": {}} if self.dimensions: _request_params["config"]["output_dimensionality"] = self.dimensions if self.task_type: _request_params["config"]["task_type"] = self.task_type if self.title: _request_params["config"]["title"] = self.title if not _request_params["config"]: del _request_params["config"] if self.request_params: _request_params.update(self.request_params) try: response = await self.aclient.aio.models.embed_content(**_request_params) usage = None if response.metadata and hasattr(response.metadata, "billable_character_count"): usage = {"billable_character_count": response.metadata.billable_character_count} if response.embeddings and len(response.embeddings) > 0: values = response.embeddings[0].values if values is not None: return values, usage log_info("No embeddings found in response") return [], usage except Exception as e: log_error(f"Error extracting embeddings: {e}") return [], usage async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict[str, Any]]]]: """ Get embeddings and usage for multiple texts in batches. Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings: List[List[float]] = [] all_usage: List[Optional[Dict[str, Any]]] = [] log_info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size}") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] # If a user provides a model id with the `models/` prefix, we need to remove it _id = self.id if _id.startswith("models/"): _id = _id.split("/")[-1] _request_params: Dict[str, Any] = {"contents": batch_texts, "model": _id, "config": {}} if self.dimensions: _request_params["config"]["output_dimensionality"] = self.dimensions if self.task_type: _request_params["config"]["task_type"] = self.task_type if self.title: _request_params["config"]["title"] = self.title if not _request_params["config"]: del _request_params["config"] if self.request_params: _request_params.update(self.request_params) try: response = await self.aclient.aio.models.embed_content(**_request_params) # Extract embeddings from batch response if response.embeddings: batch_embeddings = [] for embedding in response.embeddings: if embedding.values is not None: batch_embeddings.append(embedding.values) else: batch_embeddings.append([]) all_embeddings.extend(batch_embeddings) else: # If no embeddings, add empty lists for each text in batch all_embeddings.extend([[] for _ in batch_texts]) # Extract usage information usage_dict = None if response.metadata and hasattr(response.metadata, "billable_character_count"): usage_dict = {"billable_character_count": response.metadata.billable_character_count} # Add same usage info for each embedding in the batch all_usage.extend([usage_dict] * len(batch_texts)) except Exception as e: log_warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: text_embedding: List[float] text_usage: Optional[Dict[str, Any]] text_embedding, text_usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(text_embedding) all_usage.append(text_usage) except Exception as e2: log_warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/google.py", "license": "Apache License 2.0", "lines": 218, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/huggingface.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_error, log_warning try: from huggingface_hub import AsyncInferenceClient, InferenceClient except ImportError: log_error("`huggingface-hub` not installed, please run `pip install huggingface-hub`") raise @dataclass class HuggingfaceCustomEmbedder(Embedder): """Huggingface Custom Embedder""" id: str = "intfloat/multilingual-e5-large" api_key: Optional[str] = getenv("HUGGINGFACE_API_KEY") client_params: Optional[Dict[str, Any]] = None huggingface_client: Optional[InferenceClient] = None async_client: Optional[AsyncInferenceClient] = None def __post_init__(self): if self.enable_batch: log_warning("HuggingfaceEmbedder does not support batch embeddings, setting enable_batch to False") self.enable_batch = False @property def client(self) -> InferenceClient: if self.huggingface_client: return self.huggingface_client _client_params: Dict[str, Any] = {} if self.api_key: _client_params["api_key"] = self.api_key if self.client_params: _client_params.update(self.client_params) self.huggingface_client = InferenceClient(**_client_params) return self.huggingface_client @property def aclient(self) -> AsyncInferenceClient: if self.async_client: return self.async_client _client_params: Dict[str, Any] = {} if self.api_key: _client_params["api_key"] = self.api_key if self.client_params: _client_params.update(self.client_params) self.async_client = AsyncInferenceClient(**_client_params) return self.async_client def _response(self, text: str): return self.client.feature_extraction(text=text, model=self.id) def get_embedding(self, text: str) -> List[float]: response = self._response(text=text) try: # If already a list, return directly if isinstance(response, list): return response # If numpy array, convert to list elif hasattr(response, "tolist"): return response.tolist() else: return list(response) except Exception as e: log_warning(f"Failed to process embeddings: {e}") return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: return self.get_embedding(text=text), None async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding using AsyncInferenceClient.""" response = await self.aclient.feature_extraction(text=text, model=self.id) try: # If already a list, return directly if isinstance(response, list): return response # If numpy array, convert to list elif hasattr(response, "tolist"): return response.tolist() else: return list(response) except Exception as e: log_warning(f"Failed to process embeddings: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version of get_embedding_and_usage.""" embedding = await self.async_get_embedding(text=text) return embedding, None
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/huggingface.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/jina.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Tuple from typing_extensions import Literal from agno.knowledge.embedder.base import Embedder from agno.utils.log import logger try: import requests except ImportError: raise ImportError("`requests` not installed, use pip install requests") try: import aiohttp except ImportError: raise ImportError("`aiohttp` not installed, use pip install aiohttp") @dataclass class JinaEmbedder(Embedder): id: str = "jina-embeddings-v3" dimensions: int = 1024 embedding_type: Literal["float", "base64", "int8"] = "float" late_chunking: bool = False user: Optional[str] = None api_key: Optional[str] = getenv("JINA_API_KEY") base_url: str = "https://api.jina.ai/v1/embeddings" headers: Optional[Dict[str, str]] = None request_params: Optional[Dict[str, Any]] = None timeout: Optional[float] = None def _get_headers(self) -> Dict[str, str]: if not self.api_key: raise ValueError( "API key is required for Jina embedder. Set JINA_API_KEY environment variable or pass api_key parameter." ) headers = {"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"} if self.headers: headers.update(self.headers) return headers def _response(self, text: str) -> Dict[str, Any]: data = { "model": self.id, "late_chunking": self.late_chunking, "dimensions": self.dimensions, "embedding_type": self.embedding_type, "input": [text], # Jina API expects a list } if self.user is not None: data["user"] = self.user if self.request_params: data.update(self.request_params) response = requests.post(self.base_url, headers=self._get_headers(), json=data, timeout=self.timeout) response.raise_for_status() return response.json() def get_embedding(self, text: str) -> List[float]: try: result = self._response(text) return result["data"][0]["embedding"] except Exception as e: logger.warning(f"Failed to get embedding: {e}") return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: try: result = self._response(text) embedding = result["data"][0]["embedding"] usage = result.get("usage") return embedding, usage except Exception as e: logger.warning(f"Failed to get embedding and usage: {e}") return [], None async def _async_response(self, text: str) -> Dict[str, Any]: """Async version of _response using aiohttp.""" data = { "model": self.id, "late_chunking": self.late_chunking, "dimensions": self.dimensions, "embedding_type": self.embedding_type, "input": [text], # Jina API expects a list } if self.user is not None: data["user"] = self.user if self.request_params: data.update(self.request_params) timeout = aiohttp.ClientTimeout(total=self.timeout) if self.timeout else None async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(self.base_url, headers=self._get_headers(), json=data) as response: response.raise_for_status() return await response.json() async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding.""" try: result = await self._async_response(text) return result["data"][0]["embedding"] except Exception as e: logger.warning(f"Failed to get embedding: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version of get_embedding_and_usage.""" try: result = await self._async_response(text) embedding = result["data"][0]["embedding"] usage = result.get("usage") return embedding, usage except Exception as e: logger.warning(f"Failed to get embedding and usage: {e}") return [], None async def _async_batch_response(self, texts: List[str]) -> Dict[str, Any]: """Async batch version of _response using aiohttp.""" data = { "model": self.id, "late_chunking": self.late_chunking, "dimensions": self.dimensions, "embedding_type": self.embedding_type, "input": texts, # Jina API expects a list of texts for batch processing } if self.user is not None: data["user"] = self.user if self.request_params: data.update(self.request_params) timeout = aiohttp.ClientTimeout(total=self.timeout) if self.timeout else None async with aiohttp.ClientSession(timeout=timeout) as session: async with session.post(self.base_url, headers=self._get_headers(), json=data) as response: response.raise_for_status() return await response.json() async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """ Get embeddings and usage for multiple texts in batches. Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings = [] all_usage = [] logger.info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size}") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] try: result = await self._async_batch_response(batch_texts) batch_embeddings = [data["embedding"] for data in result["data"]] all_embeddings.extend(batch_embeddings) # For each embedding in the batch, add the same usage information usage_dict = result.get("usage") all_usage.extend([usage_dict] * len(batch_embeddings)) except Exception as e: logger.warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: logger.warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/jina.py", "license": "Apache License 2.0", "lines": 155, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/langdb.py
from dataclasses import dataclass from os import getenv from typing import Optional from agno.knowledge.embedder.openai import OpenAIEmbedder @dataclass class LangDBEmbedder(OpenAIEmbedder): id: str = "text-embedding-ada-002" dimensions: int = 1536 api_key: Optional[str] = getenv("LANGDB_API_KEY") project_id: Optional[str] = getenv("LANGDB_PROJECT_ID") base_url: Optional[str] = None def __post_init__(self): """Set the base_url based on project_id if not provided.""" if not self.project_id: raise ValueError("LANGDB_PROJECT_ID not set in the environment") if not self.base_url: self.base_url = f"https://api.us-east-1.langdb.ai/{self.project_id}/v1"
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/langdb.py", "license": "Apache License 2.0", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/embedder/mistral.py
from dataclasses import dataclass from os import getenv from typing import Any, Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_error, log_info, log_warning try: from mistralai import Mistral # type: ignore from mistralai.models.embeddingresponse import EmbeddingResponse # type: ignore except ImportError: log_error("`mistralai` not installed") raise @dataclass class MistralEmbedder(Embedder): id: str = "mistral-embed" dimensions: int = 1024 # -*- Request parameters request_params: Optional[Dict[str, Any]] = None # -*- Client parameters api_key: Optional[str] = getenv("MISTRAL_API_KEY") endpoint: Optional[str] = None max_retries: Optional[int] = None timeout: Optional[int] = None client_params: Optional[Dict[str, Any]] = None # -*- Provide the Mistral Client manually mistral_client: Optional[Mistral] = None @property def client(self) -> Mistral: if self.mistral_client: return self.mistral_client _client_params: Dict[str, Any] = { "api_key": self.api_key, "endpoint": self.endpoint, "max_retries": self.max_retries, "timeout_ms": self.timeout * 1000 if self.timeout else None, } _client_params = {k: v for k, v in _client_params.items() if v is not None} if self.client_params: _client_params.update(self.client_params) self.mistral_client = Mistral(**_client_params) return self.mistral_client def _response(self, text: str) -> EmbeddingResponse: _request_params: Dict[str, Any] = { "inputs": [text], # Mistral API expects a list "model": self.id, } if self.request_params: _request_params.update(self.request_params) response = self.client.embeddings.create(**_request_params) if response is None: raise ValueError("Failed to get embedding response") return response def get_embedding(self, text: str) -> List[float]: try: response: EmbeddingResponse = self._response(text=text) if response.data and response.data[0].embedding: return response.data[0].embedding return [] except Exception as e: log_warning(f"Error getting embedding: {e}") return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Dict[str, Any]]: try: response: EmbeddingResponse = self._response(text=text) embedding: List[float] = ( response.data[0].embedding if (response.data and response.data[0].embedding) else [] ) usage: Dict[str, Any] = response.usage.model_dump() if response.usage else {} return embedding, usage except Exception as e: log_warning(f"Error getting embedding and usage: {e}") return [], {} async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding.""" try: # Check if the client has an async version of embeddings.create if hasattr(self.client.embeddings, "create_async"): response: EmbeddingResponse = await self.client.embeddings.create_async( inputs=[text], model=self.id, **self.request_params if self.request_params else {} ) else: # Fallback to running sync method in thread executor import asyncio loop = asyncio.get_running_loop() response: EmbeddingResponse = await loop.run_in_executor( # type: ignore None, lambda: self.client.embeddings.create( inputs=[text], model=self.id, **self.request_params if self.request_params else {} ), ) if response.data and response.data[0].embedding: return response.data[0].embedding return [] except Exception as e: log_warning(f"Error getting embedding: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Dict[str, Any]]: """Async version of get_embedding_and_usage.""" try: # Check if the client has an async version of embeddings.create if hasattr(self.client.embeddings, "create_async"): response: EmbeddingResponse = await self.client.embeddings.create_async( inputs=[text], model=self.id, **self.request_params if self.request_params else {} ) else: # Fallback to running sync method in thread executor import asyncio loop = asyncio.get_running_loop() response: EmbeddingResponse = await loop.run_in_executor( # type: ignore None, lambda: self.client.embeddings.create( inputs=[text], model=self.id, **self.request_params if self.request_params else {} ), ) embedding: List[float] = ( response.data[0].embedding if (response.data and response.data[0].embedding) else [] ) usage: Dict[str, Any] = response.usage.model_dump() if response.usage else {} return embedding, usage except Exception as e: log_warning(f"Error getting embedding and usage: {e}") return [], {} async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict[str, Any]]]]: """ Get embeddings and usage for multiple texts in batches. Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings = [] all_usage = [] log_info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size}") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] _request_params: Dict[str, Any] = { "inputs": batch_texts, # Mistral API expects a list for batch processing "model": self.id, } if self.request_params: _request_params.update(self.request_params) try: # Check if the client has an async version of embeddings.create if hasattr(self.client.embeddings, "create_async"): response: EmbeddingResponse = await self.client.embeddings.create_async(**_request_params) else: # Fallback to running sync method in thread executor import asyncio loop = asyncio.get_running_loop() response: EmbeddingResponse = await loop.run_in_executor( # type: ignore None, lambda: self.client.embeddings.create(**_request_params) ) # Extract embeddings from batch response if response.data: batch_embeddings = [data.embedding for data in response.data if data.embedding] all_embeddings.extend(batch_embeddings) else: # If no embeddings, add empty lists for each text in batch all_embeddings.extend([[] for _ in batch_texts]) # Extract usage information usage_dict = response.usage.model_dump() if response.usage else None # Add same usage info for each embedding in the batch all_usage.extend([usage_dict] * len(batch_texts)) except Exception as e: log_warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: log_warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/mistral.py", "license": "Apache License 2.0", "lines": 177, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/ollama.py
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_error, logger try: import importlib.metadata as metadata from ollama import AsyncClient as AsyncOllamaClient from ollama import Client as OllamaClient from packaging import version # Get installed Ollama version ollama_version = metadata.version("ollama") # Check version compatibility (requires v0.3.x or higher) parsed_version = version.parse(ollama_version) if parsed_version.major == 0 and parsed_version.minor < 3: import warnings warnings.warn("Only Ollama v0.3.x and above are supported", UserWarning) raise RuntimeError("Incompatible Ollama version detected") except ImportError as e: # Handle different import error scenarios if "ollama" in str(e): raise ImportError("Ollama not installed. Install with `pip install ollama`") from e else: raise ImportError("Missing dependencies. Install with `pip install packaging importlib-metadata`") from e except Exception as e: # Catch-all for unexpected errors log_error(f"An unexpected error occurred: {e}") @dataclass class OllamaEmbedder(Embedder): id: str = "openhermes" dimensions: int = 4096 host: Optional[str] = None timeout: Optional[Any] = None options: Optional[Any] = None client_kwargs: Optional[Dict[str, Any]] = None ollama_client: Optional[OllamaClient] = None async_client: Optional[AsyncOllamaClient] = None def __post_init__(self): if self.enable_batch: logger.warning("OllamaEmbedder does not support batch embeddings, setting enable_batch to False") self.enable_batch = False @property def client(self) -> OllamaClient: if self.ollama_client: return self.ollama_client _ollama_params: Dict[str, Any] = { "host": self.host, "timeout": self.timeout, } _ollama_params = {k: v for k, v in _ollama_params.items() if v is not None} if self.client_kwargs: _ollama_params.update(self.client_kwargs) self.ollama_client = OllamaClient(**_ollama_params) return self.ollama_client @property def aclient(self) -> AsyncOllamaClient: if self.async_client: return self.async_client _ollama_params: Dict[str, Any] = { "host": self.host, "timeout": self.timeout, } _ollama_params = {k: v for k, v in _ollama_params.items() if v is not None} if self.client_kwargs: _ollama_params.update(self.client_kwargs) self.async_client = AsyncOllamaClient(**_ollama_params) return self.async_client def _response(self, text: str) -> Dict[str, Any]: kwargs: Dict[str, Any] = {} if self.options is not None: kwargs["options"] = self.options # Add dimensions parameter for models that support it if self.dimensions is not None: kwargs["dimensions"] = self.dimensions response = self.client.embed(input=text, model=self.id, **kwargs) if response and "embeddings" in response: embeddings = response["embeddings"] if isinstance(embeddings, list) and len(embeddings) > 0 and isinstance(embeddings[0], list): return {"embeddings": embeddings[0]} # Use the first element elif isinstance(embeddings, list) and all(isinstance(x, (int, float)) for x in embeddings): return {"embeddings": embeddings} # Return as-is if already flat return {"embeddings": []} # Return an empty list if no valid embedding is found def get_embedding(self, text: str) -> List[float]: try: response = self._response(text=text) embedding = response.get("embeddings", []) if len(embedding) != self.dimensions: logger.warning(f"Expected embedding dimension {self.dimensions}, but got {len(embedding)}") return [] return embedding except Exception as e: logger.warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: embedding = self.get_embedding(text=text) usage = None return embedding, usage async def _async_response(self, text: str) -> Dict[str, Any]: """Async version of _response using AsyncOllamaClient.""" kwargs: Dict[str, Any] = {} if self.options is not None: kwargs["options"] = self.options # Add dimensions parameter for models that support it if self.dimensions is not None: kwargs["dimensions"] = self.dimensions response = await self.aclient.embed(input=text, model=self.id, **kwargs) if response and "embeddings" in response: embeddings = response["embeddings"] if isinstance(embeddings, list) and len(embeddings) > 0 and isinstance(embeddings[0], list): return {"embeddings": embeddings[0]} # Use the first element elif isinstance(embeddings, list) and all(isinstance(x, (int, float)) for x in embeddings): return {"embeddings": embeddings} # Return as-is if already flat return {"embeddings": []} # Return an empty list if no valid embedding is found async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding.""" try: response = await self._async_response(text=text) embedding = response.get("embeddings", []) if len(embedding) != self.dimensions: logger.warning(f"Expected embedding dimension {self.dimensions}, but got {len(embedding)}") return [] return embedding except Exception as e: logger.warning(f"Error getting embedding: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version of get_embedding_and_usage.""" embedding = await self.async_get_embedding(text=text) usage = None return embedding, usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/ollama.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/openai.py
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple from typing_extensions import Literal from agno.knowledge.embedder.base import Embedder from agno.utils.log import log_info, log_warning try: from openai import AsyncOpenAI from openai import OpenAI as OpenAIClient from openai.types.create_embedding_response import CreateEmbeddingResponse except ImportError: raise ImportError("`openai` not installed") @dataclass class OpenAIEmbedder(Embedder): id: str = "text-embedding-3-small" dimensions: Optional[int] = None encoding_format: Literal["float", "base64"] = "float" user: Optional[str] = None api_key: Optional[str] = None organization: Optional[str] = None base_url: Optional[str] = None request_params: Optional[Dict[str, Any]] = None client_params: Optional[Dict[str, Any]] = None openai_client: Optional[OpenAIClient] = None async_client: Optional[AsyncOpenAI] = None def __post_init__(self): if self.dimensions is None: self.dimensions = 3072 if self.id == "text-embedding-3-large" else 1536 @property def client(self) -> OpenAIClient: if self.openai_client: return self.openai_client _client_params: Dict[str, Any] = { "api_key": self.api_key, "organization": self.organization, "base_url": self.base_url, } _client_params = {k: v for k, v in _client_params.items() if v is not None} if self.client_params: _client_params.update(self.client_params) self.openai_client = OpenAIClient(**_client_params) return self.openai_client @property def aclient(self) -> AsyncOpenAI: if self.async_client: return self.async_client params = { "api_key": self.api_key, "organization": self.organization, "base_url": self.base_url, } filtered_params: Dict[str, Any] = {k: v for k, v in params.items() if v is not None} if self.client_params: filtered_params.update(self.client_params) self.async_client = AsyncOpenAI(**filtered_params) return self.async_client def response(self, text: str) -> CreateEmbeddingResponse: _request_params: Dict[str, Any] = { "input": text, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: _request_params["user"] = self.user # Pass dimensions for text-embedding-3 models or when using custom base_url (third-party APIs) if self.id.startswith("text-embedding-3") or self.base_url is not None: _request_params["dimensions"] = self.dimensions if self.request_params: _request_params.update(self.request_params) return self.client.embeddings.create(**_request_params) def get_embedding(self, text: str) -> List[float]: try: response: CreateEmbeddingResponse = self.response(text=text) return response.data[0].embedding except Exception as e: log_warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: try: response: CreateEmbeddingResponse = self.response(text=text) embedding = response.data[0].embedding usage = response.usage if usage: return embedding, usage.model_dump() return embedding, None except Exception as e: log_warning(e) return [], None async def async_get_embedding(self, text: str) -> List[float]: req: Dict[str, Any] = { "input": text, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: req["user"] = self.user # Pass dimensions for text-embedding-3 models or when using custom base_url (third-party APIs) if self.id.startswith("text-embedding-3") or self.base_url is not None: req["dimensions"] = self.dimensions if self.request_params: req.update(self.request_params) try: response: CreateEmbeddingResponse = await self.aclient.embeddings.create(**req) return response.data[0].embedding except Exception as e: log_warning(e) return [] async def async_get_embedding_and_usage(self, text: str): req: Dict[str, Any] = { "input": text, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: req["user"] = self.user # Pass dimensions for text-embedding-3 models or when using custom base_url (third-party APIs) if self.id.startswith("text-embedding-3") or self.base_url is not None: req["dimensions"] = self.dimensions if self.request_params: req.update(self.request_params) try: response = await self.aclient.embeddings.create(**req) embedding = response.data[0].embedding usage = response.usage return embedding, usage.model_dump() if usage else None except Exception as e: log_warning(f"Error getting embedding: {e}") return [], None async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """ Get embeddings and usage for multiple texts in batches (async version). Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings = [] all_usage = [] log_info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size} (async)") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] req: Dict[str, Any] = { "input": batch_texts, "model": self.id, "encoding_format": self.encoding_format, } if self.user is not None: req["user"] = self.user # Pass dimensions for text-embedding-3 models or when using custom base_url (third-party APIs) if self.id.startswith("text-embedding-3") or self.base_url is not None: req["dimensions"] = self.dimensions if self.request_params: req.update(self.request_params) try: response: CreateEmbeddingResponse = await self.aclient.embeddings.create(**req) batch_embeddings = [data.embedding for data in response.data] all_embeddings.extend(batch_embeddings) # For each embedding in the batch, add the same usage information usage_dict = response.usage.model_dump() if response.usage else None all_usage.extend([usage_dict] * len(batch_embeddings)) except Exception as e: log_warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: log_warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/openai.py", "license": "Apache License 2.0", "lines": 174, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/sentence_transformer.py
from dataclasses import dataclass from typing import Dict, List, Optional, Tuple, Union from agno.knowledge.embedder.base import Embedder from agno.utils.log import logger try: from sentence_transformers import SentenceTransformer except ImportError: raise ImportError("`sentence-transformers` not installed, please run `pip install sentence-transformers`") try: import numpy as np except ImportError: raise ImportError("numpy not installed, use `pip install numpy`") @dataclass class SentenceTransformerEmbedder(Embedder): id: str = "sentence-transformers/all-MiniLM-L6-v2" dimensions: int = 384 sentence_transformer_client: Optional[SentenceTransformer] = None prompt: Optional[str] = None normalize_embeddings: bool = False def __post_init__(self): # Initialize the SentenceTransformer model eagerly to avoid race conditions in async contexts if self.sentence_transformer_client is None: self.sentence_transformer_client = SentenceTransformer(model_name_or_path=self.id) def get_embedding(self, text: Union[str, List[str]]) -> List[float]: if self.sentence_transformer_client is None: raise RuntimeError("SentenceTransformer model not initialized") model = self.sentence_transformer_client embedding = model.encode(text, prompt=self.prompt, normalize_embeddings=self.normalize_embeddings) try: if isinstance(embedding, np.ndarray): return embedding.tolist() return embedding # type: ignore except Exception as e: logger.warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: return self.get_embedding(text=text), None async def async_get_embedding(self, text: Union[str, List[str]]) -> List[float]: """Async version using thread executor for CPU-bound operations.""" import asyncio loop = asyncio.get_event_loop() # Run the CPU-bound operation in a thread executor return await loop.run_in_executor(None, self.get_embedding, text) async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version using thread executor for CPU-bound operations.""" import asyncio loop = asyncio.get_event_loop() return await loop.run_in_executor(None, self.get_embedding_and_usage, text)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/sentence_transformer.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/embedder/voyageai.py
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple from agno.knowledge.embedder.base import Embedder from agno.utils.log import logger try: from voyageai import AsyncClient as AsyncVoyageClient from voyageai import Client as VoyageClient from voyageai.object import EmbeddingsObject except ImportError: raise ImportError("`voyageai` not installed. Please install using `pip install voyageai`") @dataclass class VoyageAIEmbedder(Embedder): id: str = "voyage-2" dimensions: int = 1024 request_params: Optional[Dict[str, Any]] = None api_key: Optional[str] = None base_url: str = "https://api.voyageai.com/v1/embeddings" max_retries: Optional[int] = None timeout: Optional[float] = None client_params: Optional[Dict[str, Any]] = None voyage_client: Optional[VoyageClient] = None async_client: Optional[AsyncVoyageClient] = None @property def client(self) -> VoyageClient: if self.voyage_client: return self.voyage_client _client_params: Dict[str, Any] = {} if self.api_key is not None: _client_params["api_key"] = self.api_key if self.max_retries is not None: _client_params["max_retries"] = self.max_retries if self.timeout is not None: _client_params["timeout"] = self.timeout if self.client_params: _client_params.update(self.client_params) self.voyage_client = VoyageClient(**_client_params) return self.voyage_client @property def aclient(self) -> AsyncVoyageClient: if self.async_client: return self.async_client _client_params: Dict[str, Any] = {} if self.api_key is not None: _client_params["api_key"] = self.api_key if self.max_retries is not None: _client_params["max_retries"] = self.max_retries if self.timeout is not None: _client_params["timeout"] = self.timeout if self.client_params: _client_params.update(self.client_params) self.async_client = AsyncVoyageClient(**_client_params) return self.async_client def _response(self, text: str) -> EmbeddingsObject: _request_params: Dict[str, Any] = { "texts": [text], "model": self.id, } if self.request_params: _request_params.update(self.request_params) return self.client.embed(**_request_params) def get_embedding(self, text: str) -> List[float]: response: EmbeddingsObject = self._response(text=text) try: embedding = response.embeddings[0] return [float(x) for x in embedding] # Ensure all values are float except Exception as e: logger.warning(e) return [] def get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: response: EmbeddingsObject = self._response(text=text) embedding = response.embeddings[0] usage = {"total_tokens": response.total_tokens} return [float(x) for x in embedding], usage async def _async_response(self, text: str) -> EmbeddingsObject: """Async version of _response using AsyncVoyageClient.""" _request_params: Dict[str, Any] = { "texts": [text], "model": self.id, } if self.request_params: _request_params.update(self.request_params) return await self.aclient.embed(**_request_params) async def async_get_embedding(self, text: str) -> List[float]: """Async version of get_embedding.""" try: response: EmbeddingsObject = await self._async_response(text=text) embedding = response.embeddings[0] return [float(x) for x in embedding] # Ensure all values are float except Exception as e: logger.warning(f"Error getting embedding: {e}") return [] async def async_get_embedding_and_usage(self, text: str) -> Tuple[List[float], Optional[Dict]]: """Async version of get_embedding_and_usage.""" try: response: EmbeddingsObject = await self._async_response(text=text) embedding = response.embeddings[0] usage = {"total_tokens": response.total_tokens} return [float(x) for x in embedding], usage except Exception as e: logger.warning(f"Error getting embedding and usage: {e}") return [], None async def async_get_embeddings_batch_and_usage( self, texts: List[str] ) -> Tuple[List[List[float]], List[Optional[Dict]]]: """ Get embeddings and usage for multiple texts in batches. Args: texts: List of text strings to embed Returns: Tuple of (List of embedding vectors, List of usage dictionaries) """ all_embeddings: List[List[float]] = [] all_usage: List[Optional[Dict]] = [] logger.info(f"Getting embeddings and usage for {len(texts)} texts in batches of {self.batch_size}") for i in range(0, len(texts), self.batch_size): batch_texts = texts[i : i + self.batch_size] req: Dict[str, Any] = { "texts": batch_texts, "model": self.id, } if self.request_params: req.update(self.request_params) try: response: EmbeddingsObject = await self.aclient.embed(**req) batch_embeddings = [[float(x) for x in emb] for emb in response.embeddings] all_embeddings.extend(batch_embeddings) # For each embedding in the batch, add the same usage information usage_dict = {"total_tokens": response.total_tokens} all_usage.extend([usage_dict] * len(batch_embeddings)) except Exception as e: logger.warning(f"Error in async batch embedding: {e}") # Fallback to individual calls for this batch for text in batch_texts: try: embedding, usage = await self.async_get_embedding_and_usage(text) all_embeddings.append(embedding) all_usage.append(usage) except Exception as e2: logger.warning(f"Error in individual async embedding fallback: {e2}") all_embeddings.append([]) all_usage.append(None) return all_embeddings, all_usage
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/embedder/voyageai.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/knowledge.py
import asyncio import hashlib import io import time from dataclasses import dataclass from enum import Enum from io import BytesIO from os.path import basename from pathlib import Path from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast, overload from httpx import AsyncClient from agno.db.base import AsyncBaseDb, BaseDb from agno.db.schemas.knowledge import KnowledgeRow from agno.filters import EQ, FilterExpr from agno.knowledge.content import Content, ContentAuth, ContentStatus, FileData from agno.knowledge.document import Document from agno.knowledge.reader import Reader, ReaderFactory from agno.knowledge.remote_content.base import BaseStorageConfig from agno.knowledge.remote_content.remote_content import ( RemoteContent, ) from agno.knowledge.remote_knowledge import RemoteKnowledge from agno.knowledge.utils import merge_user_metadata, set_agno_metadata, strip_agno_metadata from agno.utils.http import async_fetch_with_retry from agno.utils.log import log_debug, log_error, log_info, log_warning from agno.utils.string import generate_id ContentDict = Dict[str, Union[str, Dict[str, str]]] class KnowledgeContentOrigin(Enum): PATH = "path" URL = "url" TOPIC = "topic" CONTENT = "content" @dataclass class Knowledge(RemoteKnowledge): """Knowledge class""" name: Optional[str] = None description: Optional[str] = None vector_db: Optional[Any] = None contents_db: Optional[Union[BaseDb, AsyncBaseDb]] = None max_results: int = 10 readers: Optional[Dict[str, Reader]] = None content_sources: Optional[List[BaseStorageConfig]] = None # When True, adds linked_to metadata during insert and filters by it during search. # This enables isolation when multiple Knowledge instances share the same vector database. # Requires re-indexing existing data to add linked_to metadata. # Default is False for backwards compatibility with existing data. isolate_vector_search: bool = False def __post_init__(self): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db and not self.vector_db.exists(): self.vector_db.create() self.construct_readers() # ========================================== # PUBLIC API - INSERT METHODS # ========================================== # --- Insert (Single Content) --- @overload def insert( self, *, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, reader: Optional[Reader] = None, auth: Optional[ContentAuth] = None, ) -> None: ... @overload def insert(self, *args, **kwargs) -> None: ... def insert( self, name: Optional[str] = None, description: Optional[str] = None, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, topics: Optional[List[str]] = None, remote_content: Optional[RemoteContent] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, auth: Optional[ContentAuth] = None, ) -> None: """ Synchronously insert content into the knowledge base. Args: name: Optional name for the content description: Optional description for the content path: Optional file path to load content from url: Optional URL to load content from text_content: Optional text content to insert directly metadata: Optional metadata dictionary topics: Optional list of topics remote_content: Optional cloud storage configuration reader: Optional custom reader for processing the content include: Optional list of file patterns to include exclude: Optional list of file patterns to exclude upsert: Whether to update existing content if it already exists (only used when skip_if_exists=False) skip_if_exists: Whether to skip inserting content if it already exists (default: False) """ # Validation: At least one of the parameters must be provided if all(argument is None for argument in [path, url, text_content, topics, remote_content]): log_warning( "At least one of 'path', 'url', 'text_content', 'topics', or 'remote_content' must be provided." ) return # Strip reserved _agno key from user-provided metadata safe_metadata = strip_agno_metadata(metadata) content = None file_data = None if text_content: file_data = FileData(content=text_content, type="Text") content = Content( name=name, description=description, path=path, url=url, file_data=file_data if file_data else None, metadata=safe_metadata, topics=topics, remote_content=remote_content, reader=reader, auth=auth, ) content.content_hash = self._build_content_hash(content) content.id = generate_id(content.content_hash) self._load_content(content, upsert, skip_if_exists, include, exclude) @overload async def ainsert( self, *, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, reader: Optional[Reader] = None, auth: Optional[ContentAuth] = None, ) -> None: ... @overload async def ainsert(self, *args, **kwargs) -> None: ... async def ainsert( self, name: Optional[str] = None, description: Optional[str] = None, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, topics: Optional[List[str]] = None, remote_content: Optional[RemoteContent] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, auth: Optional[ContentAuth] = None, ) -> None: # Validation: At least one of the parameters must be provided if all(argument is None for argument in [path, url, text_content, topics, remote_content]): log_warning( "At least one of 'path', 'url', 'text_content', 'topics', or 'remote_content' must be provided." ) return # Strip reserved _agno key from user-provided metadata safe_metadata = strip_agno_metadata(metadata) content = None file_data = None if text_content: file_data = FileData(content=text_content, type="Text") content = Content( name=name, description=description, path=path, url=url, file_data=file_data if file_data else None, metadata=safe_metadata, topics=topics, remote_content=remote_content, reader=reader, auth=auth, ) content.content_hash = self._build_content_hash(content) content.id = generate_id(content.content_hash) await self._aload_content(content, upsert, skip_if_exists, include, exclude) # --- Insert Many --- @overload async def ainsert_many(self, contents: List[ContentDict]) -> None: ... @overload async def ainsert_many( self, *, paths: Optional[List[str]] = None, urls: Optional[List[str]] = None, metadata: Optional[Dict[str, str]] = None, topics: Optional[List[str]] = None, text_contents: Optional[List[str]] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, remote_content: Optional[RemoteContent] = None, ) -> None: ... async def ainsert_many(self, *args, **kwargs) -> None: if args and isinstance(args[0], list): arguments = args[0] upsert = kwargs.get("upsert", True) skip_if_exists = kwargs.get("skip_if_exists", False) for argument in arguments: await self.ainsert( name=argument.get("name"), description=argument.get("description"), path=argument.get("path"), url=argument.get("url"), metadata=argument.get("metadata"), topics=argument.get("topics"), text_content=argument.get("text_content"), reader=argument.get("reader"), include=argument.get("include"), exclude=argument.get("exclude"), upsert=argument.get("upsert", upsert), skip_if_exists=argument.get("skip_if_exists", skip_if_exists), remote_content=argument.get("remote_content", None), auth=argument.get("auth"), ) elif kwargs: name = kwargs.get("name", []) metadata = kwargs.get("metadata", {}) description = kwargs.get("description", []) topics = kwargs.get("topics", []) reader = kwargs.get("reader", None) paths = kwargs.get("paths", []) urls = kwargs.get("urls", []) text_contents = kwargs.get("text_contents", []) include = kwargs.get("include") exclude = kwargs.get("exclude") upsert = kwargs.get("upsert", True) skip_if_exists = kwargs.get("skip_if_exists", False) remote_content = kwargs.get("remote_content", None) auth = kwargs.get("auth") for path in paths: await self.ainsert( name=name, description=description, path=path, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) for url in urls: await self.ainsert( name=name, description=description, url=url, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) for i, text_content in enumerate(text_contents): content_name = f"{name}_{i}" if name else f"text_content_{i}" log_debug(f"Adding text content: {content_name}") await self.ainsert( name=content_name, description=description, text_content=text_content, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) if topics: await self.ainsert( name=name, description=description, topics=topics, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) if remote_content: await self.ainsert( name=name, metadata=metadata, description=description, remote_content=remote_content, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) else: raise ValueError("Invalid usage of insert_many.") @overload def insert_many(self, contents: List[ContentDict]) -> None: ... @overload def insert_many( self, *, paths: Optional[List[str]] = None, urls: Optional[List[str]] = None, metadata: Optional[Dict[str, str]] = None, topics: Optional[List[str]] = None, text_contents: Optional[List[str]] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, remote_content: Optional[RemoteContent] = None, ) -> None: ... def insert_many(self, *args, **kwargs) -> None: """ Synchronously insert multiple content items into the knowledge base. Supports two usage patterns: 1. Pass a list of content dictionaries as first argument 2. Pass keyword arguments with paths, urls, metadata, etc. Args: contents: List of content dictionaries (when used as first overload) paths: Optional list of file paths to load content from urls: Optional list of URLs to load content from metadata: Optional metadata dictionary to apply to all content topics: Optional list of topics to insert text_contents: Optional list of text content strings to insert reader: Optional reader to use for processing content include: Optional list of file patterns to include exclude: Optional list of file patterns to exclude upsert: Whether to update existing content if it already exists (only used when skip_if_exists=False) skip_if_exists: Whether to skip inserting content if it already exists (default: True) remote_content: Optional remote content (S3, GCS, etc.) to insert """ if args and isinstance(args[0], list): arguments = args[0] upsert = kwargs.get("upsert", True) skip_if_exists = kwargs.get("skip_if_exists", False) for argument in arguments: self.insert( name=argument.get("name"), description=argument.get("description"), path=argument.get("path"), url=argument.get("url"), metadata=argument.get("metadata"), topics=argument.get("topics"), text_content=argument.get("text_content"), reader=argument.get("reader"), include=argument.get("include"), exclude=argument.get("exclude"), upsert=argument.get("upsert", upsert), skip_if_exists=argument.get("skip_if_exists", skip_if_exists), remote_content=argument.get("remote_content", None), auth=argument.get("auth"), ) elif kwargs: name = kwargs.get("name", []) metadata = kwargs.get("metadata", {}) description = kwargs.get("description", []) topics = kwargs.get("topics", []) reader = kwargs.get("reader", None) paths = kwargs.get("paths", []) urls = kwargs.get("urls", []) text_contents = kwargs.get("text_contents", []) include = kwargs.get("include") exclude = kwargs.get("exclude") upsert = kwargs.get("upsert", True) skip_if_exists = kwargs.get("skip_if_exists", False) remote_content = kwargs.get("remote_content", None) auth = kwargs.get("auth") for path in paths: self.insert( name=name, description=description, path=path, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) for url in urls: self.insert( name=name, description=description, url=url, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) for i, text_content in enumerate(text_contents): content_name = f"{name}_{i}" if name else f"text_content_{i}" log_debug(f"Adding text content: {content_name}") self.insert( name=content_name, description=description, text_content=text_content, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) if topics: self.insert( name=name, description=description, topics=topics, metadata=metadata, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) if remote_content: self.insert( name=name, metadata=metadata, description=description, remote_content=remote_content, upsert=upsert, skip_if_exists=skip_if_exists, reader=reader, auth=auth, ) else: raise ValueError("Invalid usage of insert_many.") # ========================================== # PUBLIC API - SEARCH METHODS # ========================================== def search( self, query: str, max_results: Optional[int] = None, filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, search_type: Optional[str] = None, ) -> List[Document]: """Returns relevant documents matching a query""" from agno.vectordb import VectorDb from agno.vectordb.search import SearchType self.vector_db = cast(VectorDb, self.vector_db) if ( hasattr(self.vector_db, "search_type") and isinstance(self.vector_db.search_type, SearchType) and search_type ): self.vector_db.search_type = SearchType(search_type) try: if self.vector_db is None: log_warning("No vector db provided") return [] # Inject linked_to filter when isolate_vector_search is enabled and knowledge has a name search_filters = filters if self.isolate_vector_search and self.name: if search_filters is None: search_filters = {"linked_to": self.name} elif isinstance(search_filters, dict): search_filters = {**search_filters, "linked_to": self.name} elif isinstance(search_filters, list): search_filters = [EQ("linked_to", self.name), *search_filters] _max_results = max_results or self.max_results log_debug(f"Getting {_max_results} relevant documents for query: {query}") return self.vector_db.search(query=query, limit=_max_results, filters=search_filters) except Exception as e: log_error(f"Error searching for documents: {e}") return [] async def asearch( self, query: str, max_results: Optional[int] = None, filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, search_type: Optional[str] = None, ) -> List[Document]: """Returns relevant documents matching a query""" from agno.vectordb import VectorDb from agno.vectordb.search import SearchType self.vector_db = cast(VectorDb, self.vector_db) if ( hasattr(self.vector_db, "search_type") and isinstance(self.vector_db.search_type, SearchType) and search_type ): self.vector_db.search_type = SearchType(search_type) try: if self.vector_db is None: log_warning("No vector db provided") return [] # Inject linked_to filter when isolate_vector_search is enabled and knowledge has a name search_filters = filters if self.isolate_vector_search and self.name: if search_filters is None: search_filters = {"linked_to": self.name} elif isinstance(search_filters, dict): search_filters = {**search_filters, "linked_to": self.name} elif isinstance(search_filters, list): search_filters = [EQ("linked_to", self.name), *search_filters] _max_results = max_results or self.max_results log_debug(f"Getting {_max_results} relevant documents for query: {query}") try: return await self.vector_db.async_search(query=query, limit=_max_results, filters=search_filters) except NotImplementedError: log_info("Vector db does not support async search") return self.vector_db.search(query=query, limit=_max_results, filters=search_filters) except Exception as e: log_error(f"Error searching for documents: {e}") return [] # ========================================== # PUBLIC API - CONTENT MANAGEMENT METHODS # ========================================== def get_content( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, ) -> Tuple[List[Content], int]: if self.contents_db is None: raise ValueError("No contents db provided") if isinstance(self.contents_db, AsyncBaseDb): raise ValueError("get_content() is not supported for async databases. Please use aget_content() instead.") # Filter by linked_to when knowledge has a name for isolation contents, count = self.contents_db.get_knowledge_contents( limit=limit, page=page, sort_by=sort_by, sort_order=sort_order, linked_to=self.name ) return [self._content_row_to_content(row) for row in contents], count async def aget_content( self, limit: Optional[int] = None, page: Optional[int] = None, sort_by: Optional[str] = None, sort_order: Optional[str] = None, ) -> Tuple[List[Content], int]: if self.contents_db is None: raise ValueError("No contents db provided") # Filter by linked_to when knowledge has a name for isolation if isinstance(self.contents_db, AsyncBaseDb): contents, count = await self.contents_db.get_knowledge_contents( limit=limit, page=page, sort_by=sort_by, sort_order=sort_order, linked_to=self.name ) else: contents, count = self.contents_db.get_knowledge_contents( limit=limit, page=page, sort_by=sort_by, sort_order=sort_order, linked_to=self.name ) return [self._content_row_to_content(row) for row in contents], count def get_content_by_id(self, content_id: str) -> Optional[Content]: if self.contents_db is None: raise ValueError("No contents db provided") if isinstance(self.contents_db, AsyncBaseDb): raise ValueError( "get_content_by_id() is not supported for async databases. Please use aget_content_by_id() instead." ) content_row = self.contents_db.get_knowledge_content(content_id) if content_row is None: return None return self._content_row_to_content(content_row) async def aget_content_by_id(self, content_id: str) -> Optional[Content]: if self.contents_db is None: raise ValueError("No contents db provided") if isinstance(self.contents_db, AsyncBaseDb): content_row = await self.contents_db.get_knowledge_content(content_id) else: content_row = self.contents_db.get_knowledge_content(content_id) if content_row is None: return None return self._content_row_to_content(content_row) def get_content_status(self, content_id: str) -> Tuple[Optional[ContentStatus], Optional[str]]: if self.contents_db is None: raise ValueError("No contents db provided") if isinstance(self.contents_db, AsyncBaseDb): raise ValueError( "get_content_status() is not supported for async databases. Please use aget_content_status() instead." ) content_row = self.contents_db.get_knowledge_content(content_id) if content_row is None: return None, "Content not found" return self._parse_content_status(content_row.status), content_row.status_message async def aget_content_status(self, content_id: str) -> Tuple[Optional[ContentStatus], Optional[str]]: if self.contents_db is None: raise ValueError("No contents db provided") if isinstance(self.contents_db, AsyncBaseDb): content_row = await self.contents_db.get_knowledge_content(content_id) else: content_row = self.contents_db.get_knowledge_content(content_id) if content_row is None: return None, "Content not found" return self._parse_content_status(content_row.status), content_row.status_message def patch_content(self, content: Content) -> Optional[Dict[str, Any]]: return self._update_content(content) async def apatch_content(self, content: Content) -> Optional[Dict[str, Any]]: return await self._aupdate_content(content) def remove_content_by_id(self, content_id: str): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db is not None: if self.vector_db.__class__.__name__ == "LightRag": # For LightRAG, get the content first to find the external_id content = self.get_content_by_id(content_id) if content and content.external_id: self.vector_db.delete_by_external_id(content.external_id) # type: ignore else: log_warning(f"No external_id found for content {content_id}, cannot delete from LightRAG") else: self.vector_db.delete_by_content_id(content_id) if self.contents_db is not None: self.contents_db.delete_knowledge_content(content_id) async def aremove_content_by_id(self, content_id: str): if self.vector_db is not None: if self.vector_db.__class__.__name__ == "LightRag": # For LightRAG, get the content first to find the external_id content = await self.aget_content_by_id(content_id) if content and content.external_id: self.vector_db.delete_by_external_id(content.external_id) # type: ignore else: log_warning(f"No external_id found for content {content_id}, cannot delete from LightRAG") else: self.vector_db.delete_by_content_id(content_id) if self.contents_db is not None: if isinstance(self.contents_db, AsyncBaseDb): await self.contents_db.delete_knowledge_content(content_id) else: self.contents_db.delete_knowledge_content(content_id) def remove_all_content(self): contents, _ = self.get_content() for content in contents: if content.id is not None: self.remove_content_by_id(content.id) async def aremove_all_content(self): contents, _ = await self.aget_content() for content in contents: if content.id is not None: await self.aremove_content_by_id(content.id) def remove_vector_by_id(self, id: str) -> bool: from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db is None: log_warning("No vector DB provided") return False return self.vector_db.delete_by_id(id) def remove_vectors_by_name(self, name: str) -> bool: from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db is None: log_warning("No vector DB provided") return False return self.vector_db.delete_by_name(name) def remove_vectors_by_metadata(self, metadata: Dict[str, Any]) -> bool: from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db is None: log_warning("No vector DB provided") return False return self.vector_db.delete_by_metadata(metadata) # ========================================== # PUBLIC API - FILTER METHODS # ========================================== def get_valid_filters(self) -> Set[str]: if self.contents_db is None: log_info("Advanced filtering is not supported without a contents db. All filter keys considered valid.") return set() contents, _ = self.get_content() valid_filters: Set[str] = set() for content in contents: if content.metadata: valid_filters.update(content.metadata.keys()) return valid_filters async def aget_valid_filters(self) -> Set[str]: if self.contents_db is None: log_info("Advanced filtering is not supported without a contents db. All filter keys considered valid.") return set() contents, _ = await self.aget_content() valid_filters: Set[str] = set() for content in contents: if content.metadata: valid_filters.update(content.metadata.keys()) return valid_filters def validate_filters( self, filters: Union[Dict[str, Any], List[FilterExpr]] ) -> Tuple[Union[Dict[str, Any], List[FilterExpr]], List[str]]: valid_filters_from_db = self.get_valid_filters() valid_filters, invalid_keys = self._validate_filters(filters, valid_filters_from_db) return valid_filters, invalid_keys async def avalidate_filters( self, filters: Union[Dict[str, Any], List[FilterExpr]] ) -> Tuple[Union[Dict[str, Any], List[FilterExpr]], List[str]]: """Return a tuple containing a dict with all valid filters and a list of invalid filter keys""" valid_filters_from_db = await self.aget_valid_filters() valid_filters, invalid_keys = self._validate_filters(filters, valid_filters_from_db) return valid_filters, invalid_keys def _validate_filters( self, filters: Union[Dict[str, Any], List[FilterExpr]], valid_metadata_filters: Set[str] ) -> Tuple[Union[Dict[str, Any], List[FilterExpr]], List[str]]: if not filters: return {}, [] valid_filters: Union[Dict[str, Any], List[FilterExpr]] = {} invalid_keys = [] if isinstance(filters, dict): # If no metadata filters tracked yet, all keys are considered invalid if valid_metadata_filters is None or not valid_metadata_filters: invalid_keys = list(filters.keys()) log_warning( f"No valid metadata filters tracked yet. All filter keys considered invalid: {invalid_keys}" ) return {}, invalid_keys for key, value in filters.items(): # Handle both normal keys and prefixed keys like meta_data.key base_key = key.split(".")[-1] if "." in key else key if base_key in valid_metadata_filters or key in valid_metadata_filters: valid_filters[key] = value # type: ignore else: invalid_keys.append(key) log_warning(f"Invalid filter key: {key} - not present in knowledge base") elif isinstance(filters, List): # Validate list filters against known metadata keys if valid_metadata_filters is None or not valid_metadata_filters: # Can't validate keys without metadata - return original list log_warning("No valid metadata filters tracked yet. Cannot validate list filter keys.") return filters, [] valid_list_filters: List[FilterExpr] = [] for i, filter_item in enumerate(filters): if not isinstance(filter_item, FilterExpr): log_warning( f"Invalid filter at index {i}: expected FilterExpr instance, " f"got {type(filter_item).__name__}. " f"Use filter expressions like EQ('key', 'value'), IN('key', [values]), " f"AND(...), OR(...), NOT(...) from agno.filters" ) continue # Check if filter has a key attribute and validate it if hasattr(filter_item, "key"): key = filter_item.key base_key = key.split(".")[-1] if "." in key else key if base_key in valid_metadata_filters or key in valid_metadata_filters: valid_list_filters.append(filter_item) else: invalid_keys.append(key) log_warning(f"Invalid filter key: {key} - not present in knowledge base") else: # Complex filters (AND, OR, NOT) - keep them as-is # They contain nested filters that will be validated by the vector DB valid_list_filters.append(filter_item) return valid_list_filters, invalid_keys return valid_filters, invalid_keys # ========================================== # PUBLIC API - READER MANAGEMENT METHODS # ========================================== def construct_readers(self): """Initialize readers dictionary for lazy loading.""" # Initialize empty readers dict - readers will be created on-demand if self.readers is None: self.readers = {} def add_reader(self, reader: Reader): """Add a custom reader to the knowledge base.""" if self.readers is None: self.readers = {} # Generate a key for the reader reader_key = self._generate_reader_key(reader) self.readers[reader_key] = reader return reader def get_readers(self) -> Dict[str, Reader]: """Get all currently loaded readers (only returns readers that have been used).""" if self.readers is None: self.readers = {} elif not isinstance(self.readers, dict): # Defensive check: if readers is not a dict (e.g., was set to a list), convert it if isinstance(self.readers, list): readers_dict: Dict[str, Reader] = {} for reader in self.readers: if isinstance(reader, Reader): reader_key = self._generate_reader_key(reader) # Handle potential duplicate keys by appending index if needed original_key = reader_key counter = 1 while reader_key in readers_dict: reader_key = f"{original_key}_{counter}" counter += 1 readers_dict[reader_key] = reader self.readers = readers_dict else: # For any other unexpected type, reset to empty dict self.readers = {} return self.readers # --- Reader Helper Methods --- def _generate_reader_key(self, reader: Reader) -> str: """Generate a key for a reader instance.""" if reader.name: return f"{reader.name.lower().replace(' ', '_')}" else: return f"{reader.__class__.__name__.lower().replace(' ', '_')}" def _get_reader(self, reader_type: str) -> Optional[Reader]: """Get a cached reader or create it if not cached, handling missing dependencies gracefully.""" if self.readers is None: self.readers = {} if reader_type not in self.readers: try: reader = ReaderFactory.create_reader(reader_type) if reader: self.readers[reader_type] = reader else: return None except Exception as e: log_warning(f"Cannot create {reader_type} reader {e}") return None return self.readers.get(reader_type) def _select_reader(self, extension: str) -> Reader: """Select the appropriate reader for a file extension.""" log_info(f"Selecting reader for extension: {extension}") return ReaderFactory.get_reader_for_extension(extension) def _should_include_file(self, file_path: str, include: Optional[List[str]], exclude: Optional[List[str]]) -> bool: """ Determine if a file should be included based on include/exclude patterns. Logic: 1. If include is specified, file must match at least one include pattern 2. If exclude is specified, file must not match any exclude pattern 3. If neither specified, include all files Patterns without path separators (e.g. ``*.go``) are matched against the filename only so they work when *file_path* is a full or relative path that contains directories. Args: file_path: Path to the file to check include: Optional list of include patterns (glob-style) exclude: Optional list of exclude patterns (glob-style) Returns: bool: True if file should be included, False otherwise """ import fnmatch import os file_name = os.path.basename(file_path) def _matches(path: str, name: str, pattern: str) -> bool: """Match pattern against both the full path and the basename.""" return fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(name, pattern) # If include patterns specified, file must match at least one if include: if not any(_matches(file_path, file_name, pattern) for pattern in include): return False # If exclude patterns specified, file must not match any if exclude: if any(_matches(file_path, file_name, pattern) for pattern in exclude): return False return True def _is_text_mime_type(self, mime_type: str) -> bool: """ Check if a MIME type represents text content that can be safely encoded as UTF-8. Args: mime_type: The MIME type to check Returns: bool: True if it's a text type, False if binary """ if not mime_type: return False text_types = [ "text/", "application/json", "application/xml", "application/javascript", "application/csv", "application/sql", ] return any(mime_type.startswith(t) for t in text_types) # --- Reader Properties (Lazy Loading) --- @property def pdf_reader(self) -> Optional[Reader]: """PDF reader - lazy loaded via factory.""" return self._get_reader("pdf") @property def csv_reader(self) -> Optional[Reader]: """CSV reader - lazy loaded via factory.""" return self._get_reader("csv") @property def excel_reader(self) -> Optional[Reader]: """Excel reader - lazy loaded via factory.""" return self._get_reader("excel") @property def docx_reader(self) -> Optional[Reader]: """Docx reader - lazy loaded via factory.""" return self._get_reader("docx") @property def pptx_reader(self) -> Optional[Reader]: """PPTX reader - lazy loaded via factory.""" return self._get_reader("pptx") @property def json_reader(self) -> Optional[Reader]: """JSON reader - lazy loaded via factory.""" return self._get_reader("json") @property def markdown_reader(self) -> Optional[Reader]: """Markdown reader - lazy loaded via factory.""" return self._get_reader("markdown") @property def text_reader(self) -> Optional[Reader]: """Text reader - lazy loaded via factory.""" return self._get_reader("text") @property def website_reader(self) -> Optional[Reader]: """Website reader - lazy loaded via factory.""" return self._get_reader("website") @property def firecrawl_reader(self) -> Optional[Reader]: """Firecrawl reader - lazy loaded via factory.""" return self._get_reader("firecrawl") @property def youtube_reader(self) -> Optional[Reader]: """YouTube reader - lazy loaded via factory.""" return self._get_reader("youtube") # ========================================== # PRIVATE - CONTENT LOADING METHODS # ========================================== def _load_content( self, content: Content, upsert: bool, skip_if_exists: bool, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, ) -> None: """Synchronously load content.""" if content.path: self._load_from_path(content, upsert, skip_if_exists, include, exclude) if content.url: self._load_from_url(content, upsert, skip_if_exists) if content.file_data: self._load_from_content(content, upsert, skip_if_exists) if content.topics: self._load_from_topics(content, upsert, skip_if_exists) if content.remote_content: self._load_from_remote_content(content, upsert, skip_if_exists) async def _aload_content( self, content: Content, upsert: bool, skip_if_exists: bool, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, ) -> None: if content.path: await self._aload_from_path(content, upsert, skip_if_exists, include, exclude) if content.url: await self._aload_from_url(content, upsert, skip_if_exists) if content.file_data: await self._aload_from_content(content, upsert, skip_if_exists) if content.topics: await self._aload_from_topics(content, upsert, skip_if_exists) if content.remote_content: await self._aload_from_remote_content(content, upsert, skip_if_exists) def _should_skip(self, content_hash: str, skip_if_exists: bool) -> bool: """ Handle the skip_if_exists logic for content that already exists in the vector database. Args: content_hash: The content hash string to check for existence skip_if_exists: Whether to skip if content already exists Returns: bool: True if should skip processing, False if should continue """ from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.vector_db and self.vector_db.content_hash_exists(content_hash) and skip_if_exists: log_debug(f"Content already exists: {content_hash}, skipping...") return True return False def _select_reader_by_extension( self, file_extension: str, provided_reader: Optional[Reader] = None ) -> Tuple[Optional[Reader], str]: """ Select a reader based on file extension. Args: file_extension: File extension (e.g., '.pdf', '.csv') provided_reader: Optional reader already provided Returns: Tuple of (reader, name) where name may be adjusted based on extension """ if provided_reader: return provided_reader, "" file_extension = file_extension.lower() if file_extension == ".csv": return self.csv_reader, "data.csv" elif file_extension == ".pdf": return self.pdf_reader, "" elif file_extension == ".docx": return self.docx_reader, "" elif file_extension == ".pptx": return self.pptx_reader, "" elif file_extension == ".json": return self.json_reader, "" elif file_extension == ".markdown": return self.markdown_reader, "" elif file_extension in [".xlsx", ".xls"]: return self.excel_reader, "" else: return self.text_reader, "" def _select_reader_by_uri(self, uri: str, provided_reader: Optional[Reader] = None) -> Optional[Reader]: """ Select a reader based on URI/file path extension. Args: uri: URI or file path provided_reader: Optional reader already provided Returns: Selected reader or None """ if provided_reader: return provided_reader uri_lower = uri.lower() if uri_lower.endswith(".pdf"): return self.pdf_reader elif uri_lower.endswith(".csv"): return self.csv_reader elif uri_lower.endswith(".docx"): return self.docx_reader elif uri_lower.endswith(".pptx"): return self.pptx_reader elif uri_lower.endswith(".json"): return self.json_reader elif uri_lower.endswith(".markdown"): return self.markdown_reader elif uri_lower.endswith(".xlsx") or uri_lower.endswith(".xls"): return self.excel_reader else: return self.text_reader def _read( self, reader: Reader, source: Union[Path, str, BytesIO], name: Optional[str] = None, password: Optional[str] = None, ) -> List[Document]: """ Read content using a reader with optional password handling. Args: reader: Reader to use source: Source to read from (Path, URL string, or BytesIO) name: Optional name for the document password: Optional password for protected files Returns: List of documents read """ import inspect read_signature = inspect.signature(reader.read) if password is not None and "password" in read_signature.parameters: if isinstance(source, BytesIO): return reader.read(source, name=name, password=password) else: return reader.read(source, name=name, password=password) else: if isinstance(source, BytesIO): return reader.read(source, name=name) else: return reader.read(source, name=name) async def _aread( self, reader: Reader, source: Union[Path, str, BytesIO], name: Optional[str] = None, password: Optional[str] = None, ) -> List[Document]: """ Read content using a reader's async_read method with optional password handling. Args: reader: Reader to use source: Source to read from (Path, URL string, or BytesIO) name: Optional name for the document password: Optional password for protected files Returns: List of documents read """ import inspect read_signature = inspect.signature(reader.async_read) if password is not None and "password" in read_signature.parameters: return await reader.async_read(source, name=name, password=password) else: if isinstance(source, BytesIO): return await reader.async_read(source, name=name) else: return await reader.async_read(source, name=name) def _prepare_documents_for_insert( self, documents: List[Document], content_id: str, calculate_sizes: bool = False, metadata: Optional[Dict[str, Any]] = None, ) -> List[Document]: """ Prepare documents for insertion by assigning content_id and optionally calculating sizes and updating metadata. Args: documents: List of documents to prepare content_id: Content ID to assign to documents calculate_sizes: Whether to calculate document sizes metadata: Optional metadata to merge into document metadata Returns: List of prepared documents """ for document in documents: document.content_id = content_id if calculate_sizes and document.content and not document.size: document.size = len(document.content.encode("utf-8")) if metadata: document.meta_data.update(metadata) document.meta_data["linked_to"] = self.name or "" return documents def _chunk_documents_sync(self, reader: Reader, documents: List[Document]) -> List[Document]: """ Chunk documents synchronously. Args: reader: Reader with chunking strategy documents: Documents to chunk Returns: List of chunked documents """ if not reader or reader.chunk: return documents chunked_documents = [] for doc in documents: chunked_documents.extend(reader.chunk_document(doc)) return chunked_documents async def _aload_from_path( self, content: Content, upsert: bool, skip_if_exists: bool, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, ): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from path, {content.id}, {content.name}, {content.path}, {content.description}") path = Path(content.path) # type: ignore if path.is_file(): if self._should_include_file(str(path), include, exclude): log_debug(f"Adding file {path} due to include/exclude filters") # Set name from path if not provided if not content.name: content.name = path.name await self._ainsert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return # Handle LightRAG special case - read file and upload directly if self.vector_db.__class__.__name__ == "LightRag": await self._aprocess_lightrag_content(content, KnowledgeContentOrigin.PATH) return if content.reader: reader = content.reader else: reader = ReaderFactory.get_reader_for_extension(path.suffix) log_debug(f"Using Reader: {reader.__class__.__name__}") if reader: password = content.auth.password if content.auth and content.auth.password is not None else None read_documents = await self._aread(reader, path, name=content.name or path.name, password=password) else: read_documents = [] if not content.file_type: content.file_type = path.suffix if not content.size and content.file_data: content.size = len(content.file_data.content) # type: ignore if not content.size: try: content.size = path.stat().st_size except (OSError, IOError) as e: log_warning(f"Could not get file size for {path}: {e}") content.size = 0 if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, metadata=content.metadata) await self._ahandle_vector_db_insert(content, read_documents, upsert) elif path.is_dir(): for file_path in path.iterdir(): # Apply include/exclude filtering if not self._should_include_file(str(file_path), include, exclude): log_debug(f"Skipping file {file_path} due to include/exclude filters") continue file_content = Content( name=content.name, path=str(file_path), metadata=content.metadata, description=content.description, reader=content.reader, ) file_content.content_hash = self._build_content_hash(file_content) file_content.id = generate_id(file_content.content_hash) await self._aload_from_path(file_content, upsert, skip_if_exists, include, exclude) else: log_warning(f"Invalid path: {path}") def _load_from_path( self, content: Content, upsert: bool, skip_if_exists: bool, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, ): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from path, {content.id}, {content.name}, {content.path}, {content.description}") path = Path(content.path) # type: ignore if path.is_file(): if self._should_include_file(str(path), include, exclude): log_debug(f"Adding file {path} due to include/exclude filters") # Set name from path if not provided if not content.name: content.name = path.name self._insert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED self._update_content(content) return # Handle LightRAG special case - read file and upload directly if self.vector_db.__class__.__name__ == "LightRag": self._process_lightrag_content(content, KnowledgeContentOrigin.PATH) return if content.reader: reader = content.reader else: reader = ReaderFactory.get_reader_for_extension(path.suffix) log_debug(f"Using Reader: {reader.__class__.__name__}") if reader: password = content.auth.password if content.auth and content.auth.password is not None else None read_documents = self._read(reader, path, name=content.name or path.name, password=password) else: read_documents = [] if not content.file_type: content.file_type = path.suffix if not content.size and content.file_data: content.size = len(content.file_data.content) # type: ignore if not content.size: try: content.size = path.stat().st_size except (OSError, IOError) as e: log_warning(f"Could not get file size for {path}: {e}") content.size = 0 if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, metadata=content.metadata) self._handle_vector_db_insert(content, read_documents, upsert) elif path.is_dir(): for file_path in path.iterdir(): # Apply include/exclude filtering if not self._should_include_file(str(file_path), include, exclude): log_debug(f"Skipping file {file_path} due to include/exclude filters") continue file_content = Content( name=content.name, path=str(file_path), metadata=content.metadata, description=content.description, reader=content.reader, ) file_content.content_hash = self._build_content_hash(file_content) file_content.id = generate_id(file_content.content_hash) self._load_from_path(file_content, upsert, skip_if_exists, include, exclude) else: log_warning(f"Invalid path: {path}") async def _aload_from_url( self, content: Content, upsert: bool, skip_if_exists: bool, ): """Load the content in the contextual URL 1. Set content hash 2. Validate the URL 3. Read the content 4. Prepare and insert the content in the vector database """ from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from URL {content.url}") content.file_type = "url" if not content.url: raise ValueError("No url provided") # Store URL source metadata in _agno for source tracking content.metadata = set_agno_metadata(content.metadata, "source_type", "url") content.metadata = set_agno_metadata(content.metadata, "source_url", content.url) # Set name from URL if not provided if not content.name and content.url: from urllib.parse import urlparse parsed = urlparse(content.url) url_path = Path(parsed.path) content.name = url_path.name if url_path.name else content.url # 1. Add content to contents database await self._ainsert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return if self.vector_db.__class__.__name__ == "LightRag": await self._aprocess_lightrag_content(content, KnowledgeContentOrigin.URL) return # 2. Validate URL try: from urllib.parse import urlparse parsed_url = urlparse(content.url) if not all([parsed_url.scheme, parsed_url.netloc]): content.status = ContentStatus.FAILED content.status_message = f"Invalid URL format: {content.url}" await self._aupdate_content(content) log_warning(f"Invalid URL format: {content.url}") except Exception as e: content.status = ContentStatus.FAILED content.status_message = f"Invalid URL: {content.url} - {str(e)}" await self._aupdate_content(content) log_warning(f"Invalid URL: {content.url} - {str(e)}") # 3. Fetch and load content if file has an extension url_path = Path(parsed_url.path) file_extension = url_path.suffix.lower() bytes_content = None if file_extension: async with AsyncClient() as client: response = await async_fetch_with_retry(content.url, client=client) bytes_content = BytesIO(response.content) # 4. Select reader name = content.name if content.name else content.url if file_extension: reader, default_name = self._select_reader_by_extension(file_extension, content.reader) if default_name and file_extension == ".csv": name = basename(parsed_url.path) or default_name else: reader = content.reader or self.website_reader # 5. Read content try: read_documents = [] if reader is not None: # Special handling for YouTubeReader if reader.__class__.__name__ == "YouTubeReader": read_documents = await reader.async_read(content.url, name=name) else: password = content.auth.password if content.auth and content.auth.password is not None else None source = bytes_content if bytes_content else content.url read_documents = await self._aread(reader, source, name=name, password=password) except Exception as e: log_error(f"Error reading URL: {content.url} - {str(e)}") content.status = ContentStatus.FAILED content.status_message = f"Error reading URL: {content.url} - {str(e)}" await self._aupdate_content(content) return # 6. Chunk documents if needed if reader and not reader.chunk: read_documents = await reader.chunk_documents_async(read_documents) # 7. Group documents by source URL for multi-page readers (like WebsiteReader) docs_by_source: Dict[str, List[Document]] = {} for doc in read_documents: source_url = doc.meta_data.get("url", content.url) if doc.meta_data else content.url source_url = source_url or "unknown" if source_url not in docs_by_source: docs_by_source[source_url] = [] docs_by_source[source_url].append(doc) # 8. Process each source separately if multiple sources exist if len(docs_by_source) > 1: for source_url, source_docs in docs_by_source.items(): # Compute per-document hash based on actual source URL doc_hash = self._build_document_content_hash(source_docs[0], content) # Check skip_if_exists for each source individually if self._should_skip(doc_hash, skip_if_exists): log_debug(f"Skipping already indexed: {source_url}") continue doc_id = generate_id(doc_hash) self._prepare_documents_for_insert(source_docs, doc_id, calculate_sizes=True) # Insert with per-document hash if self.vector_db.upsert_available() and upsert: try: await self.vector_db.async_upsert(doc_hash, source_docs, content.metadata) except Exception as e: log_error(f"Error upserting document from {source_url}: {e}") continue else: try: await self.vector_db.async_insert(doc_hash, documents=source_docs, filters=content.metadata) except Exception as e: log_error(f"Error inserting document from {source_url}: {e}") continue content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return # 9. Single source - use existing logic with original content hash if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, calculate_sizes=True) await self._ahandle_vector_db_insert(content, read_documents, upsert) def _load_from_url( self, content: Content, upsert: bool, skip_if_exists: bool, ): """Synchronous version of _load_from_url. Load the content from a URL: 1. Set content hash 2. Validate the URL 3. Read the content 4. Prepare and insert the content in the vector database """ from agno.utils.http import fetch_with_retry from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from URL {content.url}") content.file_type = "url" if not content.url: raise ValueError("No url provided") # Store URL source metadata in _agno for source tracking content.metadata = set_agno_metadata(content.metadata, "source_type", "url") content.metadata = set_agno_metadata(content.metadata, "source_url", content.url) # Set name from URL if not provided if not content.name and content.url: from urllib.parse import urlparse parsed = urlparse(content.url) url_path = Path(parsed.path) content.name = url_path.name if url_path.name else content.url # 1. Add content to contents database self._insert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED self._update_content(content) return if self.vector_db.__class__.__name__ == "LightRag": self._process_lightrag_content(content, KnowledgeContentOrigin.URL) return # 2. Validate URL try: from urllib.parse import urlparse parsed_url = urlparse(content.url) if not all([parsed_url.scheme, parsed_url.netloc]): content.status = ContentStatus.FAILED content.status_message = f"Invalid URL format: {content.url}" self._update_content(content) log_warning(f"Invalid URL format: {content.url}") except Exception as e: content.status = ContentStatus.FAILED content.status_message = f"Invalid URL: {content.url} - {str(e)}" self._update_content(content) log_warning(f"Invalid URL: {content.url} - {str(e)}") # 3. Fetch and load content if file has an extension url_path = Path(parsed_url.path) file_extension = url_path.suffix.lower() bytes_content = None if file_extension: response = fetch_with_retry(content.url) bytes_content = BytesIO(response.content) # 4. Select reader name = content.name if content.name else content.url if file_extension: reader, default_name = self._select_reader_by_extension(file_extension, content.reader) if default_name and file_extension == ".csv": name = basename(parsed_url.path) or default_name else: reader = content.reader or self.website_reader # 5. Read content try: read_documents = [] if reader is not None: # Special handling for YouTubeReader if reader.__class__.__name__ == "YouTubeReader": read_documents = reader.read(content.url, name=name) else: password = content.auth.password if content.auth and content.auth.password is not None else None source = bytes_content if bytes_content else content.url read_documents = self._read(reader, source, name=name, password=password) except Exception as e: log_error(f"Error reading URL: {content.url} - {str(e)}") content.status = ContentStatus.FAILED content.status_message = f"Error reading URL: {content.url} - {str(e)}" self._update_content(content) return # 6. Chunk documents if needed (sync version) if reader: read_documents = self._chunk_documents_sync(reader, read_documents) # 7. Group documents by source URL for multi-page readers (like WebsiteReader) docs_by_source: Dict[str, List[Document]] = {} for doc in read_documents: source_url = doc.meta_data.get("url", content.url) if doc.meta_data else content.url source_url = source_url or "unknown" if source_url not in docs_by_source: docs_by_source[source_url] = [] docs_by_source[source_url].append(doc) # 8. Process each source separately if multiple sources exist if len(docs_by_source) > 1: for source_url, source_docs in docs_by_source.items(): # Compute per-document hash based on actual source URL doc_hash = self._build_document_content_hash(source_docs[0], content) # Check skip_if_exists for each source individually if self._should_skip(doc_hash, skip_if_exists): log_debug(f"Skipping already indexed: {source_url}") continue doc_id = generate_id(doc_hash) self._prepare_documents_for_insert(source_docs, doc_id, calculate_sizes=True) # Insert with per-document hash if self.vector_db.upsert_available() and upsert: try: self.vector_db.upsert(doc_hash, source_docs, content.metadata) except Exception as e: log_error(f"Error upserting document from {source_url}: {e}") continue else: try: self.vector_db.insert(doc_hash, documents=source_docs, filters=content.metadata) except Exception as e: log_error(f"Error inserting document from {source_url}: {e}") continue content.status = ContentStatus.COMPLETED self._update_content(content) return # 9. Single source - use existing logic with original content hash if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, calculate_sizes=True) self._handle_vector_db_insert(content, read_documents, upsert) async def _aload_from_content( self, content: Content, upsert: bool = True, skip_if_exists: bool = False, ): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if content.name: name = content.name elif content.file_data and content.file_data.filename: name = content.file_data.filename elif content.file_data and content.file_data.content: if isinstance(content.file_data.content, bytes): name = content.file_data.content[:10].decode("utf-8", errors="ignore") elif isinstance(content.file_data.content, str): name = ( content.file_data.content[:10] if len(content.file_data.content) >= 10 else content.file_data.content ) else: name = str(content.file_data.content)[:10] else: name = None if name is not None: content.name = name log_info(f"Adding content from {content.name}") await self._ainsert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return if content.file_data and self.vector_db.__class__.__name__ == "LightRag": await self._aprocess_lightrag_content(content, KnowledgeContentOrigin.CONTENT) return read_documents = [] if isinstance(content.file_data, str): content_bytes = content.file_data.encode("utf-8", errors="replace") content_io = io.BytesIO(content_bytes) if content.reader: log_debug(f"Using reader: {content.reader.__class__.__name__} to read content") read_documents = await content.reader.async_read(content_io, name=name) else: text_reader = self.text_reader if text_reader: read_documents = await text_reader.async_read(content_io, name=name) else: content.status = ContentStatus.FAILED content.status_message = "Text reader not available" await self._aupdate_content(content) return elif isinstance(content.file_data, FileData): if content.file_data.type: if isinstance(content.file_data.content, bytes): content_io = io.BytesIO(content.file_data.content) elif isinstance(content.file_data.content, str): content_bytes = content.file_data.content.encode("utf-8", errors="replace") content_io = io.BytesIO(content_bytes) else: content_io = content.file_data.content # type: ignore # Respect an explicitly provided reader; otherwise select based on file type if content.reader: log_debug(f"Using reader: {content.reader.__class__.__name__} to read content") reader = content.reader else: # Prefer filename extension over MIME type for reader selection # (browsers often send wrong MIME types for Excel files) reader_hint = content.file_data.type if content.file_data.filename: ext = Path(content.file_data.filename).suffix.lower() if ext: reader_hint = ext reader = self._select_reader(reader_hint) # Use file_data.filename for reader (preserves extension for format detection) reader_name = content.file_data.filename or content.name or f"content_{content.file_data.type}" read_documents = await reader.async_read(content_io, name=reader_name) if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, metadata=content.metadata) if len(read_documents) == 0: content.status = ContentStatus.FAILED content.status_message = "Content could not be read" await self._aupdate_content(content) return else: content.status = ContentStatus.FAILED content.status_message = "No content provided" await self._aupdate_content(content) return await self._ahandle_vector_db_insert(content, read_documents, upsert) def _load_from_content( self, content: Content, upsert: bool = True, skip_if_exists: bool = False, ): """Synchronous version of _load_from_content.""" from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if content.name: name = content.name elif content.file_data and content.file_data.filename: name = content.file_data.filename elif content.file_data and content.file_data.content: if isinstance(content.file_data.content, bytes): name = content.file_data.content[:10].decode("utf-8", errors="ignore") elif isinstance(content.file_data.content, str): name = ( content.file_data.content[:10] if len(content.file_data.content) >= 10 else content.file_data.content ) else: name = str(content.file_data.content)[:10] else: name = None if name is not None: content.name = name log_info(f"Adding content from {content.name}") self._insert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): # type: ignore[arg-type] content.status = ContentStatus.COMPLETED self._update_content(content) return if content.file_data and self.vector_db.__class__.__name__ == "LightRag": self._process_lightrag_content(content, KnowledgeContentOrigin.CONTENT) return read_documents = [] if isinstance(content.file_data, str): content_bytes = content.file_data.encode("utf-8", errors="replace") content_io = io.BytesIO(content_bytes) if content.reader: log_debug(f"Using reader: {content.reader.__class__.__name__} to read content") read_documents = content.reader.read(content_io, name=name) else: text_reader = self.text_reader if text_reader: read_documents = text_reader.read(content_io, name=name) else: content.status = ContentStatus.FAILED content.status_message = "Text reader not available" self._update_content(content) return elif isinstance(content.file_data, FileData): if content.file_data.type: if isinstance(content.file_data.content, bytes): content_io = io.BytesIO(content.file_data.content) elif isinstance(content.file_data.content, str): content_bytes = content.file_data.content.encode("utf-8", errors="replace") content_io = io.BytesIO(content_bytes) else: content_io = content.file_data.content # type: ignore # Respect an explicitly provided reader; otherwise select based on file type if content.reader: log_debug(f"Using reader: {content.reader.__class__.__name__} to read content") reader = content.reader else: # Prefer filename extension over MIME type for reader selection # (browsers often send wrong MIME types for Excel files) reader_hint = content.file_data.type if content.file_data.filename: ext = Path(content.file_data.filename).suffix.lower() if ext: reader_hint = ext reader = self._select_reader(reader_hint) # Use file_data.filename for reader (preserves extension for format detection) reader_name = content.file_data.filename or content.name or f"content_{content.file_data.type}" read_documents = reader.read(content_io, name=reader_name) if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id, metadata=content.metadata) if len(read_documents) == 0: content.status = ContentStatus.FAILED content.status_message = "Content could not be read" self._update_content(content) return else: content.status = ContentStatus.FAILED content.status_message = "No content provided" self._update_content(content) return self._handle_vector_db_insert(content, read_documents, upsert) async def _aload_from_topics( self, content: Content, upsert: bool, skip_if_exists: bool, ): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from topics: {content.topics}") if content.topics is None: log_warning("No topics provided for content") return for topic in content.topics: content = Content( name=topic, metadata=content.metadata, reader=content.reader, status=ContentStatus.PROCESSING if content.reader else ContentStatus.FAILED, file_data=FileData( type="Topic", ), topics=[topic], ) content.content_hash = self._build_content_hash(content) content.id = generate_id(content.content_hash) await self._ainsert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): content.status = ContentStatus.COMPLETED await self._aupdate_content(content) continue # Skip to next topic, don't exit loop if self.vector_db.__class__.__name__ == "LightRag": await self._aprocess_lightrag_content(content, KnowledgeContentOrigin.TOPIC) continue # Skip to next topic, don't exit loop if self.vector_db and self.vector_db.content_hash_exists(content.content_hash) and skip_if_exists: log_info(f"Content {content.content_hash} already exists, skipping") continue if content.reader is None: log_error(f"No reader available for topic: {topic}") content.status = ContentStatus.FAILED content.status_message = "No reader available for topic" await self._aupdate_content(content) continue read_documents = await content.reader.async_read(topic) if len(read_documents) > 0: self._prepare_documents_for_insert(read_documents, content.id, calculate_sizes=True) else: content.status = ContentStatus.FAILED content.status_message = "No content found for topic" await self._aupdate_content(content) await self._ahandle_vector_db_insert(content, read_documents, upsert) def _load_from_topics( self, content: Content, upsert: bool, skip_if_exists: bool, ): """Synchronous version of _load_from_topics.""" from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) log_info(f"Adding content from topics: {content.topics}") if content.topics is None: log_warning("No topics provided for content") return for topic in content.topics: content = Content( name=topic, metadata=content.metadata, reader=content.reader, status=ContentStatus.PROCESSING if content.reader else ContentStatus.FAILED, file_data=FileData( type="Topic", ), topics=[topic], ) content.content_hash = self._build_content_hash(content) content.id = generate_id(content.content_hash) self._insert_contents_db(content) if self._should_skip(content.content_hash, skip_if_exists): content.status = ContentStatus.COMPLETED self._update_content(content) continue # Skip to next topic, don't exit loop if self.vector_db.__class__.__name__ == "LightRag": self._process_lightrag_content(content, KnowledgeContentOrigin.TOPIC) continue # Skip to next topic, don't exit loop if self.vector_db and self.vector_db.content_hash_exists(content.content_hash) and skip_if_exists: log_info(f"Content {content.content_hash} already exists, skipping") continue if content.reader is None: log_error(f"No reader available for topic: {topic}") content.status = ContentStatus.FAILED content.status_message = "No reader available for topic" self._update_content(content) continue read_documents = content.reader.read(topic) if len(read_documents) > 0: self._prepare_documents_for_insert(read_documents, content.id, calculate_sizes=True) else: content.status = ContentStatus.FAILED content.status_message = "No content found for topic" self._update_content(content) self._handle_vector_db_insert(content, read_documents, upsert) # ========================================== # PRIVATE - CONVERSION & DATA METHODS # ========================================== def _build_content_hash(self, content: Content) -> str: """ Build the content hash from the content. For URLs and paths, includes the name and description in the hash if provided to ensure unique content with the same URL/path but different names/descriptions get different hashes. Hash format: - URL with name and description: hash("{name}:{description}:{url}") - URL with name only: hash("{name}:{url}") - URL with description only: hash("{description}:{url}") - URL without name/description: hash("{url}") (backward compatible) - Same logic applies to paths """ hash_parts = [] if content.name: hash_parts.append(content.name) if content.description: hash_parts.append(content.description) if content.path: hash_parts.append(str(content.path)) elif content.url: hash_parts.append(content.url) elif content.file_data and content.file_data.content: # For file_data, always add filename, type, size, or content for uniqueness if content.file_data.filename: hash_parts.append(content.file_data.filename) elif content.file_data.type: hash_parts.append(content.file_data.type) elif content.file_data.size is not None: hash_parts.append(str(content.file_data.size)) else: # Fallback: use the content for uniqueness # Include type information to distinguish str vs bytes content_type = "str" if isinstance(content.file_data.content, str) else "bytes" content_bytes = ( content.file_data.content.encode() if isinstance(content.file_data.content, str) else content.file_data.content ) content_hash = hashlib.sha256(content_bytes).hexdigest()[:16] # Use first 16 chars hash_parts.append(f"{content_type}:{content_hash}") elif content.topics and len(content.topics) > 0: topic = content.topics[0] reader = type(content.reader).__name__ if content.reader else "unknown" hash_parts.append(f"{topic}-{reader}") else: # Fallback for edge cases import random import string fallback = ( content.name or content.id or ("unknown_content" + "".join(random.choices(string.ascii_lowercase + string.digits, k=6))) ) hash_parts.append(fallback) hash_input = ":".join(hash_parts) return hashlib.sha256(hash_input.encode()).hexdigest() def _build_document_content_hash(self, document: Document, content: Content) -> str: """ Build content hash for a specific document. Used for multi-page readers (like WebsiteReader) where each crawled page should have its own unique content hash based on its actual URL. Args: document: The document to build the hash for content: The original content object (for fallback name/description) Returns: A unique hash string for this specific document """ hash_parts = [] if content.name: hash_parts.append(content.name) if content.description: hash_parts.append(content.description) # Use document's own URL if available (set by WebsiteReader) doc_url = document.meta_data.get("url") if document.meta_data else None if doc_url: hash_parts.append(str(doc_url)) elif content.url: hash_parts.append(content.url) elif content.path: hash_parts.append(str(content.path)) else: # Fallback: use content hash for uniqueness hash_parts.append(hashlib.sha256(document.content.encode()).hexdigest()[:16]) hash_input = ":".join(hash_parts) return hashlib.sha256(hash_input.encode()).hexdigest() def _ensure_string_field(self, value: Any, field_name: str, default: str = "") -> str: """ Safely ensure a field is a string, handling various edge cases. Args: value: The value to convert to string field_name: Name of the field for logging purposes default: Default string value if conversion fails Returns: str: A safe string value """ # Handle None/falsy values if value is None or value == "": return default # Handle unexpected list types (the root cause of our Pydantic warning) if isinstance(value, list): if len(value) == 0: log_debug(f"Empty list found for {field_name}, using default: '{default}'") return default elif len(value) == 1: # Single item list, extract the item log_debug(f"Single-item list found for {field_name}, extracting: '{value[0]}'") return str(value[0]) if value[0] is not None else default else: # Multiple items, join them log_debug(f"Multi-item list found for {field_name}, joining: {value}") return " | ".join(str(item) for item in value if item is not None) # Handle other unexpected types if not isinstance(value, str): log_debug(f"Non-string type {type(value)} found for {field_name}, converting: '{value}'") try: return str(value) except Exception as e: log_warning(f"Failed to convert {field_name} to string: {e}, using default") return default # Already a string, return as-is return value def _content_row_to_content(self, content_row: KnowledgeRow) -> Content: """Convert a KnowledgeRow to a Content object.""" return Content( id=content_row.id, name=content_row.name, description=content_row.description, metadata=content_row.metadata, file_type=content_row.type, size=content_row.size, status=ContentStatus(content_row.status) if content_row.status else None, status_message=content_row.status_message, created_at=content_row.created_at, updated_at=content_row.updated_at if content_row.updated_at else content_row.created_at, external_id=content_row.external_id, ) def _build_knowledge_row(self, content: Content) -> KnowledgeRow: """Build a KnowledgeRow from a Content object.""" created_at = content.created_at if content.created_at else int(time.time()) updated_at = content.updated_at if content.updated_at else int(time.time()) file_type = ( content.file_type if content.file_type else content.file_data.type if content.file_data and content.file_data.type else None ) return KnowledgeRow( id=content.id, name=self._ensure_string_field(content.name, "content.name", default=""), description=self._ensure_string_field(content.description, "content.description", default=""), metadata=content.metadata, type=file_type, size=content.size if content.size else len(content.file_data.content) if content.file_data and content.file_data.content else None, linked_to=self.name if self.name else "", access_count=0, status=content.status if content.status else ContentStatus.PROCESSING, status_message=self._ensure_string_field(content.status_message, "content.status_message", default=""), created_at=created_at, updated_at=updated_at, ) def _parse_content_status(self, status_str: Optional[str]) -> ContentStatus: """Parse status string to ContentStatus enum.""" try: return ContentStatus(status_str.lower()) if status_str else ContentStatus.PROCESSING except ValueError: if status_str and "failed" in status_str.lower(): return ContentStatus.FAILED elif status_str and "completed" in status_str.lower(): return ContentStatus.COMPLETED return ContentStatus.PROCESSING # ========================================== # PRIVATE - DATABASE METHODS # ========================================== async def _ainsert_contents_db(self, content: Content): if self.contents_db: content_row = self._build_knowledge_row(content) if isinstance(self.contents_db, AsyncBaseDb): await self.contents_db.upsert_knowledge_content(knowledge_row=content_row) else: self.contents_db.upsert_knowledge_content(knowledge_row=content_row) def _insert_contents_db(self, content: Content): """Synchronously add content to contents database.""" if self.contents_db: if isinstance(self.contents_db, AsyncBaseDb): raise ValueError( "_insert_contents_db() is not supported with an async DB. Please use ainsert() with AsyncDb." ) content_row = self._build_knowledge_row(content) self.contents_db.upsert_knowledge_content(knowledge_row=content_row) # --- Vector DB Insert Helpers --- async def _ahandle_vector_db_insert(self, content: Content, read_documents, upsert): from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if not self.vector_db: log_error("No vector database configured") content.status = ContentStatus.FAILED content.status_message = "No vector database configured" await self._aupdate_content(content) return if self.vector_db.upsert_available() and upsert: try: await self.vector_db.async_upsert(content.content_hash, read_documents, content.metadata) # type: ignore[arg-type] except Exception as e: log_error(f"Error upserting document: {e}") content.status = ContentStatus.FAILED content.status_message = "Could not upsert embedding" await self._aupdate_content(content) return else: try: await self.vector_db.async_insert( content.content_hash, # type: ignore[arg-type] documents=read_documents, filters=content.metadata, # type: ignore[arg-type] ) except Exception as e: log_error(f"Error inserting document: {e}") content.status = ContentStatus.FAILED content.status_message = "Could not insert embedding" await self._aupdate_content(content) return content.status = ContentStatus.COMPLETED await self._aupdate_content(content) def _handle_vector_db_insert(self, content: Content, read_documents, upsert): """Synchronously handle vector database insertion.""" from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if not self.vector_db: log_error("No vector database configured") content.status = ContentStatus.FAILED content.status_message = "No vector database configured" self._update_content(content) return if self.vector_db.upsert_available() and upsert: try: self.vector_db.upsert(content.content_hash, read_documents, content.metadata) # type: ignore[arg-type] except Exception as e: log_error(f"Error upserting document: {e}") content.status = ContentStatus.FAILED content.status_message = "Could not upsert embedding" self._update_content(content) return else: try: self.vector_db.insert( content.content_hash, # type: ignore[arg-type] documents=read_documents, filters=content.metadata, # type: ignore[arg-type] ) except Exception as e: log_error(f"Error inserting document: {e}") content.status = ContentStatus.FAILED content.status_message = "Could not insert embedding" self._update_content(content) return content.status = ContentStatus.COMPLETED self._update_content(content) # --- Content Update --- def _update_content(self, content: Content) -> Optional[Dict[str, Any]]: from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) if self.contents_db: if isinstance(self.contents_db, AsyncBaseDb): raise ValueError( "update_content() is not supported with an async DB. Please use aupdate_content() instead." ) if not content.id: log_warning("Content id is required to update Knowledge content") return None # TODO: we shouldn't check for content here, we should trust the upsert method to handle conflicts content_row = self.contents_db.get_knowledge_content(content.id) if content_row is None: log_warning(f"Content row not found for id: {content.id}, cannot update status") return None # Apply safe string handling for updates as well if content.name is not None: content_row.name = self._ensure_string_field(content.name, "content.name", default="") if content.description is not None: content_row.description = self._ensure_string_field( content.description, "content.description", default="" ) if content.metadata is not None: content_row.metadata = merge_user_metadata(content_row.metadata, content.metadata) if content.status is not None: content_row.status = content.status if content.status_message is not None: content_row.status_message = self._ensure_string_field( content.status_message, "content.status_message", default="" ) if content.external_id is not None: content_row.external_id = self._ensure_string_field( content.external_id, "content.external_id", default="" ) content_row.updated_at = int(time.time()) self.contents_db.upsert_knowledge_content(knowledge_row=content_row) if self.vector_db: # Strip _agno from metadata sent to vector_db — only user fields should be searchable user_metadata = strip_agno_metadata(content.metadata) or {} self.vector_db.update_metadata(content_id=content.id, metadata=user_metadata) return content_row.to_dict() else: return None async def _aupdate_content(self, content: Content) -> Optional[Dict[str, Any]]: if self.contents_db: if not content.id: log_warning("Content id is required to update Knowledge content") return None # TODO: we shouldn't check for content here, we should trust the upsert method to handle conflicts if isinstance(self.contents_db, AsyncBaseDb): content_row = await self.contents_db.get_knowledge_content(content.id) else: content_row = self.contents_db.get_knowledge_content(content.id) if content_row is None: log_warning(f"Content row not found for id: {content.id}, cannot update status") return None # Apply safe string handling for updates if content.name is not None: content_row.name = self._ensure_string_field(content.name, "content.name", default="") if content.description is not None: content_row.description = self._ensure_string_field( content.description, "content.description", default="" ) if content.metadata is not None: content_row.metadata = merge_user_metadata(content_row.metadata, content.metadata) if content.status is not None: content_row.status = content.status if content.status_message is not None: content_row.status_message = self._ensure_string_field( content.status_message, "content.status_message", default="" ) if content.external_id is not None: content_row.external_id = self._ensure_string_field( content.external_id, "content.external_id", default="" ) content_row.updated_at = int(time.time()) if isinstance(self.contents_db, AsyncBaseDb): await self.contents_db.upsert_knowledge_content(knowledge_row=content_row) else: self.contents_db.upsert_knowledge_content(knowledge_row=content_row) if self.vector_db: # Strip _agno from metadata sent to vector_db — only user fields should be searchable user_metadata = strip_agno_metadata(content.metadata) or {} self.vector_db.update_metadata(content_id=content.id, metadata=user_metadata) return content_row.to_dict() else: return None # ========================================== # PRIVATE - LIGHTRAG PROCESSING METHODS # ========================================== async def _aprocess_lightrag_content(self, content: Content, content_type: KnowledgeContentOrigin) -> None: from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) await self._ainsert_contents_db(content) if content_type == KnowledgeContentOrigin.PATH: if content.file_data is None: log_warning("No file data provided") if content.path is None: log_error("No path provided for content") return path = Path(content.path) log_info(f"Uploading file to LightRAG from path: {path}") try: # Read the file content from path with open(path, "rb") as f: file_content = f.read() # Get file type from extension or content.file_type file_type = content.file_type or path.suffix if self.vector_db and hasattr(self.vector_db, "insert_file_bytes"): result = await self.vector_db.insert_file_bytes( file_content=file_content, filename=path.name, # Use the original filename with extension content_type=file_type, send_metadata=True, # Enable metadata so server knows the file type ) else: log_error("Vector database does not support file insertion") content.status = ContentStatus.FAILED await self._aupdate_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return except Exception as e: log_error(f"Error uploading file to LightRAG: {e}") content.status = ContentStatus.FAILED content.status_message = f"Could not upload to LightRAG: {str(e)}" await self._aupdate_content(content) return elif content_type == KnowledgeContentOrigin.URL: log_info(f"Uploading file to LightRAG from URL: {content.url}") try: reader = content.reader or self.website_reader if reader is None: log_error("No URL reader available") content.status = ContentStatus.FAILED await self._aupdate_content(content) return reader.chunk = False read_documents = reader.read(content.url, name=content.name) if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id) if not read_documents: log_error("No documents read from URL") content.status = ContentStatus.FAILED await self._aupdate_content(content) return if self.vector_db and hasattr(self.vector_db, "insert_text"): result = await self.vector_db.insert_text( file_source=content.url, text=read_documents[0].content, ) else: log_error("Vector database does not support text insertion") content.status = ContentStatus.FAILED await self._aupdate_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return except Exception as e: log_error(f"Error uploading file to LightRAG: {e}") content.status = ContentStatus.FAILED content.status_message = f"Could not upload to LightRAG: {str(e)}" await self._aupdate_content(content) return elif content_type == KnowledgeContentOrigin.CONTENT: filename = ( content.file_data.filename if content.file_data and content.file_data.filename else "uploaded_file" ) log_info(f"Uploading file to LightRAG: {filename}") # Use the content from file_data if content.file_data and content.file_data.content: if self.vector_db and hasattr(self.vector_db, "insert_file_bytes"): result = await self.vector_db.insert_file_bytes( file_content=content.file_data.content, filename=filename, content_type=content.file_data.type, send_metadata=True, # Enable metadata so server knows the file type ) else: log_error("Vector database does not support file insertion") content.status = ContentStatus.FAILED await self._aupdate_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED await self._aupdate_content(content) else: log_warning(f"No file data available for LightRAG upload: {content.name}") return elif content_type == KnowledgeContentOrigin.TOPIC: log_info(f"Uploading file to LightRAG: {content.name}") if content.reader is None: log_error("No reader available for topic content") content.status = ContentStatus.FAILED await self._aupdate_content(content) return if not content.topics: log_error("No topics available for content") content.status = ContentStatus.FAILED await self._aupdate_content(content) return read_documents = content.reader.read(content.topics) if len(read_documents) > 0: if self.vector_db and hasattr(self.vector_db, "insert_text"): result = await self.vector_db.insert_text( file_source=content.topics[0], text=read_documents[0].content, ) else: log_error("Vector database does not support text insertion") content.status = ContentStatus.FAILED await self._aupdate_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED await self._aupdate_content(content) return else: log_warning(f"No documents found for LightRAG upload: {content.name}") return def _process_lightrag_content(self, content: Content, content_type: KnowledgeContentOrigin) -> None: """Synchronously process LightRAG content. Uses asyncio.run() only for LightRAG-specific async methods.""" from agno.vectordb import VectorDb self.vector_db = cast(VectorDb, self.vector_db) self._insert_contents_db(content) if content_type == KnowledgeContentOrigin.PATH: if content.file_data is None: log_warning("No file data provided") if content.path is None: log_error("No path provided for content") return path = Path(content.path) log_info(f"Uploading file to LightRAG from path: {path}") try: # Read the file content from path with open(path, "rb") as f: file_content = f.read() # Get file type from extension or content.file_type file_type = content.file_type or path.suffix if self.vector_db and hasattr(self.vector_db, "insert_file_bytes"): # LightRAG only has async methods, use asyncio.run() here result = asyncio.run( self.vector_db.insert_file_bytes( file_content=file_content, filename=path.name, content_type=file_type, send_metadata=True, ) ) else: log_error("Vector database does not support file insertion") content.status = ContentStatus.FAILED self._update_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED self._update_content(content) return except Exception as e: log_error(f"Error uploading file to LightRAG: {e}") content.status = ContentStatus.FAILED content.status_message = f"Could not upload to LightRAG: {str(e)}" self._update_content(content) return elif content_type == KnowledgeContentOrigin.URL: log_info(f"Uploading file to LightRAG from URL: {content.url}") try: reader = content.reader or self.website_reader if reader is None: log_error("No URL reader available") content.status = ContentStatus.FAILED self._update_content(content) return reader.chunk = False read_documents = reader.read(content.url, name=content.name) if not content.id: content.id = generate_id(content.content_hash or "") self._prepare_documents_for_insert(read_documents, content.id) if not read_documents: log_error("No documents read from URL") content.status = ContentStatus.FAILED self._update_content(content) return if self.vector_db and hasattr(self.vector_db, "insert_text"): # LightRAG only has async methods, use asyncio.run() here result = asyncio.run( self.vector_db.insert_text( file_source=content.url, text=read_documents[0].content, ) ) else: log_error("Vector database does not support text insertion") content.status = ContentStatus.FAILED self._update_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED self._update_content(content) return except Exception as e: log_error(f"Error uploading file to LightRAG: {e}") content.status = ContentStatus.FAILED content.status_message = f"Could not upload to LightRAG: {str(e)}" self._update_content(content) return elif content_type == KnowledgeContentOrigin.CONTENT: filename = ( content.file_data.filename if content.file_data and content.file_data.filename else "uploaded_file" ) log_info(f"Uploading file to LightRAG: {filename}") # Use the content from file_data if content.file_data and content.file_data.content: if self.vector_db and hasattr(self.vector_db, "insert_file_bytes"): # LightRAG only has async methods, use asyncio.run() here result = asyncio.run( self.vector_db.insert_file_bytes( file_content=content.file_data.content, filename=filename, content_type=content.file_data.type, send_metadata=True, ) ) else: log_error("Vector database does not support file insertion") content.status = ContentStatus.FAILED self._update_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED self._update_content(content) else: log_warning(f"No file data available for LightRAG upload: {content.name}") return elif content_type == KnowledgeContentOrigin.TOPIC: log_info(f"Uploading file to LightRAG: {content.name}") if content.reader is None: log_error("No reader available for topic content") content.status = ContentStatus.FAILED self._update_content(content) return if not content.topics: log_error("No topics available for content") content.status = ContentStatus.FAILED self._update_content(content) return read_documents = content.reader.read(content.topics) if len(read_documents) > 0: if self.vector_db and hasattr(self.vector_db, "insert_text"): # LightRAG only has async methods, use asyncio.run() here result = asyncio.run( self.vector_db.insert_text( file_source=content.topics[0], text=read_documents[0].content, ) ) else: log_error("Vector database does not support text insertion") content.status = ContentStatus.FAILED self._update_content(content) return content.external_id = result content.status = ContentStatus.COMPLETED self._update_content(content) return else: log_warning(f"No documents found for LightRAG upload: {content.name}") return # ======================================================================== # Protocol Implementation (build_context, get_tools, retrieve) # ======================================================================== # Shared context strings _SEARCH_KNOWLEDGE_INSTRUCTIONS = ( "You have a knowledge base you can search using the search_knowledge_base tool. " "Search before answering questions—don't assume you know the answer. " "For ambiguous questions, search first rather than asking for clarification." ) _AGENTIC_FILTER_INSTRUCTION_TEMPLATE = """ The knowledge base contains documents with these metadata filters: {valid_filters_str}. Always use filters when the user query indicates specific metadata. Examples: 1. If the user asks about a specific person like "Jordan Mitchell", you MUST use the search_knowledge_base tool with the filters parameter set to {{'<valid key like user_id>': '<valid value based on the user query>'}}. 2. If the user asks about a specific document type like "contracts", you MUST use the search_knowledge_base tool with the filters parameter set to {{'document_type': 'contract'}}. 3. If the user asks about a specific location like "documents from New York", you MUST use the search_knowledge_base tool with the filters parameter set to {{'<valid key like location>': 'New York'}}. General Guidelines: - Always analyze the user query to identify relevant metadata. - Use the most specific filter(s) possible to narrow down results. - If multiple filters are relevant, combine them in the filters parameter (e.g., {{'name': 'Jordan Mitchell', 'document_type': 'contract'}}). - Ensure the filter keys match the valid metadata filters: {valid_filters_str}. Make sure to pass the filters as [Dict[str: Any]] to the tool. FOLLOW THIS STRUCTURE STRICTLY. """.strip() def _get_agentic_filter_instructions(self, valid_filters: Set[str]) -> str: """Generate the agentic filter instructions for the given valid filters.""" valid_filters_str = ", ".join(valid_filters) return self._AGENTIC_FILTER_INSTRUCTION_TEMPLATE.format(valid_filters_str=valid_filters_str) def build_context( self, enable_agentic_filters: bool = False, **kwargs, ) -> str: """Build context string for the agent's system prompt. Returns instructions about how to use the search_knowledge_base tool and available filters. Args: enable_agentic_filters: Whether agentic filters are enabled. **kwargs: Additional context (unused). Returns: Context string to add to system prompt. """ context_parts: List[str] = [self._SEARCH_KNOWLEDGE_INSTRUCTIONS] # Add filter instructions if agentic filters are enabled if enable_agentic_filters: valid_filters = self.get_valid_filters() if valid_filters: context_parts.append(self._get_agentic_filter_instructions(valid_filters)) return "<knowledge_base>\n" + "\n".join(context_parts) + "\n</knowledge_base>" async def abuild_context( self, enable_agentic_filters: bool = False, **kwargs, ) -> str: """Async version of build_context. Returns instructions about how to use the search_knowledge_base tool and available filters. Args: enable_agentic_filters: Whether agentic filters are enabled. **kwargs: Additional context (unused). Returns: Context string to add to system prompt. """ context_parts: List[str] = [self._SEARCH_KNOWLEDGE_INSTRUCTIONS] # Add filter instructions if agentic filters are enabled if enable_agentic_filters: valid_filters = await self.aget_valid_filters() if valid_filters: context_parts.append(self._get_agentic_filter_instructions(valid_filters)) return "<knowledge_base>\n" + "\n".join(context_parts) + "\n</knowledge_base>" def get_tools( self, run_response: Optional[Any] = None, run_context: Optional[Any] = None, knowledge_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, async_mode: bool = False, enable_agentic_filters: bool = False, agent: Optional[Any] = None, **kwargs, ) -> List[Any]: """Get tools to expose to the Agent or Team. Returns the search_knowledge_base tool configured for this knowledge base. Args: run_response: The run response object to add references to. run_context: The run context. knowledge_filters: Filters to apply to searches. async_mode: Whether to return async tools. enable_agentic_filters: Whether to enable filter parameter on tool. agent: The Agent or Team instance (for document conversion with references_format). **kwargs: Additional context. Returns: List containing the search tool. """ if enable_agentic_filters: tool = self._create_search_tool_with_filters( run_response=run_response, run_context=run_context, knowledge_filters=knowledge_filters, async_mode=async_mode, agent=agent, ) else: tool = self._create_search_tool( run_response=run_response, run_context=run_context, knowledge_filters=knowledge_filters, async_mode=async_mode, agent=agent, ) return [tool] async def aget_tools( self, run_response: Optional[Any] = None, run_context: Optional[Any] = None, knowledge_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, async_mode: bool = True, enable_agentic_filters: bool = False, agent: Optional[Any] = None, **kwargs, ) -> List[Any]: """Async version of get_tools.""" return self.get_tools( run_response=run_response, run_context=run_context, knowledge_filters=knowledge_filters, async_mode=async_mode, enable_agentic_filters=enable_agentic_filters, agent=agent, **kwargs, ) def _create_search_tool( self, run_response: Optional[Any] = None, run_context: Optional[Any] = None, knowledge_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, async_mode: bool = False, agent: Optional[Any] = None, ) -> Any: """Create the search_knowledge_base tool without filter parameter. Args: agent: Agent or Team instance for custom document conversion. """ from agno.models.message import MessageReferences from agno.tools.function import Function from agno.utils.timer import Timer def search_knowledge_base(query: str) -> str: """Use this function to search the knowledge base for information about a query. Args: query: The query to search for. Returns: str: A string containing the response from the knowledge base. """ retrieval_timer = Timer() retrieval_timer.start() try: docs = self.search(query=query, filters=knowledge_filters) except Exception as e: retrieval_timer.stop() log_warning(f"Knowledge search failed: {e}") return f"Error searching knowledge base: {type(e).__name__}" if run_response is not None and docs: references = MessageReferences( query=query, references=[doc.to_dict() for doc in docs], time=round(retrieval_timer.elapsed, 4), ) if run_response.references is None: run_response.references = [] run_response.references.append(references) retrieval_timer.stop() log_debug(f"Time to get references: {retrieval_timer.elapsed:.4f}s") if not docs: return "No documents found" return self._convert_documents_to_string(docs, agent) async def asearch_knowledge_base(query: str) -> str: """Use this function to search the knowledge base for information about a query asynchronously. Args: query: The query to search for. Returns: str: A string containing the response from the knowledge base. """ retrieval_timer = Timer() retrieval_timer.start() try: docs = await self.asearch(query=query, filters=knowledge_filters) except Exception as e: retrieval_timer.stop() log_warning(f"Knowledge search failed: {e}") return f"Error searching knowledge base: {type(e).__name__}" if run_response is not None and docs: references = MessageReferences( query=query, references=[doc.to_dict() for doc in docs], time=round(retrieval_timer.elapsed, 4), ) if run_response.references is None: run_response.references = [] run_response.references.append(references) retrieval_timer.stop() log_debug(f"Time to get references: {retrieval_timer.elapsed:.4f}s") if not docs: return "No documents found" return self._convert_documents_to_string(docs, agent) if async_mode: return Function.from_callable(asearch_knowledge_base, name="search_knowledge_base") else: return Function.from_callable(search_knowledge_base, name="search_knowledge_base") def _create_search_tool_with_filters( self, run_response: Optional[Any] = None, run_context: Optional[Any] = None, knowledge_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, async_mode: bool = False, agent: Optional[Any] = None, ) -> Any: """Create the search_knowledge_base tool with filter parameter. Args: agent: Agent or Team instance for custom document conversion. """ from agno.models.message import MessageReferences from agno.tools.function import Function from agno.utils.timer import Timer # Import here to avoid circular imports try: from agno.utils.knowledge import get_agentic_or_user_search_filters except ImportError: get_agentic_or_user_search_filters = None # type: ignore[assignment] def search_knowledge_base(query: str, filters: Optional[List[Any]] = None) -> str: """Use this function to search the knowledge base for information about a query. Args: query: The query to search for. filters (optional): The filters to apply to the search. This is a list of KnowledgeFilter objects. Returns: str: A string containing the response from the knowledge base. """ # Merge agentic filters with user-provided filters search_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None if filters and get_agentic_or_user_search_filters is not None: # Handle both KnowledgeFilter objects and plain dictionaries filters_dict: Dict[str, Any] = {} for filt in filters: if isinstance(filt, dict): filters_dict.update(filt) elif hasattr(filt, "key") and hasattr(filt, "value"): filters_dict[filt.key] = filt.value search_filters = get_agentic_or_user_search_filters(filters_dict, knowledge_filters) else: search_filters = knowledge_filters # Validate filters if we have that capability if search_filters: validated_filters, invalid_keys = self.validate_filters(search_filters) if invalid_keys: log_warning(f"Invalid filter keys ignored: {invalid_keys}") search_filters = validated_filters if validated_filters else None retrieval_timer = Timer() retrieval_timer.start() try: docs = self.search(query=query, filters=search_filters) except Exception as e: retrieval_timer.stop() log_warning(f"Knowledge search failed: {e}") return f"Error searching knowledge base: {type(e).__name__}" if run_response is not None and docs: references = MessageReferences( query=query, references=[doc.to_dict() for doc in docs], time=round(retrieval_timer.elapsed, 4), ) if run_response.references is None: run_response.references = [] run_response.references.append(references) retrieval_timer.stop() log_debug(f"Time to get references: {retrieval_timer.elapsed:.4f}s") if not docs: return "No documents found" return self._convert_documents_to_string(docs, agent) async def asearch_knowledge_base(query: str, filters: Optional[List[Any]] = None) -> str: """Use this function to search the knowledge base for information about a query asynchronously. Args: query: The query to search for. filters (optional): The filters to apply to the search. This is a list of KnowledgeFilter objects. Returns: str: A string containing the response from the knowledge base. """ # Merge agentic filters with user-provided filters search_filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None if filters and get_agentic_or_user_search_filters is not None: # Handle both KnowledgeFilter objects and plain dictionaries filters_dict: Dict[str, Any] = {} for filt in filters: if isinstance(filt, dict): filters_dict.update(filt) elif hasattr(filt, "key") and hasattr(filt, "value"): filters_dict[filt.key] = filt.value search_filters = get_agentic_or_user_search_filters(filters_dict, knowledge_filters) else: search_filters = knowledge_filters # Validate filters if we have that capability if search_filters: validated_filters, invalid_keys = await self.avalidate_filters(search_filters) if invalid_keys: log_warning(f"Invalid filter keys ignored: {invalid_keys}") search_filters = validated_filters if validated_filters else None retrieval_timer = Timer() retrieval_timer.start() try: docs = await self.asearch(query=query, filters=search_filters) except Exception as e: retrieval_timer.stop() log_warning(f"Knowledge search failed: {e}") return f"Error searching knowledge base: {type(e).__name__}" if run_response is not None and docs: references = MessageReferences( query=query, references=[doc.to_dict() for doc in docs], time=round(retrieval_timer.elapsed, 4), ) if run_response.references is None: run_response.references = [] run_response.references.append(references) retrieval_timer.stop() log_debug(f"Time to get references: {retrieval_timer.elapsed:.4f}s") if not docs: return "No documents found" return self._convert_documents_to_string(docs, agent) if async_mode: func = Function.from_callable(asearch_knowledge_base, name="search_knowledge_base") else: func = Function.from_callable(search_knowledge_base, name="search_knowledge_base") # Opt out of strict mode since filters use dynamic types that are incompatible with strict mode func.strict = False return func def _convert_documents_to_string( self, docs: List[Document], agent: Optional[Any] = None, ) -> str: """Convert documents to a string representation. Args: docs: List of documents to convert. agent: Optional Agent or Team instance for custom conversion using their references_format. Returns: String representation of documents. """ # If agent (Agent or Team) has a custom converter, use it for proper YAML/JSON formatting if agent is not None and hasattr(agent, "_convert_documents_to_string"): return agent._convert_documents_to_string([doc.to_dict() for doc in docs]) # Default conversion if not docs: return "No documents found" result_parts = [] for doc in docs: if doc.content: result_parts.append(doc.content) return "\n\n---\n\n".join(result_parts) if result_parts else "No content found" def retrieve( self, query: str, max_results: Optional[int] = None, filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, **kwargs, ) -> List[Document]: """Retrieve documents for context injection. Used by the add_knowledge_to_context feature to pre-fetch relevant documents into the user message. Args: query: The query string. max_results: Maximum number of results. filters: Filters to apply. **kwargs: Additional parameters. Returns: List of Document objects. """ return self.search(query=query, max_results=max_results, filters=filters) async def aretrieve( self, query: str, max_results: Optional[int] = None, filters: Optional[Union[Dict[str, Any], List[FilterExpr]]] = None, **kwargs, ) -> List[Document]: """Async version of retrieve. Args: query: The query string. max_results: Maximum number of results. filters: Filters to apply. **kwargs: Additional parameters. Returns: List of Document objects. """ return await self.asearch(query=query, max_results=max_results, filters=filters) # ======================================================================== # Deprecated Methods (for backward compatibility) # ======================================================================== @overload def add_content( self, *, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, reader: Optional[Reader] = None, auth: Optional[ContentAuth] = None, ) -> None: ... @overload def add_content(self, *args, **kwargs) -> None: ... def add_content( self, name: Optional[str] = None, description: Optional[str] = None, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, topics: Optional[List[str]] = None, remote_content: Optional[RemoteContent] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, auth: Optional[ContentAuth] = None, ) -> None: """ DEPRECATED: Use `insert()` instead. This method will be removed in a future version. Synchronously insert content into the knowledge base. This is a backward-compatible wrapper for the `insert()` method. Please migrate your code to use `insert()` instead. """ return self.insert( name=name, description=description, path=path, url=url, text_content=text_content, metadata=metadata, topics=topics, remote_content=remote_content, reader=reader, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, auth=auth, ) @overload async def add_content_async( self, *, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, str]] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, reader: Optional[Reader] = None, auth: Optional[ContentAuth] = None, ) -> None: ... @overload async def add_content_async(self, *args, **kwargs) -> None: ... async def add_content_async( self, name: Optional[str] = None, description: Optional[str] = None, path: Optional[str] = None, url: Optional[str] = None, text_content: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, topics: Optional[List[str]] = None, remote_content: Optional[RemoteContent] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, auth: Optional[ContentAuth] = None, ) -> None: """ DEPRECATED: Use `ainsert()` instead. This method will be removed in a future version. Asynchronously insert content into the knowledge base. This is a backward-compatible wrapper for the `ainsert()` method. Please migrate your code to use `ainsert()` instead. """ return await self.ainsert( name=name, description=description, path=path, url=url, text_content=text_content, metadata=metadata, topics=topics, remote_content=remote_content, reader=reader, include=include, exclude=exclude, upsert=upsert, skip_if_exists=skip_if_exists, auth=auth, ) @overload async def add_contents_async(self, contents: List[ContentDict]) -> None: ... @overload async def add_contents_async( self, *, paths: Optional[List[str]] = None, urls: Optional[List[str]] = None, metadata: Optional[Dict[str, str]] = None, topics: Optional[List[str]] = None, text_contents: Optional[List[str]] = None, reader: Optional[Reader] = None, include: Optional[List[str]] = None, exclude: Optional[List[str]] = None, upsert: bool = True, skip_if_exists: bool = False, remote_content: Optional[RemoteContent] = None, ) -> None: ... async def add_contents_async(self, *args, **kwargs) -> None: """ DEPRECATED: Use `ainsert_many()` instead. This method will be removed in a future version. Asynchronously insert multiple content items into the knowledge base. This is a backward-compatible wrapper for the `ainsert_many()` method. Please migrate your code to use `ainsert_many()` instead. """ return await self.ainsert_many(*args, **kwargs)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/knowledge.py", "license": "Apache License 2.0", "lines": 2991, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/arxiv_reader.py
import asyncio from typing import List, Optional from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType try: import arxiv # noqa: F401 except ImportError: raise ImportError("The `arxiv` package is not installed. Please install it via `pip install arxiv`.") class ArxivReader(Reader): sort_by: arxiv.SortCriterion = arxiv.SortCriterion.Relevance @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Arxiv readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.TOPIC] def __init__( self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), sort_by: arxiv.SortCriterion = arxiv.SortCriterion.Relevance, **kwargs, ) -> None: super().__init__(chunking_strategy=chunking_strategy, **kwargs) # ArxivReader-specific attributes self.sort_by = sort_by def read(self, query: str) -> List[Document]: """ Search a query from arXiv database This function gets the top_k articles based on a user's query, sorted by relevance from arxiv @param query: @return: List of documents """ documents = [] search = arxiv.Search(query=query, max_results=self.max_results, sort_by=self.sort_by) for result in search.results(): links = ", ".join([x.href for x in result.links]) documents.append( Document( name=result.title, id=result.title, meta_data={"pdf_url": str(result.pdf_url), "article_links": links}, content=result.summary, ) ) return documents async def async_read(self, query: str) -> List[Document]: """ Search a query from arXiv database asynchronously This function gets the top_k articles based on a user's query, sorted by relevance from arxiv @param query: Search query string @return: List of documents """ return await asyncio.to_thread(self.read, query)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/arxiv_reader.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
agno-agi/agno:libs/agno/agno/knowledge/reader/base.py
import asyncio from dataclasses import dataclass, field from typing import Any, List, Optional from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyFactory, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.types import ContentType @dataclass class Reader: """Base class for reading documents""" chunk: bool = True chunk_size: int = 5000 separators: List[str] = field(default_factory=lambda: ["\n", "\n\n", "\r", "\r\n", "\n\r", "\t", " ", " "]) chunking_strategy: Optional[ChunkingStrategy] = None name: Optional[str] = None description: Optional[str] = None max_results: int = 5 # Maximum number of results to return (useful for search-based readers) encoding: Optional[str] = None def __init__( self, chunk: bool = True, chunk_size: int = 5000, separators: Optional[List[str]] = None, chunking_strategy: Optional[ChunkingStrategy] = None, name: Optional[str] = None, description: Optional[str] = None, max_results: int = 5, encoding: Optional[str] = None, **kwargs, ) -> None: self.chunk = chunk self.chunk_size = chunk_size self.separators = ( separators if separators is not None else ["\n", "\n\n", "\r", "\r\n", "\n\r", "\t", " ", " "] ) self.chunking_strategy = chunking_strategy self.name = name self.description = description self.max_results = max_results self.encoding = encoding def set_chunking_strategy_from_string( self, strategy_name: str, chunk_size: Optional[int] = None, overlap: Optional[int] = None, **kwargs ) -> None: """Set the chunking strategy from a string name.""" try: strategy_type = ChunkingStrategyType.from_string(strategy_name) self.chunking_strategy = ChunkingStrategyFactory.create_strategy( strategy_type, chunk_size=chunk_size, overlap=overlap, **kwargs ) except ValueError as e: raise ValueError(f"Failed to set chunking strategy: {e}") def read(self, obj: Any, name: Optional[str] = None, password: Optional[str] = None) -> List[Document]: raise NotImplementedError async def async_read(self, obj: Any, name: Optional[str] = None, password: Optional[str] = None) -> List[Document]: raise NotImplementedError @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: raise NotImplementedError @classmethod def get_supported_content_types(cls) -> List[ContentType]: raise NotImplementedError def chunk_document(self, document: Document) -> List[Document]: if self.chunking_strategy is None: self.chunking_strategy = FixedSizeChunking(chunk_size=self.chunk_size) return self.chunking_strategy.chunk(document) async def achunk_document(self, document: Document) -> List[Document]: """Async version of chunk_document.""" if self.chunking_strategy is None: self.chunking_strategy = FixedSizeChunking(chunk_size=self.chunk_size) return await self.chunking_strategy.achunk(document) async def chunk_documents_async(self, documents: List[Document]) -> List[Document]: """ Asynchronously chunk a list of documents. Args: documents: List of documents to be chunked. Returns: A flattened list of chunked documents. """ # Process chunking in parallel for all documents chunked_lists = await asyncio.gather(*[self.achunk_document(doc) for doc in documents]) # Flatten the result return [chunk for sublist in chunked_lists for chunk in sublist]
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/base.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/csv_reader.py
import asyncio import csv import io from pathlib import Path from typing import IO, Any, List, Optional, Union from uuid import uuid4 try: import aiofiles except ImportError: raise ImportError("`aiofiles` not installed. Please install it with `pip install aiofiles`") from agno.knowledge.chunking.row import RowChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.reader.utils import stringify_cell_value from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error class CSVReader(Reader): """Reader for CSV files. Converts CSV files to documents with optional chunking support. For Excel files (.xlsx, .xls), use ExcelReader instead. Args: chunking_strategy: Strategy for chunking documents. Default is RowChunking. **kwargs: Additional arguments passed to base Reader. Example: ```python from agno.knowledge.reader.csv_reader import CSVReader reader = CSVReader() docs = reader.read("data.csv") # Custom delimiter docs = reader.read("data.tsv", delimiter="\\t") ``` """ def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = RowChunking(), **kwargs): super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for CSV readers.""" return [ ChunkingStrategyType.ROW_CHUNKER, ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: """Get the list of supported content types.""" return [ContentType.CSV] def read( self, file: Union[Path, IO[Any]], delimiter: str = ",", quotechar: str = '"', name: Optional[str] = None ) -> List[Document]: """Read a CSV file and return a list of documents. Args: file: Path to CSV file or file-like object. delimiter: CSV field delimiter. Default is comma. quotechar: CSV quote character. Default is double quote. name: Optional name override for the document. Returns: List of Document objects. Raises: FileNotFoundError: If the file path doesn't exist. """ try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading: {file}") csv_name = name or file.stem file_content: Union[io.TextIOWrapper, io.StringIO] = file.open( newline="", mode="r", encoding=self.encoding or "utf-8" ) else: log_debug(f"Reading retrieved file: {getattr(file, 'name', 'BytesIO')}") csv_name = name or getattr(file, "name", "csv_file").split(".")[0] file.seek(0) file_content = io.StringIO(file.read().decode(self.encoding or "utf-8")) csv_lines: List[str] = [] with file_content as csvfile: csv_reader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar) for row in csv_reader: # Normalize line endings in CSV cells to preserve row integrity csv_lines.append(", ".join(stringify_cell_value(cell) for cell in row)) documents = [ Document( name=csv_name, id=str(uuid4()), content="\n".join(csv_lines), ) ] if self.chunk: chunked_documents = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents return documents except FileNotFoundError: raise except UnicodeDecodeError as e: file_desc = getattr(file, "name", str(file)) if isinstance(file, IO) else file log_error(f"Encoding error reading {file_desc}: {e}. Try specifying a different encoding.") return [] except Exception as e: file_desc = getattr(file, "name", str(file)) if isinstance(file, IO) else file log_error(f"Error reading {file_desc}: {e}") return [] async def async_read( self, file: Union[Path, IO[Any]], delimiter: str = ",", quotechar: str = '"', page_size: int = 1000, name: Optional[str] = None, ) -> List[Document]: """Read a CSV file asynchronously, processing batches of rows concurrently. Args: file: Path to CSV file or file-like object. delimiter: CSV field delimiter. Default is comma. quotechar: CSV quote character. Default is double quote. page_size: Number of rows per page for large files. name: Optional name override for the document. Returns: List of Document objects. Raises: FileNotFoundError: If the file path doesn't exist. """ try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading async: {file}") async with aiofiles.open(file, mode="r", encoding=self.encoding or "utf-8", newline="") as file_content: content = await file_content.read() file_content_io = io.StringIO(content) csv_name = name or file.stem else: log_debug(f"Reading retrieved file async: {getattr(file, 'name', 'BytesIO')}") file.seek(0) file_content_io = io.StringIO(file.read().decode(self.encoding or "utf-8")) csv_name = name or getattr(file, "name", "csv_file").split(".")[0] file_content_io.seek(0) csv_reader = csv.reader(file_content_io, delimiter=delimiter, quotechar=quotechar) rows = list(csv_reader) total_rows = len(rows) if total_rows <= 10: # Small files: single document csv_content = " ".join(", ".join(stringify_cell_value(cell) for cell in row) for row in rows) documents = [ Document( name=csv_name, id=str(uuid4()), content=csv_content, ) ] else: # Large files: paginate and process in parallel pages = [] for i in range(0, total_rows, page_size): pages.append(rows[i : i + page_size]) async def _process_page(page_number: int, page_rows: List[List[str]]) -> Document: """Process a page of rows into a document.""" start_row = (page_number - 1) * page_size + 1 page_content = " ".join(", ".join(stringify_cell_value(cell) for cell in row) for row in page_rows) return Document( name=csv_name, id=str(uuid4()), meta_data={"page": page_number, "start_row": start_row, "rows": len(page_rows)}, content=page_content, ) documents = await asyncio.gather( *[_process_page(page_number, page) for page_number, page in enumerate(pages, start=1)] ) if self.chunk: documents = await self.chunk_documents_async(documents) return documents except FileNotFoundError: raise except UnicodeDecodeError as e: file_desc = getattr(file, "name", str(file)) if isinstance(file, IO) else file log_error(f"Encoding error reading {file_desc}: {e}. Try specifying a different encoding.") return [] except Exception as e: file_desc = getattr(file, "name", str(file)) if isinstance(file, IO) else file log_error(f"Error reading {file_desc}: {e}") return []
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/csv_reader.py", "license": "Apache License 2.0", "lines": 186, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/docx_reader.py
import asyncio from pathlib import Path from typing import IO, Any, List, Optional, Union from uuid import uuid4 from agno.knowledge.chunking.document import DocumentChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error try: from docx import Document as DocxDocument # type: ignore except ImportError: raise ImportError("The `python-docx` package is not installed. Please install it via `pip install python-docx`.") class DocxReader(Reader): """Reader for Doc/Docx files""" def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = DocumentChunking(), **kwargs): super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for DOCX readers.""" return [ ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.DOCX, ContentType.DOC] def read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: """Read a docx file and return a list of documents""" try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading: {file}") docx_document = DocxDocument(str(file)) doc_name = name or file.stem else: log_debug(f"Reading uploaded file: {getattr(file, 'name', 'BytesIO')}") docx_document = DocxDocument(file) doc_name = name or getattr(file, "name", "docx_file").split(".")[0] doc_content = "\n\n".join([para.text for para in docx_document.paragraphs]) documents = [ Document( name=doc_name, id=str(uuid4()), content=doc_content, ) ] if self.chunk: chunked_documents = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents return documents except Exception as e: log_error(f"Error reading file: {e}") return [] async def async_read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: """Asynchronously read a docx file and return a list of documents""" try: return await asyncio.to_thread(self.read, file, name) except Exception as e: log_error(f"Error reading file asynchronously: {e}") return []
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/docx_reader.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/firecrawl_reader.py
import asyncio from dataclasses import dataclass from typing import Dict, List, Literal, Optional from agno.knowledge.chunking.semantic import SemanticChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, logger try: from firecrawl import FirecrawlApp # type: ignore[attr-defined] except ImportError: raise ImportError("The `firecrawl` package is not installed. Please install it via `pip install firecrawl-py`.") @dataclass class FirecrawlReader(Reader): api_key: Optional[str] = None params: Optional[Dict] = None mode: Literal["scrape", "crawl"] = "scrape" def __init__( self, api_key: Optional[str] = None, params: Optional[Dict] = None, mode: Literal["scrape", "crawl"] = "scrape", chunk: bool = True, chunk_size: int = 5000, chunking_strategy: Optional[ChunkingStrategy] = SemanticChunking(), name: Optional[str] = None, description: Optional[str] = None, ) -> None: # Initialise base Reader (handles chunk_size / strategy) super().__init__( chunk=chunk, chunk_size=chunk_size, chunking_strategy=chunking_strategy, name=name, description=description ) # Firecrawl-specific attributes self.api_key = api_key self.params = params self.mode = mode @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Firecrawl readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.URL] def scrape(self, url: str, name: Optional[str] = None) -> List[Document]: """ Scrapes a website and returns a list of documents. Args: url: The URL of the website to scrape Returns: A list of documents """ log_debug(f"Scraping: {url}") app = FirecrawlApp(api_key=self.api_key) if self.params: scraped_data = app.scrape_url(url, **self.params) else: scraped_data = app.scrape_url(url) if isinstance(scraped_data, dict): content = scraped_data.get("markdown", "") else: content = getattr(scraped_data, "markdown", "") # Debug logging log_debug(f"Received content type: {type(content)}") log_debug(f"Content empty: {not bool(content)}") # Ensure content is a string if content is None: content = "" # or you could use metadata to create a meaningful message logger.warning(f"No content received for URL: {url}") documents = [] if self.chunk and content: # Only chunk if there's content documents.extend(self.chunk_document(Document(name=name or url, id=url, content=content))) else: documents.append(Document(name=name or url, id=url, content=content)) return documents async def async_scrape(self, url: str, name: Optional[str] = None) -> List[Document]: """ Asynchronously scrapes a website and returns a list of documents. Args: url: The URL of the website to scrape Returns: A list of documents """ log_debug(f"Async scraping: {url}") # Use asyncio.to_thread to run the synchronous scrape in a thread return await asyncio.to_thread(self.scrape, url, name) def crawl(self, url: str, name: Optional[str] = None) -> List[Document]: """ Crawls a website and returns a list of documents. Args: url: The URL of the website to crawl Returns: A list of documents """ log_debug(f"Crawling: {url}") app = FirecrawlApp(api_key=self.api_key) if self.params: crawl_result = app.crawl_url(url, **self.params) else: crawl_result = app.crawl_url(url) documents = [] if isinstance(crawl_result, dict): results_data = crawl_result.get("data", []) else: results_data = getattr(crawl_result, "data", []) for result in results_data: # Get markdown content, default to empty string if not found if isinstance(result, dict): content = result.get("markdown", "") else: content = getattr(result, "markdown", "") if content: # Only create document if content exists if self.chunk: documents.extend(self.chunk_document(Document(name=name or url, id=url, content=content))) else: documents.append(Document(name=name or url, id=url, content=content)) return documents async def async_crawl(self, url: str, name: Optional[str] = None) -> List[Document]: """ Asynchronously crawls a website and returns a list of documents. Args: url: The URL of the website to crawl Returns: A list of documents """ log_debug(f"Async crawling: {url}") # Use asyncio.to_thread to run the synchronous crawl in a thread return await asyncio.to_thread(self.crawl, url, name) def read(self, url: str, name: Optional[str] = None) -> List[Document]: """ Reads from a URL based on the mode setting. Args: url: The URL of the website to process Returns: A list of documents """ if self.mode == "scrape": return self.scrape(url, name) elif self.mode == "crawl": return self.crawl(url, name) else: raise NotImplementedError(f"Mode {self.mode} not implemented") async def async_read(self, url: str, name: Optional[str] = None) -> List[Document]: """ Asynchronously reads from a URL based on the mode setting. Args: url: The URL of the website to process Returns: A list of documents """ if self.mode == "scrape": return await self.async_scrape(url, name) elif self.mode == "crawl": return await self.async_crawl(url, name) else: raise NotImplementedError(f"Mode {self.mode} not implemented")
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/firecrawl_reader.py", "license": "Apache License 2.0", "lines": 163, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/json_reader.py
import asyncio import json from pathlib import Path from typing import IO, Any, List, Optional, Union from uuid import uuid4 from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error class JSONReader(Reader): """Reader for JSON files""" chunk: bool = False def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), **kwargs): super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for JSON readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.JSON] def read(self, path: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: try: if isinstance(path, Path): if not path.exists(): raise FileNotFoundError(f"Could not find file: {path}") log_debug(f"Reading: {path}") json_name = name or path.stem json_contents = json.loads(path.read_text(encoding=self.encoding or "utf-8")) elif hasattr(path, "seek") and hasattr(path, "read"): log_debug(f"Reading uploaded file: {getattr(path, 'name', 'BytesIO')}") json_name = name or getattr(path, "name", "json_file").split(".")[0] path.seek(0) json_contents = json.load(path) else: raise ValueError("Unsupported file type. Must be Path or file-like object.") if isinstance(json_contents, dict): json_contents = [json_contents] documents = [ Document( name=json_name, id=str(uuid4()), meta_data={"page": page_number}, content=json.dumps(content), ) for page_number, content in enumerate(json_contents, start=1) ] if self.chunk: chunked_documents = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents return documents except (FileNotFoundError, ValueError, json.JSONDecodeError): raise except Exception as e: log_error(f"Error reading: {path}: {e}") raise async def async_read(self, path: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: """Asynchronously read JSON files.""" return await asyncio.to_thread(self.read, path, name)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/json_reader.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/markdown_reader.py
import asyncio import uuid from pathlib import Path from typing import IO, Any, List, Optional, Union from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error, log_warning DEFAULT_CHUNKER_STRATEGY: ChunkingStrategy # Try to import MarkdownChunking, fallback to FixedSizeChunking if not available try: from agno.knowledge.chunking.markdown import MarkdownChunking DEFAULT_CHUNKER_STRATEGY = MarkdownChunking() MARKDOWN_CHUNKER_AVAILABLE = True except ImportError: from agno.knowledge.chunking.fixed import FixedSizeChunking DEFAULT_CHUNKER_STRATEGY = FixedSizeChunking() MARKDOWN_CHUNKER_AVAILABLE = False class MarkdownReader(Reader): """Reader for Markdown files""" @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Markdown readers.""" strategies = [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ] # Only include MarkdownChunking if it's available if MARKDOWN_CHUNKER_AVAILABLE: strategies.insert(0, ChunkingStrategyType.MARKDOWN_CHUNKER) return strategies @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.MARKDOWN] def __init__( self, chunking_strategy: Optional[ChunkingStrategy] = None, name: Optional[str] = None, description: Optional[str] = None, ) -> None: # Use the default chunking strategy if none provided if chunking_strategy is None: chunking_strategy = DEFAULT_CHUNKER_STRATEGY super().__init__(chunking_strategy=chunking_strategy, name=name, description=description) def read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading: {file}") file_name = name or file.stem file_contents = file.read_text(encoding=self.encoding or "utf-8") else: log_debug(f"Reading uploaded file: {getattr(file, 'name', 'BytesIO')}") file_name = name or getattr(file, "name", "file").split(".")[0] file.seek(0) file_contents = file.read().decode(self.encoding or "utf-8") documents = [Document(name=file_name, id=str(uuid.uuid4()), content=file_contents)] if self.chunk: chunked_documents = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents return documents except Exception as e: log_error(f"Error reading: {file}: {e}") return [] async def async_read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading asynchronously: {file}") file_name = name or file.stem try: import aiofiles async with aiofiles.open(file, "r", encoding=self.encoding or "utf-8") as f: file_contents = await f.read() except ImportError: log_warning("aiofiles not installed, using synchronous file I/O") file_contents = file.read_text(encoding=self.encoding or "utf-8") else: log_debug(f"Reading uploaded file asynchronously: {getattr(file, 'name', 'BytesIO')}") file_name = name or getattr(file, "name", "file").split(".")[0] file.seek(0) file_contents = file.read().decode(self.encoding or "utf-8") document = Document( name=file_name, id=str(uuid.uuid4()), content=file_contents, ) if self.chunk: return await self._async_chunk_document(document) return [document] except Exception as e: log_error(f"Error reading asynchronously: {file}: {e}") return [] async def _async_chunk_document(self, document: Document) -> List[Document]: if not self.chunk or not document: return [document] async def process_chunk(chunk_doc: Document) -> Document: return chunk_doc chunked_documents = self.chunk_document(document) if not chunked_documents: return [document] tasks = [process_chunk(chunk_doc) for chunk_doc in chunked_documents] return await asyncio.gather(*tasks)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/markdown_reader.py", "license": "Apache License 2.0", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/pdf_reader.py
import asyncio import re from pathlib import Path from typing import IO, Any, List, Optional, Tuple, Union from uuid import uuid4 from agno.knowledge.chunking.document import DocumentChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error try: from pypdf import PdfReader as DocumentReader # noqa: F401 from pypdf.errors import PdfStreamError except ImportError: raise ImportError("`pypdf` not installed. Please install it via `pip install pypdf`.") PAGE_START_NUMBERING_FORMAT_DEFAULT = "<start page {page_nr}>" PAGE_END_NUMBERING_FORMAT_DEFAULT = "<end page {page_nr}>" PAGE_NUMBERING_CORRECTNESS_RATIO_FOR_REMOVAL = 0.4 def _sanitize_pdf_text(text: str) -> str: """Normalize fragmented PDF text while preserving paragraph boundaries. PDF text extraction via pypdf often produces fragmented output where each word appears on its own line, especially for multi-column layouts or certain PDF generators. This function joins those broken lines into flowing text while keeping intentional paragraph breaks (double newlines) intact. Note: Structured content like code blocks or tables with meaningful whitespace may lose formatting. Use ``sanitize_content=False`` on the reader to disable. """ # Collapse word-per-line PDF artifacts: \n<whitespace>\n is a typical extraction artifact, # not an intentional paragraph break (which is \n\n with no whitespace between). text = re.sub(r"\n[ \t]+\n", " ", text) # Join single newlines (broken lines from PDF extraction), preserving true paragraph breaks (\n\n) text = re.sub(r"(?<!\n)[ \t]*\n[ \t]*(?!\n)", " ", text) # Collapse runs of spaces/tabs within lines text = re.sub(r"[ \t]{2,}", " ", text) return text.strip() def _ocr_reader(page: Any) -> str: """A single PDF page object.""" try: import rapidocr_onnxruntime as rapidocr except ImportError: raise ImportError( "`rapidocr_onnxruntime` not installed. Please install it via `pip install rapidocr_onnxruntime`." ) ocr = rapidocr.RapidOCR() images_text_list = [] # Extract and process images for image_object in page.images: image_data = image_object.data # Perform OCR on the image ocr_result, elapse = ocr(image_data) # Extract text from OCR result images_text_list += [item[1] for item in ocr_result] if ocr_result else [] return "\n".join(images_text_list) async def _async_ocr_reader(page: Any) -> str: """page: A single PDF page object.""" try: import rapidocr_onnxruntime as rapidocr except ImportError: raise ImportError( "`rapidocr_onnxruntime` not installed. Please install it via `pip install rapidocr_onnxruntime`." ) ocr = rapidocr.RapidOCR() # Process images in parallel async def process_image(image_data: bytes) -> List[str]: ocr_result, _ = ocr(image_data) return [item[1] for item in ocr_result] if ocr_result else [] image_tasks = [process_image(image.data) for image in page.images] images_results = await asyncio.gather(*image_tasks) images_text_list: List = [] for result in images_results: images_text_list.extend(result) images_text = "\n".join(images_text_list) return images_text def _clean_page_numbers( page_content_list: List[str], extra_content: List[str] = [], page_start_numbering_format: str = PAGE_START_NUMBERING_FORMAT_DEFAULT, page_end_numbering_format: str = PAGE_END_NUMBERING_FORMAT_DEFAULT, ) -> Tuple[List[str], Optional[int]]: f""" Identifies and removes or reformats page numbers from a list of PDF page contents, based on the most consistent sequential numbering. Args: page_content_list (List[str]): A list of strings where each string represents the content of a PDF page. extra_content (List[str]): A list of strings where each string will be appended after the main content. Can be used for appending image information. page_start_numbering_format (str): A format string to prepend to the page content, with `{{page_nr}}` as a placeholder for the page number. Defaults to {PAGE_START_NUMBERING_FORMAT_DEFAULT}. Make it an empty string to remove the page number. page_end_numbering_format (str): A format string to append to the page content, with `{{page_nr}}` as a placeholder for the page number. Defaults to {PAGE_END_NUMBERING_FORMAT_DEFAULT}. Make it an empty string to remove the page number. Returns: List[str]: The list of page contents with page numbers removed or reformatted based on the detected sequence. Optional[Int]: The shift for the page numbering. Can be (-2, -1, 0, 1, 2). Notes: - The function scans for page numbers using a regular expression that matches digits at the start or end of a string. - It evaluates several potential starting points for numbering (-2, -1, 0, 1, 2 shifts) to determine the most consistent sequence. - If at least a specified ratio of pages (defined by `PAGE_NUMBERING_CORRECTNESS_RATIO_FOR_REMOVAL`) has correct sequential numbering, the page numbers are processed. - If page numbers are found, the function will add formatted page numbers to each page's content if `page_start_numbering_format` or `page_end_numbering_format` is provided. """ assert len(extra_content) == 0 or len(extra_content) == len(page_content_list), ( "Please provide an equally sized list of extra content if provided." ) # Regex to match potential page numbers at the start or end of a string page_number_regex = re.compile(r"^\s*(\d+)\s*|\s*(\d+)\s*$") def find_page_number(content): match = page_number_regex.search(content) if match: return int(match.group(1) or match.group(2)) return None page_numbers = [find_page_number(content) for content in page_content_list] if all(x is None or x > 5 for x in page_numbers): # This approach won't work reliably for higher page numbers. page_content_list = [ f"\n{page_content_list[i]}\n{extra_content[i]}" if extra_content else page_content_list[i] for i in range(len(page_content_list)) ] return page_content_list, None # Possible range shifts to detect page numbering range_shifts = [-2, -1, 0, 1, 2] best_match, best_correct_count, best_shift = _identify_best_page_sequence(page_numbers, range_shifts) # Check if at least ..% of the pages have correct sequential numbering if best_match and best_correct_count / len(page_numbers) >= PAGE_NUMBERING_CORRECTNESS_RATIO_FOR_REMOVAL: # Remove the page numbers from the content for i, expected_number in enumerate(best_match): page_content_list[i] = re.sub( rf"^\s*{expected_number}\s*|\s*{expected_number}\s*$", "", page_content_list[i] ) page_start = ( page_start_numbering_format.format(page_nr=expected_number) + "\n" if page_start_numbering_format else "" ) page_end = ( "\n" + page_end_numbering_format.format(page_nr=expected_number) if page_end_numbering_format else "" ) extra_info = "\n" + extra_content[i] if extra_content else "" # Add formatted page numbering if configured. page_content_list[i] = page_start + page_content_list[i] + extra_info + page_end else: best_shift = None return page_content_list, best_shift def _identify_best_page_sequence(page_numbers, range_shifts): best_match = None best_shift: Optional[int] = None best_correct_count = 0 for shift in range_shifts: expected_numbers = [i + shift for i in range(len(page_numbers))] # Check if expected number occurs (or that the expected "2" occurs in an incorrectly merged number like 25, # where 2 is the page number and 5 is part of the PDF content). correct_count = sum( 1 for actual, expected in zip(page_numbers, expected_numbers) if actual == expected or str(actual).startswith(str(expected)) or str(actual).endswith(str(expected)) ) if correct_count > best_correct_count: best_correct_count = correct_count best_match = expected_numbers best_shift = shift return best_match, best_correct_count, best_shift class BasePDFReader(Reader): def __init__( self, split_on_pages: bool = True, page_start_numbering_format: Optional[str] = None, page_end_numbering_format: Optional[str] = None, password: Optional[str] = None, sanitize_content: bool = True, chunking_strategy: Optional[ChunkingStrategy] = DocumentChunking(chunk_size=5000), **kwargs, ): if page_start_numbering_format is None: page_start_numbering_format = PAGE_START_NUMBERING_FORMAT_DEFAULT if page_end_numbering_format is None: page_end_numbering_format = PAGE_END_NUMBERING_FORMAT_DEFAULT self.split_on_pages = split_on_pages self.page_start_numbering_format = page_start_numbering_format self.page_end_numbering_format = page_end_numbering_format self.password = password self.sanitize_content = sanitize_content super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for PDF readers.""" return [ ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ] def _build_chunked_documents(self, documents: List[Document]) -> List[Document]: chunked_documents: List[Document] = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents def _get_doc_name(self, pdf_source: Union[str, Path, IO[Any]], name: Optional[str] = None) -> str: """Determines the document name from the source or a provided name.""" if name: return name if isinstance(pdf_source, str): return Path(pdf_source).stem.replace(" ", "_") if isinstance(pdf_source, Path): return pdf_source.stem.replace(" ", "_") return getattr(pdf_source, "name", "pdf_file").split(".")[0].replace(" ", "_") def _decrypt_pdf(self, doc_reader: DocumentReader, doc_name: str, password: Optional[str] = None) -> bool: if not doc_reader.is_encrypted: return True # Use provided password or fall back to instance password # Note: Empty string "" is a valid password for PDFs with blank user password pdf_password = self.password if password is None else password if pdf_password is None: log_error(f'PDF file "{doc_name}" is password protected but no password provided') return False try: decrypted_pdf = doc_reader.decrypt(pdf_password) if decrypted_pdf: log_debug(f'Successfully decrypted PDF file "{doc_name}" with user password') return True else: log_error(f'Failed to decrypt PDF file "{doc_name}": incorrect password') return False except Exception as e: log_error(f'Error decrypting PDF file "{doc_name}": {e}') return False def _create_documents(self, pdf_content: List[str], doc_name: str, use_uuid_for_id: bool, page_number_shift): if self.split_on_pages: shift = page_number_shift if page_number_shift is not None else 1 documents: List[Document] = [] for page_number, page_content in enumerate(pdf_content, start=shift): documents.append( Document( name=doc_name, id=(str(uuid4()) if use_uuid_for_id else f"{doc_name}_{page_number}"), meta_data={"page": page_number}, content=page_content, ) ) else: pdf_content_str = "\n".join(pdf_content) document = Document( name=doc_name, id=str(uuid4()) if use_uuid_for_id else doc_name, meta_data={}, content=pdf_content_str, ) documents = [document] if self.chunk: return self._build_chunked_documents(documents) return documents def _pdf_reader_to_documents( self, doc_reader: DocumentReader, doc_name, read_images=False, use_uuid_for_id=False, ): pdf_content = [] pdf_images_text = [] for page in doc_reader.pages: pdf_content.append(page.extract_text()) if read_images: pdf_images_text.append(_ocr_reader(page)) # Sanitize before page number cleaning so that _clean_page_numbers can insert # its markers without the sanitizer later collapsing their newline delimiters. if self.sanitize_content: pdf_content = [_sanitize_pdf_text(page) for page in pdf_content] pdf_content, shift = _clean_page_numbers( page_content_list=pdf_content, extra_content=pdf_images_text, page_start_numbering_format=self.page_start_numbering_format, page_end_numbering_format=self.page_end_numbering_format, ) return self._create_documents(pdf_content, doc_name, use_uuid_for_id, shift) async def _async_pdf_reader_to_documents( self, doc_reader: DocumentReader, doc_name: str, read_images=False, use_uuid_for_id=False, ): async def _read_pdf_page(page, read_images) -> Tuple[str, str]: # We tried "asyncio.to_thread(page.extract_text)", but it maintains state internally, which leads to issues. page_text = page.extract_text() if read_images: pdf_images_text = await _async_ocr_reader(page) else: pdf_images_text = "" return page_text, pdf_images_text # Process pages in parallel using asyncio.gather pdf_content: List[Tuple[str, str]] = await asyncio.gather( *[_read_pdf_page(page, read_images) for page in doc_reader.pages] ) page_texts = [x[0] for x in pdf_content] if self.sanitize_content: page_texts = [_sanitize_pdf_text(page) for page in page_texts] pdf_content_clean, shift = _clean_page_numbers( page_content_list=page_texts, extra_content=[x[1] for x in pdf_content], page_start_numbering_format=self.page_start_numbering_format, page_end_numbering_format=self.page_end_numbering_format, ) return self._create_documents(pdf_content_clean, doc_name, use_uuid_for_id, shift) class PDFReader(BasePDFReader): """Reader for PDF files""" @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.PDF] def read( self, pdf: Optional[Union[str, Path, IO[Any]]] = None, name: Optional[str] = None, password: Optional[str] = None, ) -> List[Document]: if pdf is None: log_error("No pdf provided") return [] doc_name = self._get_doc_name(pdf, name) log_debug(f"Reading: {doc_name}") try: pdf_reader = DocumentReader(pdf) except PdfStreamError as e: log_error(f"Error reading PDF: {e}") return [] # Handle PDF decryption if not self._decrypt_pdf(pdf_reader, doc_name, password): return [] # Read and chunk return self._pdf_reader_to_documents(pdf_reader, doc_name, use_uuid_for_id=True) async def async_read( self, pdf: Optional[Union[str, Path, IO[Any]]] = None, name: Optional[str] = None, password: Optional[str] = None, ) -> List[Document]: if pdf is None: log_error("No pdf provided") return [] doc_name = self._get_doc_name(pdf, name) log_debug(f"Reading: {doc_name}") try: pdf_reader = DocumentReader(pdf) except PdfStreamError as e: log_error(f"Error reading PDF: {e}") return [] # Handle PDF decryption if not self._decrypt_pdf(pdf_reader, doc_name, password): return [] # Read and chunk. return await self._async_pdf_reader_to_documents(pdf_reader, doc_name, use_uuid_for_id=True) class PDFImageReader(BasePDFReader): """Reader for PDF files with text and images extraction""" def read( self, pdf: Union[str, Path, IO[Any]], name: Optional[str] = None, password: Optional[str] = None ) -> List[Document]: if not pdf: raise ValueError("No pdf provided") doc_name = self._get_doc_name(pdf, name) log_debug(f"Reading: {doc_name}") try: pdf_reader = DocumentReader(pdf) except PdfStreamError as e: log_error(f"Error reading PDF: {e}") return [] # Handle PDF decryption if not self._decrypt_pdf(pdf_reader, doc_name, password): return [] # Read and chunk. return self._pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=True) async def async_read( self, pdf: Union[str, Path, IO[Any]], name: Optional[str] = None, password: Optional[str] = None ) -> List[Document]: if not pdf: raise ValueError("No pdf provided") doc_name = self._get_doc_name(pdf, name) log_debug(f"Reading: {doc_name}") try: pdf_reader = DocumentReader(pdf) except PdfStreamError as e: log_error(f"Error reading PDF: {e}") return [] # Handle PDF decryption if not self._decrypt_pdf(pdf_reader, doc_name, password): return [] # Read and chunk. return await self._async_pdf_reader_to_documents(pdf_reader, doc_name, read_images=True, use_uuid_for_id=True)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/pdf_reader.py", "license": "Apache License 2.0", "lines": 387, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/reader_factory.py
import os from typing import Any, Callable, Dict, List, Optional from agno.knowledge.reader.base import Reader class ReaderFactory: """Factory for creating and managing document readers with lazy loading.""" # Cache for instantiated readers _reader_cache: Dict[str, Reader] = {} # Static metadata for readers - avoids instantiation just to get metadata READER_METADATA: Dict[str, Dict[str, str]] = { "pdf": { "name": "PdfReader", "description": "Processes PDF documents with OCR support for images and text extraction", }, "csv": { "name": "CsvReader", "description": "Parses CSV files with custom delimiter support", }, "excel": { "name": "ExcelReader", "description": "Processes Excel workbooks (.xlsx and .xls) with sheet filtering and row-based chunking", }, "field_labeled_csv": { "name": "FieldLabeledCsvReader", "description": "Converts CSV rows to field-labeled text format for enhanced readability and context", }, "docx": { "name": "DocxReader", "description": "Extracts text content from Microsoft Word documents (.docx and .doc formats)", }, "pptx": { "name": "PptxReader", "description": "Extracts text content from Microsoft PowerPoint presentations (.pptx format)", }, "json": { "name": "JsonReader", "description": "Processes JSON data structures and API responses with nested object handling", }, "markdown": { "name": "MarkdownReader", "description": "Processes Markdown documentation with header-aware chunking and formatting preservation", }, "text": { "name": "TextReader", "description": "Handles plain text files with customizable chunking strategies and encoding detection", }, "website": { "name": "WebsiteReader", "description": "Scrapes and extracts content from web pages with HTML parsing and text cleaning", }, "firecrawl": { "name": "FirecrawlReader", "description": "Advanced web scraping and crawling with JavaScript rendering and structured data extraction", }, "tavily": { "name": "TavilyReader", "description": "Extracts content from URLs using Tavily's Extract API with markdown or text output", }, "youtube": { "name": "YouTubeReader", "description": "Extracts transcripts and metadata from YouTube videos and playlists", }, "arxiv": { "name": "ArxivReader", "description": "Downloads and processes academic papers from ArXiv with PDF parsing and metadata extraction", }, "wikipedia": { "name": "WikipediaReader", "description": "Fetches and processes Wikipedia articles with section-aware chunking and link resolution", }, "web_search": { "name": "WebSearchReader", "description": "Executes web searches and processes results with relevance ranking and content extraction", }, } @classmethod def _get_pdf_reader(cls, **kwargs) -> Reader: """Get PDF reader instance.""" from agno.knowledge.reader.pdf_reader import PDFReader config: Dict[str, Any] = { "name": "PDF Reader", "description": "Processes PDF documents with OCR support for images and text extraction", } config.update(kwargs) return PDFReader(**config) @classmethod def _get_csv_reader(cls, **kwargs) -> Reader: """Get CSV reader instance.""" from agno.knowledge.reader.csv_reader import CSVReader config: Dict[str, Any] = { "name": "CSV Reader", "description": "Parses CSV files with custom delimiter support", } config.update(kwargs) return CSVReader(**config) @classmethod def _get_excel_reader(cls, **kwargs) -> Reader: """Get Excel reader instance.""" from agno.knowledge.reader.excel_reader import ExcelReader config: Dict[str, Any] = { "name": "Excel Reader", "description": "Processes Excel workbooks (.xlsx and .xls) with sheet filtering and row-based chunking", } config.update(kwargs) return ExcelReader(**config) @classmethod def _get_field_labeled_csv_reader(cls, **kwargs) -> Reader: """Get Field Labeled CSV reader instance.""" from agno.knowledge.reader.field_labeled_csv_reader import FieldLabeledCSVReader config: Dict[str, Any] = { "name": "Field Labeled CSV Reader", "description": "Converts CSV rows to field-labeled text format for enhanced readability and context", } config.update(kwargs) return FieldLabeledCSVReader(**config) @classmethod def _get_docx_reader(cls, **kwargs) -> Reader: """Get Docx reader instance.""" from agno.knowledge.reader.docx_reader import DocxReader config: Dict[str, Any] = { "name": "Docx Reader", "description": "Extracts text content from Microsoft Word documents (.docx and .doc formats)", } config.update(kwargs) return DocxReader(**config) @classmethod def _get_pptx_reader(cls, **kwargs) -> Reader: """Get PPTX reader instance.""" from agno.knowledge.reader.pptx_reader import PPTXReader config: Dict[str, Any] = { "name": "PPTX Reader", "description": "Extracts text content from Microsoft PowerPoint presentations (.pptx format)", } config.update(kwargs) return PPTXReader(**config) @classmethod def _get_json_reader(cls, **kwargs) -> Reader: """Get JSON reader instance.""" from agno.knowledge.reader.json_reader import JSONReader config: Dict[str, Any] = { "name": "JSON Reader", "description": "Processes JSON data structures and API responses with nested object handling", } config.update(kwargs) return JSONReader(**config) @classmethod def _get_markdown_reader(cls, **kwargs) -> Reader: """Get Markdown reader instance.""" from agno.knowledge.reader.markdown_reader import MarkdownReader config: Dict[str, Any] = { "name": "Markdown Reader", "description": "Processes Markdown documentation with header-aware chunking and formatting preservation", } config.update(kwargs) return MarkdownReader(**config) @classmethod def _get_text_reader(cls, **kwargs) -> Reader: """Get Text reader instance.""" from agno.knowledge.reader.text_reader import TextReader config: Dict[str, Any] = { "name": "Text Reader", "description": "Handles plain text files with customizable chunking strategies and encoding detection", } config.update(kwargs) return TextReader(**config) @classmethod def _get_website_reader(cls, **kwargs) -> Reader: """Get Website reader instance.""" from agno.knowledge.reader.website_reader import WebsiteReader config: Dict[str, Any] = { "name": "Website Reader", "description": "Scrapes and extracts content from web pages with HTML parsing and text cleaning", } config.update(kwargs) return WebsiteReader(**config) @classmethod def _get_firecrawl_reader(cls, **kwargs) -> Reader: """Get Firecrawl reader instance.""" from agno.knowledge.reader.firecrawl_reader import FirecrawlReader config: Dict[str, Any] = { "api_key": kwargs.get("api_key") or os.getenv("FIRECRAWL_API_KEY"), "mode": "crawl", "name": "Firecrawl Reader", "description": "Advanced web scraping and crawling with JavaScript rendering and structured data extraction", } config.update(kwargs) return FirecrawlReader(**config) @classmethod def _get_tavily_reader(cls, **kwargs) -> Reader: """Get Tavily reader instance.""" from agno.knowledge.reader.tavily_reader import TavilyReader config: Dict[str, Any] = { "api_key": kwargs.get("api_key") or os.getenv("TAVILY_API_KEY"), "extract_format": "markdown", "extract_depth": "basic", "name": "Tavily Reader", "description": "Extracts content from URLs using Tavily's Extract API with markdown or text output", } config.update(kwargs) return TavilyReader(**config) @classmethod def _get_youtube_reader(cls, **kwargs) -> Reader: """Get YouTube reader instance.""" from agno.knowledge.reader.youtube_reader import YouTubeReader config: Dict[str, Any] = { "name": "YouTube Reader", "description": "Extracts transcripts and metadata from YouTube videos and playlists", } config.update(kwargs) return YouTubeReader(**config) @classmethod def _get_arxiv_reader(cls, **kwargs) -> Reader: """Get Arxiv reader instance.""" from agno.knowledge.reader.arxiv_reader import ArxivReader config: Dict[str, Any] = { "name": "Arxiv Reader", "description": "Downloads and processes academic papers from ArXiv with PDF parsing and metadata extraction", } config.update(kwargs) return ArxivReader(**config) @classmethod def _get_wikipedia_reader(cls, **kwargs) -> Reader: """Get Wikipedia reader instance.""" from agno.knowledge.reader.wikipedia_reader import WikipediaReader config: Dict[str, Any] = { "name": "Wikipedia Reader", "description": "Fetches and processes Wikipedia articles with section-aware chunking and link resolution", } config.update(kwargs) return WikipediaReader(**config) @classmethod def _get_web_search_reader(cls, **kwargs) -> Reader: """Get Web Search reader instance.""" from agno.knowledge.reader.web_search_reader import WebSearchReader config: Dict[str, Any] = { "name": "Web Search Reader", "description": "Executes web searches and processes results with relevance ranking and content extraction", } config.update(kwargs) return WebSearchReader(**config) @classmethod def _get_reader_method(cls, reader_key: str) -> Callable[[], Reader]: """Get the appropriate reader method for the given key.""" method_name = f"_get_{reader_key}_reader" if not hasattr(cls, method_name): raise ValueError(f"Unknown reader: {reader_key}") return getattr(cls, method_name) @classmethod def get_reader_class(cls, reader_key: str) -> type: """Get the reader CLASS without instantiation. This is useful for accessing class methods like get_supported_chunking_strategies() without the overhead of creating an instance. Args: reader_key: The reader key (e.g., 'pdf', 'csv', 'markdown') Returns: The reader class (not an instance) Raises: ValueError: If the reader key is unknown ImportError: If the reader's dependencies are not installed """ # Map reader keys to their import paths reader_class_map: Dict[str, tuple] = { "pdf": ("agno.knowledge.reader.pdf_reader", "PDFReader"), "csv": ("agno.knowledge.reader.csv_reader", "CSVReader"), "excel": ("agno.knowledge.reader.excel_reader", "ExcelReader"), "field_labeled_csv": ("agno.knowledge.reader.field_labeled_csv_reader", "FieldLabeledCSVReader"), "docx": ("agno.knowledge.reader.docx_reader", "DocxReader"), "pptx": ("agno.knowledge.reader.pptx_reader", "PPTXReader"), "json": ("agno.knowledge.reader.json_reader", "JSONReader"), "markdown": ("agno.knowledge.reader.markdown_reader", "MarkdownReader"), "text": ("agno.knowledge.reader.text_reader", "TextReader"), "website": ("agno.knowledge.reader.website_reader", "WebsiteReader"), "firecrawl": ("agno.knowledge.reader.firecrawl_reader", "FirecrawlReader"), "tavily": ("agno.knowledge.reader.tavily_reader", "TavilyReader"), "youtube": ("agno.knowledge.reader.youtube_reader", "YouTubeReader"), "arxiv": ("agno.knowledge.reader.arxiv_reader", "ArxivReader"), "wikipedia": ("agno.knowledge.reader.wikipedia_reader", "WikipediaReader"), "web_search": ("agno.knowledge.reader.web_search_reader", "WebSearchReader"), } if reader_key not in reader_class_map: raise ValueError(f"Unknown reader: {reader_key}") module_path, class_name = reader_class_map[reader_key] import importlib module = importlib.import_module(module_path) return getattr(module, class_name) @classmethod def create_reader(cls, reader_key: str, **kwargs) -> Reader: """Create a reader instance with the given key and optional overrides.""" if reader_key in cls._reader_cache: return cls._reader_cache[reader_key] # Get the reader method and create the instance reader_method = cls._get_reader_method(reader_key) reader = reader_method(**kwargs) # Cache the reader cls._reader_cache[reader_key] = reader return reader @classmethod def get_reader_for_extension(cls, extension: str) -> Reader: """Get the appropriate reader for a file extension.""" extension = extension.lower() if extension in [".pdf", "application/pdf"]: return cls.create_reader("pdf") elif extension in [".csv", "text/csv"]: return cls.create_reader("csv") elif extension in [ ".xlsx", ".xls", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel", ]: return cls.create_reader("excel") elif extension in [".docx", ".doc", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"]: return cls.create_reader("docx") elif extension == ".pptx": return cls.create_reader("pptx") elif extension == ".json": return cls.create_reader("json") elif extension in [".md", ".markdown"]: return cls.create_reader("markdown") elif extension in [".txt", ".text"]: return cls.create_reader("text") else: # Default to text reader for unknown extensions return cls.create_reader("text") @classmethod def get_reader_for_url(cls, url: str) -> Reader: """Get the appropriate reader for a URL.""" url_lower = url.lower() # Check for YouTube URLs if any(domain in url_lower for domain in ["youtube.com", "youtu.be"]): return cls.create_reader("youtube") # Default to website reader return cls.create_reader("website") @classmethod def get_all_reader_keys(cls) -> List[str]: """Get all available reader keys in priority order.""" # Extract reader keys from method names PREFIX = "_get_" SUFFIX = "_reader" reader_keys = [] for attr_name in dir(cls): if attr_name.startswith(PREFIX) and attr_name.endswith(SUFFIX): reader_key = attr_name[len(PREFIX) : -len(SUFFIX)] # Remove "_get_" prefix and "_reader" suffix reader_keys.append(reader_key) # Define priority order for URL readers url_reader_priority = [ "website", "firecrawl", "tavily", "youtube", ] # Sort with URL readers in priority order, others alphabetically def sort_key(reader_key): if reader_key in url_reader_priority: return (0, url_reader_priority.index(reader_key)) else: return (1, reader_key) reader_keys.sort(key=sort_key) return reader_keys @classmethod def create_all_readers(cls) -> Dict[str, Reader]: """Create all readers and return them as a dictionary.""" readers = {} for reader_key in cls.get_all_reader_keys(): readers[reader_key] = cls.create_reader(reader_key) return readers @classmethod def clear_cache(cls): """Clear the reader cache.""" cls._reader_cache.clear() @classmethod def register_reader( cls, key: str, reader_method, name: str, description: str, extensions: Optional[List[str]] = None, ): """Register a new reader type.""" # Add the reader method to the class method_name = f"_get_{key}_reader" setattr(cls, method_name, classmethod(reader_method))
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/reader_factory.py", "license": "Apache License 2.0", "lines": 382, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/s3_reader.py
import asyncio from io import BytesIO from pathlib import Path from typing import List, Optional from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.reader.pdf_reader import PDFReader from agno.knowledge.reader.text_reader import TextReader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error try: from agno.aws.resource.s3.object import S3Object # type: ignore except (ModuleNotFoundError, ImportError): raise ImportError("`agno-aws` not installed. Please install using `pip install agno-aws`") try: import textract # noqa: F401 except ImportError: raise ImportError("`textract` not installed. Please install it via `pip install textract`.") try: from pypdf import PdfReader as DocumentReader # noqa: F401 except ImportError: raise ImportError("`pypdf` not installed. Please install it via `pip install pypdf`.") class S3Reader(Reader): """Reader for S3 files""" def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), **kwargs): super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for S3 readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.FILE, ContentType.URL, ContentType.TEXT] def read(self, name: Optional[str], s3_object: S3Object) -> List[Document]: try: log_debug(f"Reading S3 file: {s3_object.uri}") doc_name = name or s3_object.name.split("/")[-1].split(".")[0].replace("/", "_").replace(" ", "_") # Read PDF files if s3_object.uri.endswith(".pdf"): object_resource = s3_object.get_resource() object_body = object_resource.get()["Body"] return PDFReader().read(pdf=BytesIO(object_body.read()), name=doc_name) # Read text files else: obj_name = s3_object.name.split("/")[-1] temporary_file = Path("storage").joinpath(obj_name) s3_object.download(temporary_file) documents = TextReader().read(file=temporary_file, name=doc_name) temporary_file.unlink() return documents except Exception as e: log_error(f"Error reading: {s3_object.uri}: {e}") return [] async def async_read(self, name: Optional[str], s3_object: S3Object) -> List[Document]: """Asynchronously read S3 files by running the synchronous read operation in a thread.""" return await asyncio.to_thread(self.read, name, s3_object)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/s3_reader.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/text_reader.py
import asyncio import uuid from pathlib import Path from typing import IO, Any, List, Optional, Union from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_error, log_warning class TextReader(Reader): """Reader for Text files""" def __init__(self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), **kwargs): super().__init__(chunking_strategy=chunking_strategy, **kwargs) @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Text readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.TXT] def read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading: {file}") file_name = name or file.stem file_contents = file.read_text(encoding=self.encoding or "utf-8") else: log_debug(f"Reading uploaded file: {getattr(file, 'name', 'BytesIO')}") file_name = name or getattr(file, "name", "text_file").split(".")[0] file.seek(0) file_contents = file.read().decode(self.encoding or "utf-8") documents = [ Document( name=file_name, id=str(uuid.uuid4()), content=file_contents, ) ] if self.chunk: chunked_documents = [] for document in documents: chunked_documents.extend(self.chunk_document(document)) return chunked_documents return documents except Exception as e: log_error(f"Error reading: {file}: {e}") return [] async def async_read(self, file: Union[Path, IO[Any]], name: Optional[str] = None) -> List[Document]: try: if isinstance(file, Path): if not file.exists(): raise FileNotFoundError(f"Could not find file: {file}") log_debug(f"Reading asynchronously: {file}") file_name = name or file.stem try: import aiofiles async with aiofiles.open(file, "r", encoding=self.encoding or "utf-8") as f: file_contents = await f.read() except ImportError: log_warning("aiofiles not installed, using synchronous file I/O") file_contents = file.read_text(encoding=self.encoding or "utf-8") else: log_debug(f"Reading uploaded file asynchronously: {getattr(file, 'name', 'BytesIO')}") file_name = name or getattr(file, "name", "text_file").split(".")[0] file.seek(0) file_contents = file.read().decode(self.encoding or "utf-8") document = Document( name=file_name, id=str(uuid.uuid4()), content=file_contents, ) if self.chunk: return await self._async_chunk_document(document) return [document] except Exception as e: log_error(f"Error reading asynchronously: {file}: {e}") return [] async def _async_chunk_document(self, document: Document) -> List[Document]: if not self.chunk or not document: return [document] async def process_chunk(chunk_doc: Document) -> Document: return chunk_doc chunked_documents = self.chunk_document(document) if not chunked_documents: return [] tasks = [process_chunk(chunk_doc) for chunk_doc in chunked_documents] return await asyncio.gather(*tasks)
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/text_reader.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/web_search_reader.py
import asyncio import random import time from dataclasses import dataclass, field from typing import Dict, List, Literal, Optional, Set from urllib.parse import urlparse import httpx from agno.knowledge.chunking.semantic import SemanticChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document.base import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, logger try: from bs4 import BeautifulSoup, Tag # noqa: F401 except ImportError: raise ImportError("The `bs4` package is not installed. Please install it via `pip install beautifulsoup4`.") try: from ddgs import DDGS except ImportError: raise ImportError("The `ddgs` package is not installed. Please install it via `pip install ddgs`.") @dataclass class WebSearchReader(Reader): """Reader that uses web search to find content for a given query""" search_timeout: int = 10 request_timeout: int = 30 delay_between_requests: float = 2.0 # Increased default delay max_retries: int = 3 user_agent: str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" # Search engine configuration search_engine: Literal["duckduckgo"] = "duckduckgo" search_delay: float = 3.0 # Delay between search requests max_search_retries: int = 2 # Retries for search operations # Rate limiting rate_limit_delay: float = 5.0 # Delay when rate limited exponential_backoff: bool = True # Internal state _visited_urls: Set[str] = field(default_factory=set) _last_search_time: float = field(default=0.0, init=False) # Override default chunking strategy chunking_strategy: Optional[ChunkingStrategy] = SemanticChunking() @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Web Search readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.TOPIC] def _respect_rate_limits(self): """Ensure we don't exceed rate limits""" current_time = time.time() time_since_last_search = current_time - self._last_search_time if time_since_last_search < self.search_delay: sleep_time = self.search_delay - time_since_last_search log_debug(f"Rate limiting: sleeping for {sleep_time:.2f} seconds") time.sleep(sleep_time) self._last_search_time = time.time() def _perform_duckduckgo_search(self, query: str) -> List[Dict[str, str]]: """Perform web search using DuckDuckGo with rate limiting""" log_debug(f"Performing DuckDuckGo search for: {query}") for attempt in range(self.max_search_retries): try: self._respect_rate_limits() ddgs = DDGS(timeout=self.search_timeout) search_results = ddgs.text(query=query, max_results=self.max_results) # Convert to list and extract relevant fields results = [] for result in search_results: results.append( { "title": result.get("title", ""), "url": result.get("href", ""), "description": result.get("body", ""), } ) log_debug(f"Found {len(results)} search results") return results except Exception as e: logger.warning(f"DuckDuckGo search attempt {attempt + 1} failed: {e}") if "rate limit" in str(e).lower() or "429" in str(e): # Rate limited - wait longer wait_time = ( self.rate_limit_delay * (2**attempt) if self.exponential_backoff else self.rate_limit_delay ) logger.info(f"Rate limited, waiting {wait_time} seconds before retry") time.sleep(wait_time) elif attempt < self.max_search_retries - 1: # Other error - shorter wait time.sleep(self.search_delay) else: logger.error(f"All DuckDuckGo search attempts failed: {e}") return [] return [] def _perform_web_search(self, query: str) -> List[Dict[str, str]]: """Perform web search using the configured search engine""" if self.search_engine == "duckduckgo": return self._perform_duckduckgo_search(query) else: logger.error(f"Unsupported search engine: {self.search_engine}") return [] def _is_valid_url(self, url: str) -> bool: """Check if URL is valid and not already visited""" try: parsed = urlparse(url) return bool(parsed.scheme in ["http", "https"] and parsed.netloc and url not in self._visited_urls) except Exception: return False def _extract_text_from_html(self, html_content: str, url: str) -> str: """Extract clean text content from HTML""" try: soup = BeautifulSoup(html_content, "html.parser") # Remove script and style elements for script in soup(["script", "style"]): script.decompose() # Get text content text = soup.get_text() # Clean up whitespace lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) text = " ".join(chunk for chunk in chunks if chunk) return text except Exception as e: logger.warning(f"Error extracting text from {url}: {e}") return html_content def _fetch_url_content(self, url: str) -> Optional[str]: """Fetch content from a URL with retry logic""" headers = {"User-Agent": self.user_agent} for attempt in range(self.max_retries): try: response = httpx.get(url, headers=headers, timeout=self.request_timeout, follow_redirects=True) response.raise_for_status() # Check if it's HTML content content_type = response.headers.get("content-type", "").lower() if "text/html" in content_type: return self._extract_text_from_html(response.text, url) else: # For non-HTML content, return as-is return response.text except Exception as e: logger.warning(f"Attempt {attempt + 1} failed for {url}: {e}") if attempt < self.max_retries - 1: time.sleep(random.uniform(1, 3)) # Random delay between retries continue logger.error(f"Failed to fetch content from {url} after {self.max_retries} attempts") return None def _create_document_from_url(self, url: str, content: str, search_result: Dict[str, str]) -> Document: """Create a Document object from URL content and search result metadata""" # Use the URL as the document ID doc_id = url # Use the search result title as the document name, fallback to URL doc_name = search_result.get("title", urlparse(url).netloc) # Create metadata with search information meta_data = { "url": url, "search_title": search_result.get("title", ""), "search_description": search_result.get("description", ""), "source": "web_search", "search_engine": self.search_engine, } return Document(id=doc_id, name=doc_name, content=content, meta_data=meta_data) def read(self, query: str) -> List[Document]: """Read content for a given query by performing web search and fetching content""" # Clear so URLs from previous queries aren't incorrectly skipped self._visited_urls.clear() if not query: raise ValueError("Query cannot be empty") log_debug(f"Starting web search reader for query: {query}") # Perform web search search_results = self._perform_web_search(query) if not search_results: logger.warning(f"No search results found for query: {query}") return [] documents: List[Document] = [] for result in search_results: url = result.get("url", "") # Skip if URL is invalid or already visited if not self._is_valid_url(url): continue # Mark URL as visited self._visited_urls.add(url) # Add delay between requests to be respectful if len(documents) > 0: time.sleep(self.delay_between_requests) # Fetch content from URL content = self._fetch_url_content(url) if content is None: continue # Create document document = self._create_document_from_url(url, content, result) # Apply chunking if enabled if self.chunk: chunked_docs = self.chunk_document(document) documents.extend(chunked_docs) else: documents.append(document) # Stop if we've reached max_results if len(documents) >= self.max_results: break log_debug(f"Created {len(documents)} documents from web search") return documents async def async_read(self, query: str) -> List[Document]: """Asynchronously read content for a given query""" # Clear so URLs from previous queries aren't incorrectly skipped self._visited_urls.clear() if not query: raise ValueError("Query cannot be empty") log_debug(f"Starting async web search reader for query: {query}") search_results = self._perform_web_search(query) if not search_results: logger.warning(f"No search results found for query: {query}") return [] async def fetch_url_async(result: Dict[str, str]) -> Optional[Document]: url = result.get("url", "") if not self._is_valid_url(url): return None self._visited_urls.add(url) try: headers = {"User-Agent": self.user_agent} async with httpx.AsyncClient(timeout=self.request_timeout) as client: response = await client.get(url, headers=headers, follow_redirects=True) response.raise_for_status() content_type = response.headers.get("content-type", "").lower() if "text/html" in content_type: content = self._extract_text_from_html(response.text, url) else: content = response.text return self._create_document_from_url(url, content, result) except Exception as e: logger.warning(f"Error fetching {url}: {e}") return None documents = [] for i, result in enumerate(search_results): if i > 0: await asyncio.sleep(self.delay_between_requests) doc = await fetch_url_async(result) if doc is not None: if self.chunk: chunked_docs = await self.chunk_documents_async([doc]) documents.extend(chunked_docs) else: documents.append(doc) if len(documents) >= self.max_results: break log_debug(f"Created {len(documents)} documents from async web search") return documents
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/web_search_reader.py", "license": "Apache License 2.0", "lines": 252, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
agno-agi/agno:libs/agno/agno/knowledge/reader/wikipedia_reader.py
import asyncio from typing import List, Optional from agno.knowledge.chunking.fixed import FixedSizeChunking from agno.knowledge.chunking.strategy import ChunkingStrategy, ChunkingStrategyType from agno.knowledge.document import Document from agno.knowledge.reader.base import Reader from agno.knowledge.types import ContentType from agno.utils.log import log_debug, log_info try: import wikipedia # noqa: F401 except ImportError: raise ImportError("The `wikipedia` package is not installed. Please install it via `pip install wikipedia`.") class WikipediaReader(Reader): auto_suggest: bool = True def __init__( self, chunking_strategy: Optional[ChunkingStrategy] = FixedSizeChunking(), auto_suggest: bool = True, **kwargs ): super().__init__(chunking_strategy=chunking_strategy, **kwargs) self.auto_suggest = auto_suggest @classmethod def get_supported_chunking_strategies(cls) -> List[ChunkingStrategyType]: """Get the list of supported chunking strategies for Wikipedia readers.""" return [ ChunkingStrategyType.CODE_CHUNKER, ChunkingStrategyType.FIXED_SIZE_CHUNKER, ChunkingStrategyType.AGENTIC_CHUNKER, ChunkingStrategyType.DOCUMENT_CHUNKER, ChunkingStrategyType.RECURSIVE_CHUNKER, ChunkingStrategyType.SEMANTIC_CHUNKER, ] @classmethod def get_supported_content_types(cls) -> List[ContentType]: return [ContentType.TOPIC] def read(self, topic: str) -> List[Document]: log_debug(f"Reading Wikipedia topic: {topic}") summary = None try: summary = wikipedia.summary(topic, auto_suggest=self.auto_suggest) except wikipedia.exceptions.PageError: summary = None log_info("Wikipedia Error: Page not found.") # Only create Document if we successfully got a summary if summary: return [ Document( name=topic, meta_data={"topic": topic}, content=summary, ) ] return [] async def async_read(self, topic: str) -> List[Document]: """ Asynchronously read content from Wikipedia. Args: topic: The Wikipedia topic to read Returns: A list of documents containing the Wikipedia summary """ log_debug(f"Async reading Wikipedia topic: {topic}") summary = None try: # Run the synchronous wikipedia API call in a thread pool summary = await asyncio.to_thread(wikipedia.summary, topic, auto_suggest=self.auto_suggest) except wikipedia.exceptions.PageError: summary = None log_info("Wikipedia Error: Page not found.") # Only create Document if we successfully got a summary if summary: return [ Document( name=topic, meta_data={"topic": topic}, content=summary, ) ] return []
{ "repo_id": "agno-agi/agno", "file_path": "libs/agno/agno/knowledge/reader/wikipedia_reader.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple