{"repo": "BrainBlend-AI/atomic-agents", "n_pairs": 125, "version": "v3_compressed", "max_tokens": 6000, "contexts": {"atomic-agents/tests/context/test_system_prompt_generator.py::15": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_default_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::149": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_metadata_and_published_date", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::99": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::17": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_default_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::237": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_include_answer", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::111": {"resolved_imports": [], "used_names": ["NoTranscriptFound", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "patch", "pytest"], "enclosing_function": "test_youtube_transcript_tool_no_transcript", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_format_tool_message.py::35": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_without_tool_id", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::320": {"resolved_imports": [], "used_names": ["WebpageScraperToolConfig"], "enclosing_function": "test_tool_config", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::44": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseIOSchema"], "enclosing_function": "test_base_tool_initialization_without_type_parameters", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 549, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 549, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::148": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_metadata_and_published_date", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::114": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": [], "enclosing_function": "test_context_provider_repr", "extracted_code": "", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::204": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_error", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::44": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_custom_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::104": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema"], "enclosing_function": "test_tavily_search_tool_sync_run_method", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_format_tool_message.py::54": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["BaseModel", "format_tool_message"], "enclosing_function": "test_format_tool_message_with_different_tool", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-agents/tests/base/test_base_tool.py::57": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_with_config", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-agents/tests/connectors/mcp/test_mcp_factory.py::81": {"resolved_imports": ["atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py", "atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py"], "used_names": ["MCPFactory", "MCPToolDefinition", "MCPTransportType", "fetch_mcp_tools"], "enclosing_function": "test_fetch_mcp_tools_with_definitions_http", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\nclass MCPFactory:\ndef __init__(\n self,\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the factory.\n\n Args:\n mcp_endpoint: URL of the MCP server (for SSE/HTTP stream) or the full command to run the server (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n client_session: Optional pre-initialized ClientSession for reuse\n event_loop: Optional event loop for running asynchronous operations\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.mcp_endpoint = mcp_endpoint\n self.transport_type = transport_type\n self.client_session = client_session\n self.event_loop = event_loop\n self.schema_transformer = SchemaTransformer()\n self.working_directory = working_directory\n\n # Validate configuration\n if client_session is not None and event_loop is None:\n raise ValueError(\"When `client_session` is provided an `event_loop` must also be supplied.\")\n if not mcp_endpoint and client_session is None:\n raise ValueError(\"`mcp_endpoint` must be provided when no `client_session` is supplied.\")\n def create_tools(self) -> List[Type[BaseTool]]:\n \"\"\"Create tool classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"Fetch tool definitions using the appropriate method.\"\"\"\n ...\n def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:\n \"\"\"Create tool classes from definitions.\"\"\"\n ...\n def create_orchestrator_schema(\n self,\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n ) -> Optional[Type[BaseIOSchema]]:\n \"\"\"Create an orchestrator schema for the given tools.\"\"\"\n ...\n def create_resources(self) -> List[Type[BaseResource]]:\n \"\"\"Create resource classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"Fetch resource definitions using the appropriate method.\"\"\"\n ...\n def _create_resource_classes(self, resource_definitions: List[MCPResourceDefinition]) -> List[Type[BaseResource]]:\n \"\"\"Create resource classes from definitions.\"\"\"\n ...\n def create_prompts(self) -> List[Type[BasePrompt]]:\n \"\"\"Create prompt classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"Fetch prompt definitions using the appropriate method.\"\"\"\n ...\n def _create_prompt_classes(self, prompt_definitions: List[MCPPromptDefinition]) -> List[Type[BasePrompt]]:\n \"\"\"Create prompt classes from definitions.\"\"\"\n ...\n\ndef fetch_mcp_tools(\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n *,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n) -> List[Type[BaseTool]]:\n \"\"\"Connects to an MCP server via SSE, HTTP Stream or STDIO, discovers tool definitions, and dynamically generates\"\"\"\n ...\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPTransportType(Enum):\n \"\"\"Enum for MCP transport types.\"\"\"\n\n SSE = \"sse\"\n HTTP_STREAM = \"http_stream\"\n STDIO = \"stdio\"\n\nclass MCPToolDefinition(NamedTuple):\n \"\"\"Definition of an MCP tool.\"\"\"\n\n name: str\n description: Optional[str]\n input_schema: Dict[str, Any]\n output_schema: Optional[Dict[str, Any]] = None", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47651, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\nclass MCPFactory:\n \"\"\"Factory for creating MCP tool classes.\"\"\"\n\n def __init__(\n self,\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the factory.\n\n Args:\n mcp_endpoint: URL of the MCP server (for SSE/HTTP stream) or the full command to run the server (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n client_session: Optional pre-initialized ClientSession for reuse\n event_loop: Optional event loop for running asynchronous operations\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.mcp_endpoint = mcp_endpoint\n self.transport_type = transport_type\n self.client_session = client_session\n self.event_loop = event_loop\n self.schema_transformer = SchemaTransformer()\n self.working_directory = working_directory\n\n # Validate configuration\n if client_session is not None and event_loop is None:\n raise ValueError(\"When `client_session` is provided an `event_loop` must also be supplied.\")\n if not mcp_endpoint and client_session is None:\n raise ValueError(\"`mcp_endpoint` must be provided when no `client_session` is supplied.\")\n\n def create_tools(self) -> List[Type[BaseTool]]:\n \"\"\"\n Create tool classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated BaseTool subclasses\n \"\"\"\n tool_definitions = self._fetch_tool_definitions()\n if not tool_definitions:\n return []\n\n return self._create_tool_classes(tool_definitions)\n\n def _fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions using the appropriate method.\n\n Returns:\n List of tool definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_tool_definitions_from_session(self.client_session) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_tool_definitions())\n\n def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:\n \"\"\"\n Create tool classes from definitions.\n\n Args:\n tool_definitions: List of tool definitions\n\n Returns:\n List of dynamically generated BaseTool subclasses\n \"\"\"\n generated_tools = []\n\n for definition in tool_definitions:\n try:\n tool_name = definition.name\n tool_description = definition.description or f\"Dynamically generated tool for MCP tool: {tool_name}\"\n input_schema_dict = definition.input_schema\n\n # Create input schema\n InputSchema = self.schema_transformer.create_model_from_schema(\n input_schema_dict,\n f\"{tool_name}InputSchema\",\n tool_name,\n f\"Input schema for {tool_name}\",\n attribute_type=MCPAttributeType.TOOL,\n )\n\n # Create output schema - use MCP-provided schema if available, otherwise fallback to generic.\n # When a typed output schema is used, _has_typed_output_schema is set on the tool class\n # to enable structured content extraction at runtime (see result processing below).\n output_schema_dict: Optional[Dict[str, Any]] = definition.output_schema\n has_typed_output_schema = False\n if output_schema_dict:\n # Use the schema transformer to create a proper typed output schema\n OutputSchema = self.schema_transformer.create_model_from_schema(\n output_schema_dict,\n f\"{tool_name}OutputSchema\",\n tool_name,\n f\"Output schema for {tool_name}\",\n attribute_type=MCPAttributeType.TOOL,\n is_output_schema=True,\n )\n has_typed_output_schema = True\n else:\n # Fallback to generic output schema\n OutputSchema = type(\n f\"{tool_name}OutputSchema\", (MCPToolOutputSchema,), {\"__doc__\": f\"Output schema for {tool_name}\"}\n )\n\n # Async implementation\n async def run_tool_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_tool_name = self.mcp_tool_name\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n # Get arguments, excluding tool_name\n arguments = params.model_dump(exclude={\"tool_name\"}, exclude_none=True)\n\n async def _connect_and_call():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(f\"Executing tool '{bound_tool_name}' via STDIO: command='{command}', args={args}\")\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(f\"Executing tool '{bound_tool_name}' via HTTP Stream: endpoint={http_endpoint}\")\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Executing tool '{bound_tool_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n tool_result = await session.call_tool(name=bound_tool_name, arguments=call_args)\n return tool_result\n finally:\n await stack.aclose()\n\n async def _call_with_persistent_session():\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n return await persistent_session.call_tool(name=bound_tool_name, arguments=call_args)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n tool_result = await _call_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n tool_result = await _connect_and_call()\n\n # Process the result based on whether we have a typed output schema.\n # Extraction precedence for typed schemas:\n # 1. structuredContent attribute (MCP spec primary path)\n # 2. content[0].text parsed as JSON (some servers return JSON as text)\n # 3. content[0].data dict (structured data in content item)\n # 4. Dict with structuredContent/content keys\n # 5. Direct dict usage as fallback\n has_typed_schema = getattr(self, \"_has_typed_output_schema\", False)\n BoundOutputSchema = self.output_schema\n\n if has_typed_schema:\n # For typed output schemas, try to extract structured content\n # MCP tools with output schemas return structured data\n if isinstance(tool_result, BaseModel) and hasattr(tool_result, \"structuredContent\"):\n # Use structured content if available (MCP spec)\n structured_data = tool_result.structuredContent\n if isinstance(structured_data, dict):\n return BoundOutputSchema(**structured_data)\n elif hasattr(structured_data, \"model_dump\"):\n return BoundOutputSchema(**structured_data.model_dump())\n else:\n # Unexpected type for structuredContent\n logger.error(\n f\"Unexpected structuredContent type for tool '{bound_tool_name}': \"\n f\"got {type(structured_data).__name__}, expected dict or BaseModel. \"\n f\"Content: {structured_data!r}\"\n )\n raise TypeError(\n f\"MCP tool '{bound_tool_name}' returned structuredContent with unexpected type \"\n f\"{type(structured_data).__name__}. Expected dict or BaseModel.\"\n )\n elif isinstance(tool_result, BaseModel) and hasattr(tool_result, \"content\"):\n # Try to parse content as structured data\n content = tool_result.content\n # Ensure content is a list/tuple before indexing\n if content and isinstance(content, (list, tuple)) and len(content) > 0:\n first_content = content[0]\n # Check for text content that might be JSON\n if hasattr(first_content, \"text\"):\n try:\n parsed = json.loads(first_content.text)\n if isinstance(parsed, dict):\n return BoundOutputSchema(**parsed)\n else:\n logger.debug(\n f\"Tool '{bound_tool_name}' content parsed as JSON but was \"\n f\"{type(parsed).__name__}, not dict. Trying other extraction methods.\"\n )\n except json.JSONDecodeError as e:\n logger.debug(\n f\"Tool '{bound_tool_name}' content is not valid JSON: {e}. \"\n f\"Content preview: {first_content.text[:200]!r}...\"\n if len(first_content.text) > 200\n else f\"Content: {first_content.text!r}\"\n )\n except TypeError as e:\n logger.warning(\n f\"Tool '{bound_tool_name}' content.text has unexpected type \"\n f\"{type(first_content.text).__name__}: {e}\"\n )\n # Check for structured content in the content item\n if hasattr(first_content, \"data\") and isinstance(first_content.data, dict):\n return BoundOutputSchema(**first_content.data)\n elif isinstance(tool_result, dict):\n if \"structuredContent\" in tool_result:\n return BoundOutputSchema(**tool_result[\"structuredContent\"])\n elif \"content\" in tool_result:\n content = tool_result[\"content\"]\n if isinstance(content, dict):\n return BoundOutputSchema(**content)\n # Fallback: try to use tool_result directly if it's a dict\n if isinstance(tool_result, dict):\n return BoundOutputSchema(**tool_result)\n # If we have a typed schema but couldn't extract structured content,\n # this is an error - we cannot fall through to generic handling\n # because the typed schema doesn't have a 'result' field.\n logger.error(\n f\"Could not parse structured output for tool '{bound_tool_name}'. \"\n f\"Expected typed output but got: type={type(tool_result).__name__}, \"\n f\"value={tool_result!r}\"\n )\n raise ValueError(\n f\"MCP tool '{bound_tool_name}' has outputSchema but returned unparseable result. \"\n f\"Received type: {type(tool_result).__name__}. \"\n f\"Check MCP server implementation.\"\n )\n\n # Generic output schema handling (original behavior) - only for tools without typed schemas\n if isinstance(tool_result, BaseModel) and hasattr(tool_result, \"content\"):\n actual_result_content = tool_result.content\n elif isinstance(tool_result, dict) and \"content\" in tool_result:\n actual_result_content = tool_result[\"content\"]\n else:\n actual_result_content = tool_result\n\n return BoundOutputSchema(result=actual_result_content)\n\n except Exception as e:\n logger.error(f\"Error executing MCP tool '{bound_tool_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to execute MCP tool '{bound_tool_name}': {e}\") from e\n\n # Create sync wrapper\n def run_tool_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.arun(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to execute MCP tool '{tool_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.arun(params))\n\n # Create the tool class using types.new_class() instead of type()\n attrs = {\n \"arun\": run_tool_async,\n \"run\": run_tool_sync,\n \"__doc__\": tool_description,\n \"mcp_tool_name\": tool_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n \"_has_typed_output_schema\": has_typed_output_schema,\n }\n\n # Create the class using new_class() for proper generic type support\n tool_class = types.new_class(\n tool_name, (BaseTool[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n # since they might not be properly inherited with types.new_class\n setattr(tool_class, \"input_schema\", InputSchema)\n setattr(tool_class, \"output_schema\", OutputSchema)\n\n generated_tools.append(tool_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for tool '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_tools\n\n def create_orchestrator_schema(\n self,\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n ) -> Optional[Type[BaseIOSchema]]:\n \"\"\"\n Create an orchestrator schema for the given tools.\n\n Args:\n tools: List of tool classes\n resources: List of resource classes\n prompts: List of prompt classes\n\n Returns:\n Orchestrator schema or None if no tools provided\n \"\"\"\n if tools is None and resources is None and prompts is None:\n logger.warning(\"No tools/resources/prompts provided to create orchestrator schema\")\n return None\n if tools is None:\n tools = []\n if resources is None:\n resources = []\n if prompts is None:\n prompts = []\n\n tool_schemas = [ToolClass.input_schema for ToolClass in tools]\n resource_schemas = [ResourceClass.input_schema for ResourceClass in resources]\n prompt_schemas = [PromptClass.input_schema for PromptClass in prompts]\n\n # Build runtime Union types for each attribute group when present\n field_defs = {}\n\n if tool_schemas:\n ToolUnion = Union[tuple(tool_schemas)]\n field_defs[\"tool_parameters\"] = (\n ToolUnion,\n Field(\n ...,\n description=\"The parameters for the selected tool, matching its specific schema (which includes the 'tool_name').\",\n ),\n )\n\n if resource_schemas:\n ResourceUnion = Union[tuple(resource_schemas)]\n field_defs[\"resource_parameters\"] = (\n ResourceUnion,\n Field(\n ...,\n description=\"The parameters for the selected resource, matching its specific schema (which includes the 'resource_name').\",\n ),\n )\n\n if prompt_schemas:\n PromptUnion = Union[tuple(prompt_schemas)]\n field_defs[\"prompt_parameters\"] = (\n PromptUnion,\n Field(\n ...,\n description=\"The parameters for the selected prompt, matching its specific schema (which includes the 'prompt_name').\",\n ),\n )\n\n if not field_defs:\n logger.warning(\"No schemas available to create orchestrator union\")\n return None\n\n # Dynamically create the output schema with the appropriate fields\n orchestrator_schema = create_model(\n \"MCPOrchestratorOutputSchema\",\n __doc__=\"Output schema for the MCP Orchestrator Agent. Contains the parameters for the selected tool/resource/prompt.\",\n __base__=BaseIOSchema,\n **field_defs,\n )\n\n return orchestrator_schema\n\n def create_resources(self) -> List[Type[BaseResource]]:\n \"\"\"\n Create resource classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated resource classes\n \"\"\"\n resource_definitions = self._fetch_resource_definitions()\n if not resource_definitions:\n return []\n\n return self._create_resource_classes(resource_definitions)\n\n def _fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions using the appropriate method.\n\n Returns:\n List of resource definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_resource_definitions_from_session(\n self.client_session\n ) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_resource_definitions())\n\n def _create_resource_classes(self, resource_definitions: List[MCPResourceDefinition]) -> List[Type[BaseResource]]:\n \"\"\"\n Create resource classes from definitions.\n\n Args:\n resource_definitions: List of resource definitions\n\n Returns:\n List of dynamically generated resource classes\n \"\"\"\n generated_resources = []\n\n for definition in resource_definitions:\n try:\n resource_name = definition.name\n resource_description = (\n definition.description or f\"Dynamically generated resource for MCP resource: {resource_name}\"\n )\n uri = definition.uri\n mime_type = definition.mime_type\n\n InputSchema = self.schema_transformer.create_model_from_schema(\n definition.input_schema,\n f\"{resource_name}InputSchema\",\n resource_name,\n f\"Input schema for {resource_name}\",\n attribute_type=MCPAttributeType.RESOURCE,\n )\n\n # Create output schema\n OutputSchema = type(\n f\"{resource_name}OutputSchema\",\n (MCPResourceOutputSchema,),\n {\"__doc__\": f\"Output schema for {resource_name}\"},\n )\n\n # Async implementation\n async def read_resource_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_uri = self.uri\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n arguments = params.model_dump(exclude={\"resource_name\"}, exclude_none=True)\n\n async def _connect_and_read():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(\n f\"Reading resource '{self.mcp_resource_name}' via STDIO: command='{command}', args={args}\"\n )\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(\n f\"Reading resource '{self.mcp_resource_name}' via HTTP Stream: endpoint={http_endpoint}\"\n )\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Reading resource '{self.mcp_resource_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Substitute URI placeholders with provided parameters when available.\n call_args = arguments if isinstance(arguments, dict) else {}\n # If params contain keys, format the URI template.\n try:\n concrete_uri = bound_uri.format(**call_args) if call_args else bound_uri\n except Exception:\n concrete_uri = bound_uri\n resource_result: mcp.types.ReadResourceResult = await session.read_resource(uri=concrete_uri)\n return resource_result\n finally:\n await stack.aclose()\n\n async def _read_with_persistent_session():\n call_args = arguments if isinstance(arguments, dict) else {}\n\n try:\n concrete_uri_p = bound_uri.format(**call_args) if call_args else bound_uri\n except Exception:\n concrete_uri_p = bound_uri\n\n return await persistent_session.read_resource(uri=concrete_uri_p)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n resource_result = await _read_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n resource_result = await _connect_and_read()\n\n # Process the result\n if isinstance(resource_result, BaseModel) and hasattr(resource_result, \"contents\"):\n actual_content = resource_result.contents\n # MCP stores mimeType in each content item, not on the result itself\n if actual_content and len(actual_content) > 0:\n # Get mimeType from the first content item\n first_content = actual_content[0]\n actual_mime = getattr(first_content, \"mimeType\", mime_type)\n else:\n actual_mime = mime_type\n elif isinstance(resource_result, dict) and \"contents\" in resource_result:\n actual_content = resource_result[\"contents\"]\n actual_mime = resource_result.get(\"mime_type\", mime_type)\n else:\n actual_content = resource_result\n actual_mime = mime_type\n\n return OutputSchema(content=actual_content, mime_type=actual_mime)\n\n except Exception as e:\n logger.error(f\"Error reading MCP resource '{self.mcp_resource_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to read MCP resource '{self.mcp_resource_name}': {e}\") from e\n\n # Create sync wrapper\n def read_resource_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.aread(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to read MCP resource '{resource_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.aread(params))\n\n # Create the resource class using types.new_class() instead of type()\n attrs = {\n \"aread\": read_resource_async,\n \"read\": read_resource_sync,\n \"__doc__\": resource_description,\n \"mcp_resource_name\": resource_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n \"uri\": uri,\n }\n\n # Create the class using new_class() for proper generic type support\n resource_class = types.new_class(\n resource_name, (BaseResource[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n setattr(resource_class, \"input_schema\", InputSchema)\n setattr(resource_class, \"output_schema\", OutputSchema)\n\n generated_resources.append(resource_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for resource '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_resources\n\n def create_prompts(self) -> List[Type[BasePrompt]]:\n \"\"\"\n Create prompt classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated prompt classes\n \"\"\"\n prompt_definitions = self._fetch_prompt_definitions()\n if not prompt_definitions:\n return []\n\n return self._create_prompt_classes(prompt_definitions)\n\n def _fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt definitions using the appropriate method.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_prompt_definitions_from_session(\n self.client_session\n ) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_prompt_definitions())\n\n def _create_prompt_classes(self, prompt_definitions: List[MCPPromptDefinition]) -> List[Type[BasePrompt]]:\n \"\"\"\n Create prompt classes from definitions.\n\n Args:\n prompt_definitions: List of prompt definitions\n\n Returns:\n List of dynamically generated prompt classes\n \"\"\"\n generated_prompts = []\n\n for definition in prompt_definitions:\n try:\n prompt_name = definition.name\n prompt_description = definition.description or f\"Dynamically generated prompt for MCP prompt: {prompt_name}\"\n\n InputSchema = self.schema_transformer.create_model_from_schema(\n definition.input_schema,\n f\"{prompt_name}InputSchema\",\n prompt_name,\n f\"Input schema for {prompt_name}\",\n attribute_type=MCPAttributeType.PROMPT,\n )\n\n # Create output schema\n OutputSchema = type(\n f\"{prompt_name}OutputSchema\", (MCPPromptOutputSchema,), {\"__doc__\": f\"Output schema for {prompt_name}\"}\n )\n\n # Async implementation\n async def generate_prompt_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_prompt_name = self.mcp_prompt_name\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n # Get arguments\n arguments = params.model_dump(exclude={\"prompt_name\"}, exclude_none=True)\n\n async def _connect_and_generate():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(\n f\"Getting prompt '{bound_prompt_name}' via STDIO: command='{command}', args={args}\"\n )\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(f\"Getting prompt '{bound_prompt_name}' via HTTP Stream: endpoint={http_endpoint}\")\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Getting prompt '{bound_prompt_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n prompt_result = await session.get_prompt(name=bound_prompt_name, arguments=call_args)\n return prompt_result\n finally:\n await stack.aclose()\n\n async def _get_with_persistent_session():\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n return await persistent_session.get_prompt(name=bound_prompt_name, arguments=call_args)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n prompt_result = await _get_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n prompt_result = await _connect_and_generate()\n\n # Process the result\n messages = None\n if isinstance(prompt_result, BaseModel) and hasattr(prompt_result, \"messages\"):\n messages = prompt_result.messages\n elif isinstance(prompt_result, dict) and \"messages\" in prompt_result:\n messages = prompt_result[\"messages\"]\n else:\n raise Exception(\"Prompt response has no messages.\")\n\n texts = []\n for message in messages:\n if isinstance(message, BaseModel) and hasattr(message, \"content\"):\n content = message.content # type: ignore\n elif isinstance(message, dict) and \"content\" in message:\n content = message[\"content\"]\n else:\n content = message\n\n if isinstance(content, str):\n texts.append(content)\n elif isinstance(content, dict):\n texts.append(content.get(\"text\"))\n elif getattr(content, \"text\", None):\n texts.append(content.text) # type: ignore\n else:\n texts.append(str(content))\n final_content = \"\\n\\n\".join(texts)\n\n return OutputSchema(content=final_content)\n\n except Exception as e:\n logger.error(f\"Error getting MCP prompt '{bound_prompt_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to get MCP prompt '{bound_prompt_name}': {e}\") from e\n\n # Create sync wrapper\n def generate_prompt_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.agenerate(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to get MCP prompt '{prompt_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.agenerate(params))\n\n # Create the prompt class using types.new_class() instead of type()\n attrs = {\n \"agenerate\": generate_prompt_async,\n \"generate\": generate_prompt_sync,\n \"__doc__\": prompt_description,\n \"mcp_prompt_name\": prompt_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n }\n\n # Create the class using new_class() for proper generic type support\n prompt_class = types.new_class(\n prompt_name, (BasePrompt[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n setattr(prompt_class, \"input_schema\", InputSchema)\n setattr(prompt_class, \"output_schema\", OutputSchema)\n\n generated_prompts.append(prompt_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for prompt '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_prompts\n\ndef fetch_mcp_tools(\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n *,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n) -> List[Type[BaseTool]]:\n \"\"\"\n Connects to an MCP server via SSE, HTTP Stream or STDIO, discovers tool definitions, and dynamically generates\n synchronous Atomic Agents compatible BaseTool subclasses for each tool.\n Each generated tool will establish its own connection when its `run` method is called.\n\n Args:\n mcp_endpoint: URL of the MCP server or command for STDIO.\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO).\n client_session: Optional pre-initialized ClientSession for reuse.\n event_loop: Optional event loop for running asynchronous operations.\n working_directory: Optional working directory for STDIO.\n \"\"\"\n factory = MCPFactory(mcp_endpoint, transport_type, client_session, event_loop, working_directory)\n return factory.create_tools()\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPTransportType(Enum):\n \"\"\"Enum for MCP transport types.\"\"\"\n\n SSE = \"sse\"\n HTTP_STREAM = \"http_stream\"\n STDIO = \"stdio\"\n\nclass MCPToolDefinition(NamedTuple):\n \"\"\"Definition of an MCP tool.\"\"\"\n\n name: str\n description: Optional[str]\n input_schema: Dict[str, Any]\n output_schema: Optional[Dict[str, Any]] = None", "n_chars_compressed": 4196, "compression_ratio": 0.08805691381083293}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::326": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_clean_markdown_empty_content", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::147": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_metadata_and_published_date", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::150": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_metadata_and_published_date", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::233": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_include_answer", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::318": {"resolved_imports": [], "used_names": ["WebpageScraperToolConfig"], "enclosing_function": "test_tool_config", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/calculator/tests/test_calculator.py::17": {"resolved_imports": [], "used_names": ["CalculatorTool", "CalculatorToolInputSchema", "CalculatorToolOutputSchema"], "enclosing_function": "test_calculator_tool", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::12": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_string_type_required", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::200": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_error", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_token_counter.py::181": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCounter", "patch", "pytest"], "enclosing_function": "test_count_context", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 5801, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_chars_compressed": 5801, "compression_ratio": 1.0}, "atomic-agents/tests/utils/test_format_tool_message.py::53": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["BaseModel", "format_tool_message"], "enclosing_function": "test_format_tool_message_with_different_tool", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::214": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_max_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/connectors/mcp/test_mcp_factory.py::631": {"resolved_imports": ["atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py", "atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py"], "used_names": ["BaseModel", "create_mcp_orchestrator_schema"], "enclosing_function": "test_create_mcp_orchestrator_schema_with_prompts", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\ndef create_mcp_orchestrator_schema(\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n) -> Optional[Type[BaseIOSchema]]:\n \"\"\"\n Creates a schema for the MCP Orchestrator's output using the Union of all tool input schemas.\n\n Args:\n tools: List of dynamically generated MCP tool classes\n\n Returns:\n A Pydantic model class to be used as the output schema for an orchestrator agent\n \"\"\"\n # Bypass constructor validation since orchestrator schema does not require endpoint or session\n factory = object.__new__(MCPFactory)\n return MCPFactory.create_orchestrator_schema(factory, tools, resources, prompts)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 815, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\ndef create_mcp_orchestrator_schema(\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n) -> Optional[Type[BaseIOSchema]]:\n \"\"\"\n Creates a schema for the MCP Orchestrator's output using the Union of all tool input schemas.\n\n Args:\n tools: List of dynamically generated MCP tool classes\n\n Returns:\n A Pydantic model class to be used as the output schema for an orchestrator agent\n \"\"\"\n # Bypass constructor validation since orchestrator schema does not require endpoint or session\n factory = object.__new__(MCPFactory)\n return MCPFactory.create_orchestrator_schema(factory, tools, resources, prompts)", "n_chars_compressed": 815, "compression_ratio": 1.0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::234": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_include_answer", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::68": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::53": {"resolved_imports": [], "used_names": ["MagicMock", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "YouTubeTranscriptToolOutputSchema", "datetime", "patch"], "enclosing_function": "test_youtube_transcript_tool", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::21": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_default_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_mcp_definition_service.py::483": {"resolved_imports": ["atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py"], "used_names": ["AsyncMock", "MCPDefinitionService", "pytest"], "enclosing_function": "test_fetch_tool_definitions_from_session_no_tools", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPDefinitionService:\n \"\"\"Service for fetching tool definitions from MCP endpoints.\"\"\"\n\n def __init__(\n self,\n endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the service.\n\n Args:\n endpoint: URL of the MCP server (for SSE/HTTP stream) or command string (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.endpoint = endpoint\n self.transport_type = transport_type\n self.working_directory = working_directory\n\n async def fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from the configured endpoint.\n\n Returns:\n List of tool definitions\n\n Raises:\n ConnectionError: If connection to the MCP server fails\n ValueError: If the STDIO command string is empty\n RuntimeError: For other unexpected errors\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n definitions = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n # STDIO transport\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.info(f\"Attempting STDIO connection with command='{command}', args={args}\")\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n logger.info(f\"Attempting HTTP Stream connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n transport_endpoint = f\"{self.endpoint}/sse\"\n logger.info(f\"Attempting SSE connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n definitions = await self.fetch_tool_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during tool definition fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return definitions\n\n @staticmethod\n async def fetch_tool_definitions_from_session(session: ClientSession) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of tool definitions\n\n Raises:\n Exception: If listing tools fails\n \"\"\"\n definitions: List[MCPToolDefinition] = []\n try:\n # `initialize` is idempotent – calling it twice is safe and\n # ensures the session is ready.\n await session.initialize()\n response = await session.list_tools()\n for mcp_tool in response.tools:\n # Capture outputSchema if the MCP server provides one\n output_schema = getattr(mcp_tool, \"outputSchema\", None)\n definitions.append(\n MCPToolDefinition(\n name=mcp_tool.name,\n description=mcp_tool.description,\n input_schema=mcp_tool.inputSchema or {\"type\": \"object\", \"properties\": {}},\n output_schema=output_schema,\n )\n )\n\n if not definitions:\n logger.warning(\"No tool definitions found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list tools via MCP session: %s\", e, exc_info=True)\n raise\n\n return definitions\n\n async def fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from the configured endpoint.\n\n Returns:\n List of resource definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n resources: List[MCPResourceDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n resources = await self.fetch_resource_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during resource fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return resources\n\n @staticmethod\n async def fetch_resource_definitions_from_session(session: ClientSession) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of resource definitions\n \"\"\"\n resources: List[MCPResourceDefinition] = []\n\n try:\n await session.initialize()\n response: types.ListResourcesResult = await session.list_resources()\n\n resources_iterable: List[types.Resource] = list(response.resources or [])\n\n if not resources_iterable:\n res_templates: types.ListResourceTemplatesResult = await session.list_resource_templates()\n for template in res_templates.resourceTemplates:\n # Resources have no \"input_schema\" value and use URI templates with parameters.\n resources_iterable.append(\n types.Resource(\n name=template.name,\n description=template.description,\n uri=AnyUrl(template.uriTemplate),\n )\n )\n\n for mcp_resource in resources_iterable:\n # Support both attribute-style objects and dict-like responses\n if hasattr(mcp_resource, \"name\"):\n name = mcp_resource.name\n description = mcp_resource.description\n uri = mcp_resource.uri\n elif isinstance(mcp_resource, dict):\n # assume mapping\n name = mcp_resource[\"name\"]\n description = mcp_resource.get(\"description\")\n uri = mcp_resource.get(\"uri\", \"\")\n else:\n raise ValueError(f\"Unexpected resource format: {mcp_resource}\")\n\n # Extract placeholders from the chosen source\n uri = decode_uri(str(uri))\n placeholders = re.findall(r\"\\{([^}]+)\\}\", uri) if uri else []\n properties: Dict[str, Any] = {}\n for param_name in placeholders:\n properties[param_name] = {\"type\": \"string\", \"description\": f\"URI parameter {param_name}\"}\n\n resources.append(\n MCPResourceDefinition(\n name=name,\n description=description,\n uri=uri,\n mime_type=getattr(mcp_resource, \"mimeType\", None),\n input_schema={\"type\": \"object\", \"properties\": properties, \"required\": list(placeholders)},\n )\n )\n\n if not resources:\n logger.warning(\"No resources found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list resources via MCP session: %s\", e, exc_info=True)\n raise\n\n return resources\n\n async def fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from the configured endpoint.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n prompts: List[MCPPromptDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n prompts = await self.fetch_prompt_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during prompt fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return prompts\n\n @staticmethod\n async def fetch_prompt_definitions_from_session(session: ClientSession) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of prompt definitions\n \"\"\"\n prompts: List[MCPPromptDefinition] = []\n try:\n await session.initialize()\n response: types.ListPromptsResult = await session.list_prompts()\n for mcp_prompt in response.prompts:\n arguments: List[types.PromptArgument] = mcp_prompt.arguments or []\n prompts.append(\n MCPPromptDefinition(\n name=mcp_prompt.name,\n description=mcp_prompt.description,\n input_schema={\n \"type\": \"object\",\n \"properties\": {arg.name: {\"type\": \"string\", \"description\": arg.description} for arg in arguments},\n \"required\": [arg.name for arg in arguments if arg.required],\n },\n )\n )\n if not prompts:\n logger.warning(\"No prompts found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list prompts via MCP session: %s\", e, exc_info=True)\n raise\n\n return prompts", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 14667, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPDefinitionService:\n \"\"\"Service for fetching tool definitions from MCP endpoints.\"\"\"\n\n def __init__(\n self,\n endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the service.\n\n Args:\n endpoint: URL of the MCP server (for SSE/HTTP stream) or command string (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.endpoint = endpoint\n self.transport_type = transport_type\n self.working_directory = working_directory\n\n async def fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from the configured endpoint.\n\n Returns:\n List of tool definitions\n\n Raises:\n ConnectionError: If connection to the MCP server fails\n ValueError: If the STDIO command string is empty\n RuntimeError: For other unexpected errors\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n definitions = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n # STDIO transport\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.info(f\"Attempting STDIO connection with command='{command}', args={args}\")\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n logger.info(f\"Attempting HTTP Stream connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n transport_endpoint = f\"{self.endpoint}/sse\"\n logger.info(f\"Attempting SSE connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n definitions = await self.fetch_tool_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during tool definition fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return definitions\n\n @staticmethod\n async def fetch_tool_definitions_from_session(session: ClientSession) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of tool definitions\n\n Raises:\n Exception: If listing tools fails\n \"\"\"\n definitions: List[MCPToolDefinition] = []\n try:\n # `initialize` is idempotent – calling it twice is safe and\n # ensures the session is ready.\n await session.initialize()\n response = await session.list_tools()\n for mcp_tool in response.tools:\n # Capture outputSchema if the MCP server provides one\n output_schema = getattr(mcp_tool, \"outputSchema\", None)\n definitions.append(\n MCPToolDefinition(\n name=mcp_tool.name,\n description=mcp_tool.description,\n input_schema=mcp_tool.inputSchema or {\"type\": \"object\", \"properties\": {}},\n output_schema=output_schema,\n )\n )\n\n if not definitions:\n logger.warning(\"No tool definitions found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list tools via MCP session: %s\", e, exc_info=True)\n raise\n\n return definitions\n\n async def fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from the configured endpoint.\n\n Returns:\n List of resource definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n resources: List[MCPResourceDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n resources = await self.fetch_resource_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during resource fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return resources\n\n @staticmethod\n async def fetch_resource_definitions_from_session(session: ClientSession) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of resource definitions\n \"\"\"\n resources: List[MCPResourceDefinition] = []\n\n try:\n await session.initialize()\n response: types.ListResourcesResult = await session.list_resources()\n\n resources_iterable: List[types.Resource] = list(response.resources or [])\n\n if not resources_iterable:\n res_templates: types.ListResourceTemplatesResult = await session.list_resource_templates()\n for template in res_templates.resourceTemplates:\n # Resources have no \"input_schema\" value and use URI templates with parameters.\n resources_iterable.append(\n types.Resource(\n name=template.name,\n description=template.description,\n uri=AnyUrl(template.uriTemplate),\n )\n )\n\n for mcp_resource in resources_iterable:\n # Support both attribute-style objects and dict-like responses\n if hasattr(mcp_resource, \"name\"):\n name = mcp_resource.name\n description = mcp_resource.description\n uri = mcp_resource.uri\n elif isinstance(mcp_resource, dict):\n # assume mapping\n name = mcp_resource[\"name\"]\n description = mcp_resource.get(\"description\")\n uri = mcp_resource.get(\"uri\", \"\")\n else:\n raise ValueError(f\"Unexpected resource format: {mcp_resource}\")\n\n # Extract placeholders from the chosen source\n uri = decode_uri(str(uri))\n placeholders = re.findall(r\"\\{([^}]+)\\}\", uri) if uri else []\n properties: Dict[str, Any] = {}\n for param_name in placeholders:\n properties[param_name] = {\"type\": \"string\", \"description\": f\"URI parameter {param_name}\"}\n\n resources.append(\n MCPResourceDefinition(\n name=name,\n description=description,\n uri=uri,\n mime_type=getattr(mcp_resource, \"mimeType\", None),\n input_schema={\"type\": \"object\", \"properties\": properties, \"required\": list(placeholders)},\n )\n )\n\n if not resources:\n logger.warning(\"No resources found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list resources via MCP session: %s\", e, exc_info=True)\n raise\n\n return resources\n\n async def fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from the configured endpoint.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n prompts: List[MCPPromptDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n prompts = await self.fetch_prompt_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during prompt fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return prompts\n\n @staticmethod\n async def fetch_prompt_definitions_from_session(session: ClientSession) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of prompt definitions\n \"\"\"\n prompts: List[MCPPromptDefinition] = []\n try:\n await session.initialize()\n response: types.ListPromptsResult = await session.list_prompts()\n for mcp_prompt in response.prompts:\n arguments: List[types.PromptArgument] = mcp_prompt.arguments or []\n prompts.append(\n MCPPromptDefinition(\n name=mcp_prompt.name,\n description=mcp_prompt.description,\n input_schema={\n \"type\": \"object\",\n \"properties\": {arg.name: {\"type\": \"string\", \"description\": arg.description} for arg in arguments},\n \"required\": [arg.name for arg in arguments if arg.required],\n },\n )\n )\n if not prompts:\n logger.warning(\"No prompts found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list prompts via MCP session: %s\", e, exc_info=True)\n raise\n\n return prompts", "n_chars_compressed": 14667, "compression_ratio": 1.0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::51": {"resolved_imports": [], "used_names": ["MagicMock", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "YouTubeTranscriptToolOutputSchema", "datetime", "patch"], "enclosing_function": "test_youtube_transcript_tool", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::121": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseIOSchema", "BaseTool"], "enclosing_function": "test_base_tool_schema_resolution", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1181, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 1181, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::114": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["BaseIOSchema", "SchemaTransformer"], "enclosing_function": "test_empty_object_schema", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8330, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 8330, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_mcp_definition_service.py::530": {"resolved_imports": ["atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py"], "used_names": ["AsyncMock", "MCPDefinitionService", "MagicMock", "pytest"], "enclosing_function": "test_fetch_resources_from_session", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPDefinitionService:\n \"\"\"Service for fetching tool definitions from MCP endpoints.\"\"\"\n\n def __init__(\n self,\n endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the service.\n\n Args:\n endpoint: URL of the MCP server (for SSE/HTTP stream) or command string (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.endpoint = endpoint\n self.transport_type = transport_type\n self.working_directory = working_directory\n\n async def fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from the configured endpoint.\n\n Returns:\n List of tool definitions\n\n Raises:\n ConnectionError: If connection to the MCP server fails\n ValueError: If the STDIO command string is empty\n RuntimeError: For other unexpected errors\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n definitions = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n # STDIO transport\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.info(f\"Attempting STDIO connection with command='{command}', args={args}\")\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n logger.info(f\"Attempting HTTP Stream connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n transport_endpoint = f\"{self.endpoint}/sse\"\n logger.info(f\"Attempting SSE connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n definitions = await self.fetch_tool_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during tool definition fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return definitions\n\n @staticmethod\n async def fetch_tool_definitions_from_session(session: ClientSession) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of tool definitions\n\n Raises:\n Exception: If listing tools fails\n \"\"\"\n definitions: List[MCPToolDefinition] = []\n try:\n # `initialize` is idempotent – calling it twice is safe and\n # ensures the session is ready.\n await session.initialize()\n response = await session.list_tools()\n for mcp_tool in response.tools:\n # Capture outputSchema if the MCP server provides one\n output_schema = getattr(mcp_tool, \"outputSchema\", None)\n definitions.append(\n MCPToolDefinition(\n name=mcp_tool.name,\n description=mcp_tool.description,\n input_schema=mcp_tool.inputSchema or {\"type\": \"object\", \"properties\": {}},\n output_schema=output_schema,\n )\n )\n\n if not definitions:\n logger.warning(\"No tool definitions found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list tools via MCP session: %s\", e, exc_info=True)\n raise\n\n return definitions\n\n async def fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from the configured endpoint.\n\n Returns:\n List of resource definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n resources: List[MCPResourceDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n resources = await self.fetch_resource_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during resource fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return resources\n\n @staticmethod\n async def fetch_resource_definitions_from_session(session: ClientSession) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of resource definitions\n \"\"\"\n resources: List[MCPResourceDefinition] = []\n\n try:\n await session.initialize()\n response: types.ListResourcesResult = await session.list_resources()\n\n resources_iterable: List[types.Resource] = list(response.resources or [])\n\n if not resources_iterable:\n res_templates: types.ListResourceTemplatesResult = await session.list_resource_templates()\n for template in res_templates.resourceTemplates:\n # Resources have no \"input_schema\" value and use URI templates with parameters.\n resources_iterable.append(\n types.Resource(\n name=template.name,\n description=template.description,\n uri=AnyUrl(template.uriTemplate),\n )\n )\n\n for mcp_resource in resources_iterable:\n # Support both attribute-style objects and dict-like responses\n if hasattr(mcp_resource, \"name\"):\n name = mcp_resource.name\n description = mcp_resource.description\n uri = mcp_resource.uri\n elif isinstance(mcp_resource, dict):\n # assume mapping\n name = mcp_resource[\"name\"]\n description = mcp_resource.get(\"description\")\n uri = mcp_resource.get(\"uri\", \"\")\n else:\n raise ValueError(f\"Unexpected resource format: {mcp_resource}\")\n\n # Extract placeholders from the chosen source\n uri = decode_uri(str(uri))\n placeholders = re.findall(r\"\\{([^}]+)\\}\", uri) if uri else []\n properties: Dict[str, Any] = {}\n for param_name in placeholders:\n properties[param_name] = {\"type\": \"string\", \"description\": f\"URI parameter {param_name}\"}\n\n resources.append(\n MCPResourceDefinition(\n name=name,\n description=description,\n uri=uri,\n mime_type=getattr(mcp_resource, \"mimeType\", None),\n input_schema={\"type\": \"object\", \"properties\": properties, \"required\": list(placeholders)},\n )\n )\n\n if not resources:\n logger.warning(\"No resources found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list resources via MCP session: %s\", e, exc_info=True)\n raise\n\n return resources\n\n async def fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from the configured endpoint.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n prompts: List[MCPPromptDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n prompts = await self.fetch_prompt_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during prompt fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return prompts\n\n @staticmethod\n async def fetch_prompt_definitions_from_session(session: ClientSession) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of prompt definitions\n \"\"\"\n prompts: List[MCPPromptDefinition] = []\n try:\n await session.initialize()\n response: types.ListPromptsResult = await session.list_prompts()\n for mcp_prompt in response.prompts:\n arguments: List[types.PromptArgument] = mcp_prompt.arguments or []\n prompts.append(\n MCPPromptDefinition(\n name=mcp_prompt.name,\n description=mcp_prompt.description,\n input_schema={\n \"type\": \"object\",\n \"properties\": {arg.name: {\"type\": \"string\", \"description\": arg.description} for arg in arguments},\n \"required\": [arg.name for arg in arguments if arg.required],\n },\n )\n )\n if not prompts:\n logger.warning(\"No prompts found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list prompts via MCP session: %s\", e, exc_info=True)\n raise\n\n return prompts", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 14667, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPDefinitionService:\n \"\"\"Service for fetching tool definitions from MCP endpoints.\"\"\"\n\n def __init__(\n self,\n endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the service.\n\n Args:\n endpoint: URL of the MCP server (for SSE/HTTP stream) or command string (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.endpoint = endpoint\n self.transport_type = transport_type\n self.working_directory = working_directory\n\n async def fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from the configured endpoint.\n\n Returns:\n List of tool definitions\n\n Raises:\n ConnectionError: If connection to the MCP server fails\n ValueError: If the STDIO command string is empty\n RuntimeError: For other unexpected errors\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n definitions = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n # STDIO transport\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.info(f\"Attempting STDIO connection with command='{command}', args={args}\")\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n logger.info(f\"Attempting HTTP Stream connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n transport_endpoint = f\"{self.endpoint}/sse\"\n logger.info(f\"Attempting SSE connection to {transport_endpoint}\")\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n definitions = await self.fetch_tool_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP tool definitions from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during tool definition fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return definitions\n\n @staticmethod\n async def fetch_tool_definitions_from_session(session: ClientSession) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of tool definitions\n\n Raises:\n Exception: If listing tools fails\n \"\"\"\n definitions: List[MCPToolDefinition] = []\n try:\n # `initialize` is idempotent – calling it twice is safe and\n # ensures the session is ready.\n await session.initialize()\n response = await session.list_tools()\n for mcp_tool in response.tools:\n # Capture outputSchema if the MCP server provides one\n output_schema = getattr(mcp_tool, \"outputSchema\", None)\n definitions.append(\n MCPToolDefinition(\n name=mcp_tool.name,\n description=mcp_tool.description,\n input_schema=mcp_tool.inputSchema or {\"type\": \"object\", \"properties\": {}},\n output_schema=output_schema,\n )\n )\n\n if not definitions:\n logger.warning(\"No tool definitions found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list tools via MCP session: %s\", e, exc_info=True)\n raise\n\n return definitions\n\n async def fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from the configured endpoint.\n\n Returns:\n List of resource definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n resources: List[MCPResourceDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n resources = await self.fetch_resource_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP resources from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during resource fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return resources\n\n @staticmethod\n async def fetch_resource_definitions_from_session(session: ClientSession) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of resource definitions\n \"\"\"\n resources: List[MCPResourceDefinition] = []\n\n try:\n await session.initialize()\n response: types.ListResourcesResult = await session.list_resources()\n\n resources_iterable: List[types.Resource] = list(response.resources or [])\n\n if not resources_iterable:\n res_templates: types.ListResourceTemplatesResult = await session.list_resource_templates()\n for template in res_templates.resourceTemplates:\n # Resources have no \"input_schema\" value and use URI templates with parameters.\n resources_iterable.append(\n types.Resource(\n name=template.name,\n description=template.description,\n uri=AnyUrl(template.uriTemplate),\n )\n )\n\n for mcp_resource in resources_iterable:\n # Support both attribute-style objects and dict-like responses\n if hasattr(mcp_resource, \"name\"):\n name = mcp_resource.name\n description = mcp_resource.description\n uri = mcp_resource.uri\n elif isinstance(mcp_resource, dict):\n # assume mapping\n name = mcp_resource[\"name\"]\n description = mcp_resource.get(\"description\")\n uri = mcp_resource.get(\"uri\", \"\")\n else:\n raise ValueError(f\"Unexpected resource format: {mcp_resource}\")\n\n # Extract placeholders from the chosen source\n uri = decode_uri(str(uri))\n placeholders = re.findall(r\"\\{([^}]+)\\}\", uri) if uri else []\n properties: Dict[str, Any] = {}\n for param_name in placeholders:\n properties[param_name] = {\"type\": \"string\", \"description\": f\"URI parameter {param_name}\"}\n\n resources.append(\n MCPResourceDefinition(\n name=name,\n description=description,\n uri=uri,\n mime_type=getattr(mcp_resource, \"mimeType\", None),\n input_schema={\"type\": \"object\", \"properties\": properties, \"required\": list(placeholders)},\n )\n )\n\n if not resources:\n logger.warning(\"No resources found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list resources via MCP session: %s\", e, exc_info=True)\n raise\n\n return resources\n\n async def fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from the configured endpoint.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if not self.endpoint:\n raise ValueError(\"Endpoint is required\")\n\n prompts: List[MCPPromptDefinition] = []\n stack = AsyncExitStack()\n try:\n if self.transport_type == MCPTransportType.STDIO:\n command_parts = shlex.split(self.endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n server_params = StdioServerParameters(command=command, args=args, env=None, cwd=self.working_directory)\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif self.transport_type == MCPTransportType.HTTP_STREAM:\n transport_endpoint = f\"{self.endpoint}/mcp/\"\n transport = await stack.enter_async_context(streamablehttp_client(transport_endpoint))\n read_stream, write_stream, _ = transport\n elif self.transport_type == MCPTransportType.SSE:\n transport_endpoint = f\"{self.endpoint}/sse\"\n transport = await stack.enter_async_context(sse_client(transport_endpoint))\n read_stream, write_stream = transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(f\"Unknown transport type: {self.transport_type}. Available types: {available_types}\")\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n prompts = await self.fetch_prompt_definitions_from_session(session)\n\n except ConnectionError as e:\n logger.error(f\"Error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise\n except Exception as e:\n logger.error(f\"Unexpected error fetching MCP prompts from {self.endpoint}: {e}\", exc_info=True)\n raise RuntimeError(f\"Unexpected error during prompt fetching: {e}\") from e\n finally:\n await stack.aclose()\n\n return prompts\n\n @staticmethod\n async def fetch_prompt_definitions_from_session(session: ClientSession) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt/template definitions from an existing session.\n\n Args:\n session: MCP client session\n\n Returns:\n List of prompt definitions\n \"\"\"\n prompts: List[MCPPromptDefinition] = []\n try:\n await session.initialize()\n response: types.ListPromptsResult = await session.list_prompts()\n for mcp_prompt in response.prompts:\n arguments: List[types.PromptArgument] = mcp_prompt.arguments or []\n prompts.append(\n MCPPromptDefinition(\n name=mcp_prompt.name,\n description=mcp_prompt.description,\n input_schema={\n \"type\": \"object\",\n \"properties\": {arg.name: {\"type\": \"string\", \"description\": arg.description} for arg in arguments},\n \"required\": [arg.name for arg in arguments if arg.required],\n },\n )\n )\n if not prompts:\n logger.warning(\"No prompts found on MCP server\")\n\n except Exception as e:\n logger.error(\"Failed to list prompts via MCP session: %s\", e, exc_info=True)\n raise\n\n return prompts", "n_chars_compressed": 14667, "compression_ratio": 1.0}, "atomic-agents/tests/base/test_base_tool.py::56": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_with_config", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::134": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_clean_markdown", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::64": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "SearXNGSearchToolOutputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_category", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/agents/test_atomic_agent.py::796": {"resolved_imports": ["atomic-agents/atomic_agents/agents/atomic_agent.py", "atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/context/system_prompt_generator.py", "atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["AgentConfig", "AtomicAgent", "BasicChatInputSchema", "BasicChatOutputSchema", "Mock", "TokenCountResult", "patch"], "enclosing_function": "test_get_context_token_count_basic", "extracted_code": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 26519, "extracted_code_full": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_chars_compressed": 26519, "compression_ratio": 1.0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::72": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "BoChaSearchToolOutputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_format_tool_message.py::90": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["BaseIOSchema", "format_tool_message"], "enclosing_function": "test_format_tool_message_with_complex_model", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1460, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 1460, "compression_ratio": 1.0}, "atomic-agents/tests/context/test_chat_history.py::87": {"resolved_imports": ["atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_add_message", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::36": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_config_with_values", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::98": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::97": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::60": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "SearXNGSearchToolOutputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_category", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::224": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "os", "pytest"], "enclosing_function": "test_bocha_search_tool_config_params_real_case_cn", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::52": {"resolved_imports": [], "used_names": ["MagicMock", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "YouTubeTranscriptToolOutputSchema", "datetime", "patch"], "enclosing_function": "test_youtube_transcript_tool", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::42": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseIOSchema"], "enclosing_function": "test_base_tool_initialization_without_type_parameters", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 549, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 549, "compression_ratio": 1.0}, "atomic-agents/tests/utils/test_token_counter.py::180": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCounter", "patch", "pytest"], "enclosing_function": "test_count_context", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 5801, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_chars_compressed": 5801, "compression_ratio": 1.0}, "atomic-agents/tests/base/test_base_tool.py::50": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_base_tool_initialization", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-agents/tests/agents/test_atomic_agent.py::416": {"resolved_imports": ["atomic-agents/atomic_agents/agents/atomic_agent.py", "atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/context/system_prompt_generator.py", "atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["BasicChatInputSchema", "BasicChatOutputSchema", "pytest"], "enclosing_function": "test_run_async_stream", "extracted_code": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 671, "extracted_code_full": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )", "n_chars_compressed": 671, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::63": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "SearXNGSearchToolOutputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_category", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_format_tool_message.py::38": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_without_tool_id", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::266": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_error", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/agents/test_atomic_agent.py::351": {"resolved_imports": ["atomic-agents/atomic_agents/agents/atomic_agent.py", "atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/context/system_prompt_generator.py", "atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["AgentConfig", "AtomicAgent", "BasicChatInputSchema", "BasicChatOutputSchema", "ChatHistory"], "enclosing_function": "test_messages_sync_after_run", "extracted_code": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\ndef __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n def initialize_turn(self) -> None:\n \"\"\"Initializes a new turn by generating a random turn ID.\"\"\"\n ...\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"Adds a message to the chat history and manages overflow.\"\"\"\n ...\n def _manage_overflow(self) -> None:\n \"\"\"Manages the chat history overflow based on max_messages constraint.\"\"\"\n ...\n def get_history(self) -> List[Dict]:\n \"\"\"Retrieves the chat history, handling both regular and multimodal content.\"\"\"\n ...\n def _extract_multimodal_info(obj):\n \"\"\"Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\"\"\"\n ...\n def copy(self) -> \"ChatHistory\":\n \"\"\"Creates a copy of the chat history.\"\"\"\n ...\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"Returns the current turn ID.\"\"\"\n ...\n def delete_turn_id(self, turn_id: int):\n \"\"\"Delete messages from the history by its turn ID.\"\"\"\n ...\n def get_message_count(self) -> int:\n \"\"\"Returns the number of messages in the chat history.\"\"\"\n ...\n def dump(self) -> str:\n \"\"\"Serializes the entire ChatHistory instance to a JSON string.\"\"\"\n ...\n def load(self, serialized_data: str) -> None:\n \"\"\"Deserializes a JSON string and loads it into the ChatHistory instance.\"\"\"\n ...\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"Retrieves a class object from its string representation.\"\"\"\n ...\n def _process_multimodal_paths(self, obj):\n \"\"\"Process multimodal objects to convert string paths to Path objects.\"\"\"\n ...", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 38113, "extracted_code_full": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\n \"\"\"\n Manages the chat history for an AI agent.\n\n Attributes:\n history (List[Message]): A list of messages representing the chat history.\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n current_turn_id (Optional[str]): The ID of the current turn.\n \"\"\"\n\n def __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n\n def initialize_turn(self) -> None:\n \"\"\"\n Initializes a new turn by generating a random turn ID.\n \"\"\"\n self.current_turn_id = str(uuid.uuid4())\n\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"\n Adds a message to the chat history and manages overflow.\n\n Args:\n role (str): The role of the message sender.\n content (BaseIOSchema): The content of the message.\n \"\"\"\n if self.current_turn_id is None:\n self.initialize_turn()\n\n message = Message(\n role=role,\n content=content,\n turn_id=self.current_turn_id,\n )\n self.history.append(message)\n self._manage_overflow()\n\n def _manage_overflow(self) -> None:\n \"\"\"\n Manages the chat history overflow based on max_messages constraint.\n \"\"\"\n if self.max_messages is not None:\n while len(self.history) > self.max_messages:\n self.history.pop(0)\n\n def get_history(self) -> List[Dict]:\n \"\"\"\n Retrieves the chat history, handling both regular and multimodal content.\n\n Returns:\n List[Dict]: The list of messages in the chat history as dictionaries.\n Each dictionary has 'role' and 'content' keys, where 'content' contains\n either a single JSON string or a mixed array of JSON and multimodal objects.\n\n Note:\n This method supports multimodal content at any nesting depth by\n recursively extracting multimodal objects and using Pydantic's\n model_dump_json(exclude=...) for proper serialization of remaining fields.\n \"\"\"\n history = []\n for message in self.history:\n input_content = message.content\n multimodal_objects, exclude_spec = self._extract_multimodal_info(input_content)\n\n if multimodal_objects:\n processed_content = []\n content_json = input_content.model_dump_json(exclude=exclude_spec)\n if content_json and content_json != \"{}\":\n processed_content.append(content_json)\n processed_content.extend(multimodal_objects)\n history.append({\"role\": message.role, \"content\": processed_content})\n else:\n content_json = input_content.model_dump_json()\n history.append({\"role\": message.role, \"content\": content_json})\n\n return history\n\n @staticmethod\n def _extract_multimodal_info(obj):\n \"\"\"\n Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\n\n Walks the object tree to find all Instructor multimodal types (Image, Audio, PDF)\n at any nesting depth, collecting them into a flat list and building an exclude\n specification that can be passed to model_dump_json(exclude=...).\n\n Args:\n obj: The object to inspect (BaseIOSchema, list, dict, or primitive).\n\n Returns:\n tuple: (multimodal_objects, exclude_spec) where:\n - multimodal_objects: flat list of all multimodal objects found\n - exclude_spec: Pydantic exclude dict, True (exclude entirely), or None\n \"\"\"\n if isinstance(obj, INSTRUCTOR_MULTIMODAL_TYPES):\n return [obj], True\n\n if hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n all_objects = []\n exclude = {}\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n field_value = getattr(obj, field_name)\n objects, sub_exclude = ChatHistory._extract_multimodal_info(field_value)\n if objects:\n all_objects.extend(objects)\n exclude[field_name] = sub_exclude\n return all_objects, (exclude if exclude else None)\n\n if isinstance(obj, (list, tuple)):\n all_objects = []\n exclude = {}\n for i, item in enumerate(obj):\n objects, sub_exclude = ChatHistory._extract_multimodal_info(item)\n if objects:\n all_objects.extend(objects)\n exclude[i] = sub_exclude\n if not all_objects:\n return [], None\n # If every item in the list is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n if isinstance(obj, dict):\n all_objects = []\n exclude = {}\n for k, v in obj.items():\n objects, sub_exclude = ChatHistory._extract_multimodal_info(v)\n if objects:\n all_objects.extend(objects)\n exclude[k] = sub_exclude\n if not all_objects:\n return [], None\n # If every value in the dict is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n return [], None\n\n def copy(self) -> \"ChatHistory\":\n \"\"\"\n Creates a copy of the chat history.\n\n Returns:\n ChatHistory: A copy of the chat history.\n \"\"\"\n new_history = ChatHistory(max_messages=self.max_messages)\n new_history.load(self.dump())\n new_history.current_turn_id = self.current_turn_id\n return new_history\n\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"\n Returns the current turn ID.\n\n Returns:\n Optional[str]: The current turn ID, or None if not set.\n \"\"\"\n return self.current_turn_id\n\n def delete_turn_id(self, turn_id: int):\n \"\"\"\n Delete messages from the history by its turn ID.\n\n Args:\n turn_id (int): The turn ID of the message to delete.\n\n Returns:\n str: A success message with the deleted turn ID.\n\n Raises:\n ValueError: If the specified turn ID is not found in the history.\n \"\"\"\n initial_length = len(self.history)\n self.history = [msg for msg in self.history if msg.turn_id != turn_id]\n\n if len(self.history) == initial_length:\n raise ValueError(f\"Turn ID {turn_id} not found in history.\")\n\n # Update current_turn_id if necessary\n if not len(self.history):\n self.current_turn_id = None\n elif turn_id == self.current_turn_id:\n # Always update to the last message's turn_id\n self.current_turn_id = self.history[-1].turn_id\n\n def get_message_count(self) -> int:\n \"\"\"\n Returns the number of messages in the chat history.\n\n Returns:\n int: The number of messages.\n \"\"\"\n return len(self.history)\n\n def dump(self) -> str:\n \"\"\"\n Serializes the entire ChatHistory instance to a JSON string.\n\n Returns:\n str: A JSON string representation of the ChatHistory.\n \"\"\"\n serialized_history = []\n for message in self.history:\n content_class = message.content.__class__\n serialized_message = {\n \"role\": message.role,\n \"content\": {\n \"class_name\": f\"{content_class.__module__}.{content_class.__name__}\",\n \"data\": message.content.model_dump_json(),\n },\n \"turn_id\": message.turn_id,\n }\n serialized_history.append(serialized_message)\n\n history_data = {\n \"history\": serialized_history,\n \"max_messages\": self.max_messages,\n \"current_turn_id\": self.current_turn_id,\n }\n return json.dumps(history_data)\n\n def load(self, serialized_data: str) -> None:\n \"\"\"\n Deserializes a JSON string and loads it into the ChatHistory instance.\n\n Args:\n serialized_data (str): A JSON string representation of the ChatHistory.\n\n Raises:\n ValueError: If the serialized data is invalid or cannot be deserialized.\n \"\"\"\n try:\n history_data = json.loads(serialized_data)\n self.history = []\n self.max_messages = history_data[\"max_messages\"]\n self.current_turn_id = history_data[\"current_turn_id\"]\n\n for message_data in history_data[\"history\"]:\n content_info = message_data[\"content\"]\n content_class = self._get_class_from_string(content_info[\"class_name\"])\n content_instance = content_class.model_validate_json(content_info[\"data\"])\n\n # Process any Image objects to convert string paths back to Path objects\n self._process_multimodal_paths(content_instance)\n\n message = Message(role=message_data[\"role\"], content=content_instance, turn_id=message_data[\"turn_id\"])\n self.history.append(message)\n except (json.JSONDecodeError, KeyError, AttributeError, TypeError) as e:\n raise ValueError(f\"Invalid serialized data: {e}\")\n\n @staticmethod\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"\n Retrieves a class object from its string representation.\n\n Args:\n class_string (str): The fully qualified class name.\n\n Returns:\n Type[BaseIOSchema]: The class object.\n\n Raises:\n AttributeError: If the class cannot be found.\n \"\"\"\n module_name, class_name = class_string.rsplit(\".\", 1)\n module = __import__(module_name, fromlist=[class_name])\n return getattr(module, class_name)\n\n def _process_multimodal_paths(self, obj):\n \"\"\"\n Process multimodal objects to convert string paths to Path objects.\n\n Note: this is necessary only for PDF and Image instructor types. The from_path\n behavior is slightly different for Audio as it keeps the source as a string.\n\n Args:\n obj: The object to process.\n\n \"\"\"\n if isinstance(obj, (Image, PDF)) and isinstance(obj.source, str):\n # Check if the string looks like a file path (not a URL or base64 data)\n if not obj.source.startswith((\"http://\", \"https://\", \"data:\")):\n obj.source = Path(obj.source)\n elif isinstance(obj, list):\n # Process each item in the list\n for item in obj:\n self._process_multimodal_paths(item)\n elif isinstance(obj, dict):\n # Process each value in the dictionary\n for value in obj.values():\n self._process_multimodal_paths(value)\n elif hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n # Process each field of the Pydantic model\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n self._process_multimodal_paths(getattr(obj, field_name))\n elif hasattr(obj, \"__dict__\") and not isinstance(obj, Enum):\n # Process each attribute of the object\n for attr_name, attr_value in obj.__dict__.items():\n if attr_name != \"__pydantic_fields_set__\": # Skip pydantic internal fields\n self._process_multimodal_paths(attr_value)", "n_chars_compressed": 27979, "compression_ratio": 0.7341064728570305}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::220": {"resolved_imports": [], "used_names": ["BeautifulSoup"], "enclosing_function": "test_extract_main_content_fallbacks", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_token_counter.py::27": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCountResult"], "enclosing_function": "test_creation_with_all_fields", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 815, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_chars_compressed": 815, "compression_ratio": 1.0}, "atomic-agents/tests/utils/test_format_tool_message.py::89": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["BaseIOSchema", "format_tool_message"], "enclosing_function": "test_format_tool_message_with_complex_model", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1460, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n\n# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 1460, "compression_ratio": 1.0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::147": {"resolved_imports": [], "used_names": ["AsyncMock", "BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_no_results", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::103": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema"], "enclosing_function": "test_tavily_search_tool_sync_run_method", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::50": {"resolved_imports": [], "used_names": ["MagicMock", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "YouTubeTranscriptToolOutputSchema", "datetime", "patch"], "enclosing_function": "test_youtube_transcript_tool", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::310": {"resolved_imports": [], "used_names": ["WebpageScraperToolConfig"], "enclosing_function": "test_tool_config", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::71": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_mock_tool_run", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::37": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_custom_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::14": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_string_type_required", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::146": {"resolved_imports": [], "used_names": [], "enclosing_function": "test_clean_markdown_triple_newlines", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::39": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_custom_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-agents/tests/agents/test_atomic_agent.py::363": {"resolved_imports": ["atomic-agents/atomic_agents/agents/atomic_agent.py", "atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/context/system_prompt_generator.py", "atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["AgentConfig", "AtomicAgent", "BasicChatInputSchema", "BasicChatOutputSchema", "ChatHistory"], "enclosing_function": "test_messages_sync_after_run", "extracted_code": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\ndef __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n def initialize_turn(self) -> None:\n \"\"\"Initializes a new turn by generating a random turn ID.\"\"\"\n ...\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"Adds a message to the chat history and manages overflow.\"\"\"\n ...\n def _manage_overflow(self) -> None:\n \"\"\"Manages the chat history overflow based on max_messages constraint.\"\"\"\n ...\n def get_history(self) -> List[Dict]:\n \"\"\"Retrieves the chat history, handling both regular and multimodal content.\"\"\"\n ...\n def _extract_multimodal_info(obj):\n \"\"\"Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\"\"\"\n ...\n def copy(self) -> \"ChatHistory\":\n \"\"\"Creates a copy of the chat history.\"\"\"\n ...\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"Returns the current turn ID.\"\"\"\n ...\n def delete_turn_id(self, turn_id: int):\n \"\"\"Delete messages from the history by its turn ID.\"\"\"\n ...\n def get_message_count(self) -> int:\n \"\"\"Returns the number of messages in the chat history.\"\"\"\n ...\n def dump(self) -> str:\n \"\"\"Serializes the entire ChatHistory instance to a JSON string.\"\"\"\n ...\n def load(self, serialized_data: str) -> None:\n \"\"\"Deserializes a JSON string and loads it into the ChatHistory instance.\"\"\"\n ...\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"Retrieves a class object from its string representation.\"\"\"\n ...\n def _process_multimodal_paths(self, obj):\n \"\"\"Process multimodal objects to convert string paths to Path objects.\"\"\"\n ...", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 38113, "extracted_code_full": "# Source: atomic-agents/atomic_agents/agents/atomic_agent.py\nclass BasicChatInputSchema(BaseIOSchema):\n \"\"\"This schema represents the input from the user to the AI agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=\"The chat message sent by the user to the assistant.\",\n )\n\nclass BasicChatOutputSchema(BaseIOSchema):\n \"\"\"This schema represents the response generated by the chat agent.\"\"\"\n\n chat_message: str = Field(\n ...,\n description=(\n \"The chat message exchanged between the user and the chat agent. \"\n \"This contains the markdown-enabled response generated by the chat agent.\"\n ),\n )\n\nclass AgentConfig(BaseModel):\n client: instructor.client.Instructor = Field(..., description=\"Client for interacting with the language model.\")\n model: str = Field(default=\"gpt-5-mini\", description=\"The model to use for generating responses.\")\n history: Optional[ChatHistory] = Field(default=None, description=\"History component for storing chat history.\")\n system_prompt_generator: Optional[SystemPromptGenerator] = Field(\n default=None, description=\"Component for generating system prompts.\"\n )\n system_role: Optional[str] = Field(\n default=\"system\", description=\"The role of the system in the conversation. None means no system prompt.\"\n )\n assistant_role: str = Field(\n default=\"assistant\",\n description=\"The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\",\n )\n model_config = {\"arbitrary_types_allowed\": True}\n mode: Mode = Field(default=Mode.TOOLS, description=\"The Instructor mode used for structured outputs (TOOLS, JSON, etc.).\")\n model_api_parameters: Optional[dict] = Field(None, description=\"Additional parameters passed to the API provider.\")\n\nclass AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:\n \"\"\"\n Base class for chat agents with full Instructor hook system integration.\n\n This class provides the core functionality for handling chat interactions, including managing history,\n generating system prompts, and obtaining responses from a language model. It includes comprehensive\n hook system support for monitoring and error handling.\n\n Type Parameters:\n InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.\n OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.\n\n Attributes:\n client: Client for interacting with the language model.\n model (str): The model to use for generating responses.\n history (ChatHistory): History component for storing chat history.\n system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.\n system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.\n assistant_role (str): The role of the assistant in the conversation. Use 'model' for Gemini, 'assistant' for OpenAI/Anthropic.\n initial_history (ChatHistory): Initial state of the history.\n current_user_input (Optional[InputSchema]): The current user input being processed.\n model_api_parameters (dict): Additional parameters passed to the API provider.\n - Use this for parameters like 'temperature', 'max_tokens', etc.\n\n Hook System:\n The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring\n and error handling capabilities. Supported events include:\n\n - 'parse:error': Triggered when Pydantic validation fails\n - 'completion:kwargs': Triggered before completion request\n - 'completion:response': Triggered after completion response\n - 'completion:error': Triggered on completion errors\n - 'completion:last_attempt': Triggered on final retry attempt\n\n Hook Methods:\n - register_hook(event, handler): Register a hook handler for an event\n - unregister_hook(event, handler): Remove a hook handler\n - clear_hooks(event=None): Clear hooks for specific event or all events\n - enable_hooks()/disable_hooks(): Control hook processing\n - hooks_enabled: Property to check if hooks are enabled\n\n Example:\n ```python\n # Basic usage\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Register parse error hook for intelligent retry handling\n def handle_parse_error(error):\n print(f\"Validation failed: {error}\")\n # Implement custom retry logic, logging, etc.\n\n agent.register_hook(\"parse:error\", handle_parse_error)\n\n # Now parse:error hooks will fire on validation failures\n response = agent.run(user_input)\n ```\n \"\"\"\n\n @classmethod\n def __init_subclass__(cls, **kwargs):\n \"\"\"\n Hook called when a class is subclassed.\n\n Captures generic type parameters during class creation and stores them as class attributes\n to work around the unreliable __orig_class__ attribute in modern Python generic syntax.\n \"\"\"\n super().__init_subclass__(**kwargs)\n if hasattr(cls, \"__orig_bases__\"):\n for base in cls.__orig_bases__:\n if get_origin(base) is AtomicAgent:\n args = get_args(base)\n if len(args) == 2:\n cls._input_schema_cls = args[0]\n cls._output_schema_cls = args[1]\n break\n\n def __init__(self, config: AgentConfig):\n \"\"\"\n Initializes the AtomicAgent.\n\n Args:\n config (AgentConfig): Configuration for the chat agent.\n \"\"\"\n self.client = config.client\n self.model = config.model\n self.history = config.history or ChatHistory()\n self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()\n self.system_role = config.system_role\n self.assistant_role = config.assistant_role\n self.initial_history = self.history.copy()\n self.current_user_input = None\n self.mode = config.mode\n self.model_api_parameters = config.model_api_parameters or {}\n\n # Hook management attributes\n self._hook_handlers: Dict[str, List[Callable]] = {}\n self._hooks_enabled: bool = True\n\n def reset_history(self):\n \"\"\"\n Resets the history to its initial state.\n \"\"\"\n self.history = self.initial_history.copy()\n\n @property\n def input_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the input schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_input_schema_cls\"):\n return self.__class__._input_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n TI, _ = get_args(self.__orig_class__)\n return TI\n\n # No type info available\n return BasicChatInputSchema\n\n @property\n def output_schema(self) -> Type[BaseIOSchema]:\n \"\"\"\n Returns the output schema for the agent.\n\n Uses a three-level fallback mechanism:\n 1. Class attributes from __init_subclass__ (handles subclassing)\n 2. Instance __orig_class__ (handles direct instantiation)\n 3. Default schema (handles untyped usage)\n \"\"\"\n # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])\n if hasattr(self.__class__, \"_output_schema_cls\"):\n return self.__class__._output_schema_cls\n\n # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()\n if hasattr(self, \"__orig_class__\"):\n _, TO = get_args(self.__orig_class__)\n return TO\n\n # No type info available\n return BasicChatOutputSchema\n\n def _build_system_messages(self) -> List[Dict]:\n \"\"\"\n Builds the system message(s) based on the configured system role.\n\n Returns:\n List[Dict]: A list containing the system message, or an empty list if system_role is None.\n \"\"\"\n if self.system_role is None:\n return []\n return [\n {\n \"role\": self.system_role,\n \"content\": self.system_prompt_generator.generate_prompt(),\n }\n ]\n\n def _prepare_messages(self):\n self.messages = self._build_system_messages()\n self.messages += self.history.get_history()\n\n def _build_tools_definition(self) -> Optional[List[Dict[str, Any]]]:\n \"\"\"\n Build the tools definition that Instructor sends for TOOLS mode.\n\n This uses Instructor's actual schema generation to create the exact\n tools parameter that would be sent to the LLM for TOOLS mode.\n For JSON modes, returns None as the schema is embedded in messages.\n\n Returns:\n Optional[List[Dict[str, Any]]]: Tools definition for TOOLS mode, or None for JSON modes.\n \"\"\"\n from instructor.processing.schema import generate_openai_schema\n\n # Only return tools for TOOLS-based modes\n tools_modes = {Mode.TOOLS, Mode.TOOLS_STRICT, Mode.PARALLEL_TOOLS}\n if self.mode in tools_modes:\n return [\n {\n \"type\": \"function\",\n \"function\": generate_openai_schema(self.output_schema),\n }\n ]\n return None\n\n def _build_schema_for_json_mode(self) -> str:\n \"\"\"\n Build the schema context for JSON modes (appended to system message).\n\n This matches exactly how Instructor formats the schema for JSON/MD_JSON modes.\n\n Returns:\n str: JSON schema string formatted as Instructor does.\n \"\"\"\n from textwrap import dedent\n\n schema = self.output_schema.model_json_schema()\n return dedent(\n f\"\"\"\n As a genius expert, your task is to understand the content and provide\n the parsed objects in json that match the following json_schema:\n\n {json.dumps(schema, indent=2, ensure_ascii=False)}\n\n Make sure to return an instance of the JSON, not the schema itself\n \"\"\"\n ).strip()\n\n def _serialize_history_for_token_count(self) -> List[Dict[str, Any]]:\n \"\"\"\n Serialize conversation history for token counting, handling multimodal content.\n\n This method converts instructor multimodal objects (Image, Audio, PDF) to the\n OpenAI format that LiteLLM's token counter expects. Text content is also\n converted to the proper multimodal text format when mixed with media.\n\n Returns:\n List[Dict[str, Any]]: History messages in LiteLLM-compatible format.\n \"\"\"\n history = self.history.get_history()\n serialized = []\n\n for message in history:\n content = message.get(\"content\")\n\n if isinstance(content, list):\n # Multimodal content - convert to OpenAI format\n serialized_content = []\n for item in content:\n if isinstance(item, str):\n # Text content - wrap in OpenAI text format\n serialized_content.append({\"type\": \"text\", \"text\": item})\n elif isinstance(item, (Image, Audio, PDF)):\n # Multimodal object - use instructor's to_openai method\n try:\n serialized_content.append(item.to_openai(Mode.JSON))\n except Exception as e:\n # Log the error and use placeholder for token estimation\n logger = logging.getLogger(__name__)\n media_type = type(item).__name__\n logger.warning(\n f\"Failed to serialize {media_type} for token counting: {e}. \"\n f\"Using placeholder for estimation.\"\n )\n serialized_content.append({\"type\": \"text\", \"text\": f\"[{media_type.lower()} content]\"})\n else:\n # Unknown type - convert to string\n serialized_content.append({\"type\": \"text\", \"text\": str(item)})\n serialized.append({\"role\": message[\"role\"], \"content\": serialized_content})\n else:\n # Simple text content - keep as is\n serialized.append(message)\n\n return serialized\n\n def get_context_token_count(self) -> TokenCountResult:\n \"\"\"\n Get the accurate token count for the current context.\n\n This method computes the token count by serializing the context exactly\n as Instructor does, including:\n - System prompt\n - Conversation history (with multimodal content serialized properly)\n - Tools/schema overhead (using Instructor's actual schema generation)\n\n For TOOLS mode: Uses the actual tools parameter that Instructor sends.\n For JSON modes: Appends the schema to the system message as Instructor does.\n\n Works with any model supported by LiteLLM including OpenAI, Anthropic,\n Google, and 100+ other providers.\n\n Returns:\n TokenCountResult: A named tuple containing:\n - total: Total tokens in the context (including schema overhead)\n - system_prompt: Tokens in the system prompt\n - history: Tokens in the conversation history\n - tools: Tokens in the tools/function definitions (TOOLS mode only)\n - model: The model used for counting\n - max_tokens: Maximum context window (if known)\n - utilization: Percentage of context used (if max_tokens known)\n\n Example:\n ```python\n agent = AtomicAgent[InputSchema, OutputSchema](config)\n\n # Get accurate token count at any time\n result = agent.get_context_token_count()\n print(f\"Total: {result.total} tokens\")\n print(f\"System: {result.system_prompt} tokens\")\n print(f\"History: {result.history} tokens\")\n print(f\"Tools: {result.tools} tokens\")\n if result.utilization:\n print(f\"Context usage: {result.utilization:.1%}\")\n ```\n\n Note:\n The 'token:counted' hook event is dispatched, allowing for\n monitoring and logging of token usage.\n \"\"\"\n counter = get_token_counter()\n\n # Build system messages\n system_messages = self._build_system_messages()\n\n # Handle schema serialization based on mode\n tools = self._build_tools_definition()\n\n if tools is None:\n # JSON mode - append schema to system message like Instructor does\n schema_context = self._build_schema_for_json_mode()\n if system_messages:\n system_messages = [\n {\n \"role\": system_messages[0][\"role\"],\n \"content\": system_messages[0][\"content\"] + \"\\n\\n\" + schema_context,\n }\n ]\n else:\n system_messages = [{\"role\": \"system\", \"content\": schema_context}]\n\n result = counter.count_context(\n model=self.model,\n system_messages=system_messages,\n history_messages=self._serialize_history_for_token_count(),\n tools=tools,\n )\n\n # Dispatch hook for monitoring\n self._dispatch_hook(\"token:counted\", result)\n\n return result\n\n def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent with the given user input synchronously.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n response = self.client.chat.completions.create(\n messages=self.messages,\n model=self.model,\n response_model=self.output_schema,\n **self.model_api_parameters,\n )\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n\n return response\n\n def run_stream(self, user_input: Optional[InputSchema] = None) -> Generator[OutputSchema, None, OutputSchema]:\n \"\"\"\n Runs the chat agent with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n\n Returns:\n OutputSchema: The final response from the chat agent.\n \"\"\"\n assert not isinstance(\n self.client, instructor.client.AsyncInstructor\n ), \"The run_stream method is not supported for async clients. Use run_async instead.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n for partial_response in response_stream:\n yield partial_response\n\n full_response_content = self.output_schema(**partial_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n return full_response_content\n\n async def run_async(self, user_input: Optional[InputSchema] = None) -> OutputSchema:\n \"\"\"\n Runs the chat agent asynchronously with the given user input.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Returns:\n OutputSchema: The response from the chat agent.\n\n Raises:\n NotAsyncIterableError: If used as an async generator (in an async for loop).\n Use run_async_stream() method instead for streaming responses.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response = await self.client.chat.completions.create(\n model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters\n )\n\n self.history.add_message(self.assistant_role, response)\n self._prepare_messages()\n return response\n\n async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:\n \"\"\"\n Runs the chat agent asynchronously with the given user input, supporting streaming output.\n\n Args:\n user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.\n\n Yields:\n OutputSchema: Partial responses from the chat agent.\n \"\"\"\n assert isinstance(self.client, instructor.client.AsyncInstructor), \"The run_async method is for async clients.\"\n if user_input:\n self.history.initialize_turn()\n self.current_user_input = user_input\n self.history.add_message(\"user\", user_input)\n\n self._prepare_messages()\n\n response_stream = self.client.chat.completions.create_partial(\n model=self.model,\n messages=self.messages,\n response_model=self.output_schema,\n **self.model_api_parameters,\n stream=True,\n )\n\n last_response = None\n async for partial_response in response_stream:\n last_response = partial_response\n yield partial_response\n\n if last_response:\n full_response_content = self.output_schema(**last_response.model_dump())\n self.history.add_message(self.assistant_role, full_response_content)\n self._prepare_messages()\n\n def get_context_provider(self, provider_name: str) -> Type[BaseDynamicContextProvider]:\n \"\"\"\n Retrieves a context provider by name.\n\n Args:\n provider_name (str): The name of the context provider.\n\n Returns:\n BaseDynamicContextProvider: The context provider if found.\n\n Raises:\n KeyError: If the context provider is not found.\n \"\"\"\n if provider_name not in self.system_prompt_generator.context_providers:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n return self.system_prompt_generator.context_providers[provider_name]\n\n def register_context_provider(self, provider_name: str, provider: BaseDynamicContextProvider):\n \"\"\"\n Registers a new context provider.\n\n Args:\n provider_name (str): The name of the context provider.\n provider (BaseDynamicContextProvider): The context provider instance.\n \"\"\"\n self.system_prompt_generator.context_providers[provider_name] = provider\n\n def unregister_context_provider(self, provider_name: str):\n \"\"\"\n Unregisters an existing context provider.\n\n Args:\n provider_name (str): The name of the context provider to remove.\n \"\"\"\n if provider_name in self.system_prompt_generator.context_providers:\n del self.system_prompt_generator.context_providers[provider_name]\n else:\n raise KeyError(f\"Context provider '{provider_name}' not found.\")\n\n # Hook Management Methods\n def register_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Registers a hook handler for a specific event.\n\n Args:\n event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)\n handler (Callable): The callback function to handle the event\n \"\"\"\n if event not in self._hook_handlers:\n self._hook_handlers[event] = []\n self._hook_handlers[event].append(handler)\n\n # Register with instructor client if it supports hooks\n if hasattr(self.client, \"on\"):\n self.client.on(event, handler)\n\n def unregister_hook(self, event: str, handler: Callable) -> None:\n \"\"\"\n Unregisters a hook handler for a specific event.\n\n Args:\n event (str): The event name\n handler (Callable): The callback function to remove\n \"\"\"\n if event in self._hook_handlers and handler in self._hook_handlers[event]:\n self._hook_handlers[event].remove(handler)\n\n # Remove from instructor client if it supports hooks\n if hasattr(self.client, \"off\"):\n self.client.off(event, handler)\n\n def clear_hooks(self, event: Optional[str] = None) -> None:\n \"\"\"\n Clears hook handlers for a specific event or all events.\n\n Args:\n event (Optional[str]): The event name to clear, or None to clear all\n \"\"\"\n if event:\n if event in self._hook_handlers:\n # Clear from instructor client first\n if hasattr(self.client, \"clear\"):\n self.client.clear(event)\n self._hook_handlers[event].clear()\n else:\n # Clear all hooks\n if hasattr(self.client, \"clear\"):\n self.client.clear()\n self._hook_handlers.clear()\n\n def _dispatch_hook(self, event: str, *args, **kwargs) -> None:\n \"\"\"\n Internal method to dispatch hook events with error isolation.\n\n Args:\n event (str): The event name\n *args: Arguments to pass to handlers\n **kwargs: Keyword arguments to pass to handlers\n \"\"\"\n if not self._hooks_enabled or event not in self._hook_handlers:\n return\n\n for handler in self._hook_handlers[event]:\n try:\n handler(*args, **kwargs)\n except Exception as e:\n # Log error but don't interrupt main flow\n logger = logging.getLogger(__name__)\n logger.warning(f\"Hook handler for '{event}' raised exception: {e}\")\n\n def enable_hooks(self) -> None:\n \"\"\"Enable hook processing.\"\"\"\n self._hooks_enabled = True\n\n def disable_hooks(self) -> None:\n \"\"\"Disable hook processing.\"\"\"\n self._hooks_enabled = False\n\n @property\n def hooks_enabled(self) -> bool:\n \"\"\"Check if hooks are enabled.\"\"\"\n return self._hooks_enabled\n\n\n# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\n \"\"\"\n Manages the chat history for an AI agent.\n\n Attributes:\n history (List[Message]): A list of messages representing the chat history.\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n current_turn_id (Optional[str]): The ID of the current turn.\n \"\"\"\n\n def __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n\n def initialize_turn(self) -> None:\n \"\"\"\n Initializes a new turn by generating a random turn ID.\n \"\"\"\n self.current_turn_id = str(uuid.uuid4())\n\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"\n Adds a message to the chat history and manages overflow.\n\n Args:\n role (str): The role of the message sender.\n content (BaseIOSchema): The content of the message.\n \"\"\"\n if self.current_turn_id is None:\n self.initialize_turn()\n\n message = Message(\n role=role,\n content=content,\n turn_id=self.current_turn_id,\n )\n self.history.append(message)\n self._manage_overflow()\n\n def _manage_overflow(self) -> None:\n \"\"\"\n Manages the chat history overflow based on max_messages constraint.\n \"\"\"\n if self.max_messages is not None:\n while len(self.history) > self.max_messages:\n self.history.pop(0)\n\n def get_history(self) -> List[Dict]:\n \"\"\"\n Retrieves the chat history, handling both regular and multimodal content.\n\n Returns:\n List[Dict]: The list of messages in the chat history as dictionaries.\n Each dictionary has 'role' and 'content' keys, where 'content' contains\n either a single JSON string or a mixed array of JSON and multimodal objects.\n\n Note:\n This method supports multimodal content at any nesting depth by\n recursively extracting multimodal objects and using Pydantic's\n model_dump_json(exclude=...) for proper serialization of remaining fields.\n \"\"\"\n history = []\n for message in self.history:\n input_content = message.content\n multimodal_objects, exclude_spec = self._extract_multimodal_info(input_content)\n\n if multimodal_objects:\n processed_content = []\n content_json = input_content.model_dump_json(exclude=exclude_spec)\n if content_json and content_json != \"{}\":\n processed_content.append(content_json)\n processed_content.extend(multimodal_objects)\n history.append({\"role\": message.role, \"content\": processed_content})\n else:\n content_json = input_content.model_dump_json()\n history.append({\"role\": message.role, \"content\": content_json})\n\n return history\n\n @staticmethod\n def _extract_multimodal_info(obj):\n \"\"\"\n Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\n\n Walks the object tree to find all Instructor multimodal types (Image, Audio, PDF)\n at any nesting depth, collecting them into a flat list and building an exclude\n specification that can be passed to model_dump_json(exclude=...).\n\n Args:\n obj: The object to inspect (BaseIOSchema, list, dict, or primitive).\n\n Returns:\n tuple: (multimodal_objects, exclude_spec) where:\n - multimodal_objects: flat list of all multimodal objects found\n - exclude_spec: Pydantic exclude dict, True (exclude entirely), or None\n \"\"\"\n if isinstance(obj, INSTRUCTOR_MULTIMODAL_TYPES):\n return [obj], True\n\n if hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n all_objects = []\n exclude = {}\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n field_value = getattr(obj, field_name)\n objects, sub_exclude = ChatHistory._extract_multimodal_info(field_value)\n if objects:\n all_objects.extend(objects)\n exclude[field_name] = sub_exclude\n return all_objects, (exclude if exclude else None)\n\n if isinstance(obj, (list, tuple)):\n all_objects = []\n exclude = {}\n for i, item in enumerate(obj):\n objects, sub_exclude = ChatHistory._extract_multimodal_info(item)\n if objects:\n all_objects.extend(objects)\n exclude[i] = sub_exclude\n if not all_objects:\n return [], None\n # If every item in the list is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n if isinstance(obj, dict):\n all_objects = []\n exclude = {}\n for k, v in obj.items():\n objects, sub_exclude = ChatHistory._extract_multimodal_info(v)\n if objects:\n all_objects.extend(objects)\n exclude[k] = sub_exclude\n if not all_objects:\n return [], None\n # If every value in the dict is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n return [], None\n\n def copy(self) -> \"ChatHistory\":\n \"\"\"\n Creates a copy of the chat history.\n\n Returns:\n ChatHistory: A copy of the chat history.\n \"\"\"\n new_history = ChatHistory(max_messages=self.max_messages)\n new_history.load(self.dump())\n new_history.current_turn_id = self.current_turn_id\n return new_history\n\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"\n Returns the current turn ID.\n\n Returns:\n Optional[str]: The current turn ID, or None if not set.\n \"\"\"\n return self.current_turn_id\n\n def delete_turn_id(self, turn_id: int):\n \"\"\"\n Delete messages from the history by its turn ID.\n\n Args:\n turn_id (int): The turn ID of the message to delete.\n\n Returns:\n str: A success message with the deleted turn ID.\n\n Raises:\n ValueError: If the specified turn ID is not found in the history.\n \"\"\"\n initial_length = len(self.history)\n self.history = [msg for msg in self.history if msg.turn_id != turn_id]\n\n if len(self.history) == initial_length:\n raise ValueError(f\"Turn ID {turn_id} not found in history.\")\n\n # Update current_turn_id if necessary\n if not len(self.history):\n self.current_turn_id = None\n elif turn_id == self.current_turn_id:\n # Always update to the last message's turn_id\n self.current_turn_id = self.history[-1].turn_id\n\n def get_message_count(self) -> int:\n \"\"\"\n Returns the number of messages in the chat history.\n\n Returns:\n int: The number of messages.\n \"\"\"\n return len(self.history)\n\n def dump(self) -> str:\n \"\"\"\n Serializes the entire ChatHistory instance to a JSON string.\n\n Returns:\n str: A JSON string representation of the ChatHistory.\n \"\"\"\n serialized_history = []\n for message in self.history:\n content_class = message.content.__class__\n serialized_message = {\n \"role\": message.role,\n \"content\": {\n \"class_name\": f\"{content_class.__module__}.{content_class.__name__}\",\n \"data\": message.content.model_dump_json(),\n },\n \"turn_id\": message.turn_id,\n }\n serialized_history.append(serialized_message)\n\n history_data = {\n \"history\": serialized_history,\n \"max_messages\": self.max_messages,\n \"current_turn_id\": self.current_turn_id,\n }\n return json.dumps(history_data)\n\n def load(self, serialized_data: str) -> None:\n \"\"\"\n Deserializes a JSON string and loads it into the ChatHistory instance.\n\n Args:\n serialized_data (str): A JSON string representation of the ChatHistory.\n\n Raises:\n ValueError: If the serialized data is invalid or cannot be deserialized.\n \"\"\"\n try:\n history_data = json.loads(serialized_data)\n self.history = []\n self.max_messages = history_data[\"max_messages\"]\n self.current_turn_id = history_data[\"current_turn_id\"]\n\n for message_data in history_data[\"history\"]:\n content_info = message_data[\"content\"]\n content_class = self._get_class_from_string(content_info[\"class_name\"])\n content_instance = content_class.model_validate_json(content_info[\"data\"])\n\n # Process any Image objects to convert string paths back to Path objects\n self._process_multimodal_paths(content_instance)\n\n message = Message(role=message_data[\"role\"], content=content_instance, turn_id=message_data[\"turn_id\"])\n self.history.append(message)\n except (json.JSONDecodeError, KeyError, AttributeError, TypeError) as e:\n raise ValueError(f\"Invalid serialized data: {e}\")\n\n @staticmethod\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"\n Retrieves a class object from its string representation.\n\n Args:\n class_string (str): The fully qualified class name.\n\n Returns:\n Type[BaseIOSchema]: The class object.\n\n Raises:\n AttributeError: If the class cannot be found.\n \"\"\"\n module_name, class_name = class_string.rsplit(\".\", 1)\n module = __import__(module_name, fromlist=[class_name])\n return getattr(module, class_name)\n\n def _process_multimodal_paths(self, obj):\n \"\"\"\n Process multimodal objects to convert string paths to Path objects.\n\n Note: this is necessary only for PDF and Image instructor types. The from_path\n behavior is slightly different for Audio as it keeps the source as a string.\n\n Args:\n obj: The object to process.\n\n \"\"\"\n if isinstance(obj, (Image, PDF)) and isinstance(obj.source, str):\n # Check if the string looks like a file path (not a URL or base64 data)\n if not obj.source.startswith((\"http://\", \"https://\", \"data:\")):\n obj.source = Path(obj.source)\n elif isinstance(obj, list):\n # Process each item in the list\n for item in obj:\n self._process_multimodal_paths(item)\n elif isinstance(obj, dict):\n # Process each value in the dictionary\n for value in obj.values():\n self._process_multimodal_paths(value)\n elif hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n # Process each field of the Pydantic model\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n self._process_multimodal_paths(getattr(obj, field_name))\n elif hasattr(obj, \"__dict__\") and not isinstance(obj, Enum):\n # Process each attribute of the object\n for attr_name, attr_value in obj.__dict__.items():\n if attr_name != \"__pydantic_fields_set__\": # Skip pydantic internal fields\n self._process_multimodal_paths(attr_value)", "n_chars_compressed": 27979, "compression_ratio": 0.7341064728570305}, "atomic-agents/tests/utils/test_format_tool_message.py::22": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_with_provided_tool_id", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::262": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_error", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::194": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_concurrent_queries", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::178": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_no_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_token_counter.py::26": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCountResult"], "enclosing_function": "test_creation_with_all_fields", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 815, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_chars_compressed": 815, "compression_ratio": 1.0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::108": {"resolved_imports": [], "used_names": ["NoTranscriptFound", "YouTubeTranscriptTool", "YouTubeTranscriptToolConfig", "YouTubeTranscriptToolInputSchema", "patch", "pytest"], "enclosing_function": "test_youtube_transcript_tool_no_transcript", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::63": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_with_custom_title", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::123": {"resolved_imports": [], "used_names": ["AsyncMock", "BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_count", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_chat_history.py::110": {"resolved_imports": ["atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["json"], "enclosing_function": "test_get_history", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::128": {"resolved_imports": [], "used_names": ["AsyncMock", "BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_count", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_token_counter.py::25": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCountResult"], "enclosing_function": "test_creation_with_all_fields", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 815, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCountResult(NamedTuple):\n \"\"\"\n Result of a token count operation.\n\n Attributes:\n total: Total number of tokens in the context (messages + tools).\n system_prompt: Tokens in the system prompt (0 if no system prompt).\n history: Tokens in the conversation history.\n tools: Tokens in the tools/function definitions (0 if no tools).\n model: The model used for tokenization.\n max_tokens: Maximum context window for the model (None if unknown).\n utilization: Percentage of context window used (None if max_tokens unknown).\n \"\"\"\n\n total: int\n system_prompt: int\n history: int\n tools: int\n model: str\n max_tokens: Optional[int] = None\n utilization: Optional[float] = None", "n_chars_compressed": 815, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::26": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_integer_type_with_default", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::94": {"resolved_imports": [], "used_names": ["AsyncMock", "BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema"], "enclosing_function": "test_bocha_search_tool_sync_run", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::43": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseIOSchema"], "enclosing_function": "test_base_tool_initialization_without_type_parameters", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 549, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 549, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::62": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "SearXNGSearchToolOutputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_category", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::30": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_config_creation", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::221": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "os", "pytest"], "enclosing_function": "test_bocha_search_tool_config_params_real_case_cn", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_chat_history.py::76": {"resolved_imports": ["atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_initialization", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::140": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_with_max_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/agents/test_atomic_agent.py::480": {"resolved_imports": ["atomic-agents/atomic_agents/agents/atomic_agent.py", "atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/context/system_prompt_generator.py", "atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": [], "enclosing_function": "test_hook_initialization", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 5, "n_chars_extracted": 0}, "atomic-forge/tools/youtube_transcript_scraper/tests/test_youtube_transcript_scraper.py::151": {"resolved_imports": [], "used_names": ["YouTubeTranscriptTool", "YouTubeTranscriptToolConfig"], "enclosing_function": "test_extract_video_id", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::69": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::240": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_no_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::108": {"resolved_imports": [], "used_names": ["BeautifulSoup", "Document", "WebpageMetadata"], "enclosing_function": "test_extract_metadata", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::49": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_base_tool_initialization", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::81": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_base_tool_output_schema", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::67": {"resolved_imports": [], "used_names": ["TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::73": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "BoChaSearchToolOutputSchema", "asyncio", "pytest"], "enclosing_function": "test_bocha_search_tool_missing_fields", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_system_prompt_generator.py::16": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_default_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_mcp_factory.py::154": {"resolved_imports": ["atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py", "atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py"], "used_names": ["MCPFactory", "MCPToolDefinition", "MCPTransportType", "fetch_mcp_tools"], "enclosing_function": "test_fetch_mcp_tools_mixed_output_schemas", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\nclass MCPFactory:\ndef __init__(\n self,\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the factory.\n\n Args:\n mcp_endpoint: URL of the MCP server (for SSE/HTTP stream) or the full command to run the server (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n client_session: Optional pre-initialized ClientSession for reuse\n event_loop: Optional event loop for running asynchronous operations\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.mcp_endpoint = mcp_endpoint\n self.transport_type = transport_type\n self.client_session = client_session\n self.event_loop = event_loop\n self.schema_transformer = SchemaTransformer()\n self.working_directory = working_directory\n\n # Validate configuration\n if client_session is not None and event_loop is None:\n raise ValueError(\"When `client_session` is provided an `event_loop` must also be supplied.\")\n if not mcp_endpoint and client_session is None:\n raise ValueError(\"`mcp_endpoint` must be provided when no `client_session` is supplied.\")\n def create_tools(self) -> List[Type[BaseTool]]:\n \"\"\"Create tool classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"Fetch tool definitions using the appropriate method.\"\"\"\n ...\n def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:\n \"\"\"Create tool classes from definitions.\"\"\"\n ...\n def create_orchestrator_schema(\n self,\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n ) -> Optional[Type[BaseIOSchema]]:\n \"\"\"Create an orchestrator schema for the given tools.\"\"\"\n ...\n def create_resources(self) -> List[Type[BaseResource]]:\n \"\"\"Create resource classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"Fetch resource definitions using the appropriate method.\"\"\"\n ...\n def _create_resource_classes(self, resource_definitions: List[MCPResourceDefinition]) -> List[Type[BaseResource]]:\n \"\"\"Create resource classes from definitions.\"\"\"\n ...\n def create_prompts(self) -> List[Type[BasePrompt]]:\n \"\"\"Create prompt classes from the configured endpoint or session.\"\"\"\n ...\n def _fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"Fetch prompt definitions using the appropriate method.\"\"\"\n ...\n def _create_prompt_classes(self, prompt_definitions: List[MCPPromptDefinition]) -> List[Type[BasePrompt]]:\n \"\"\"Create prompt classes from definitions.\"\"\"\n ...\n\ndef fetch_mcp_tools(\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n *,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n) -> List[Type[BaseTool]]:\n \"\"\"Connects to an MCP server via SSE, HTTP Stream or STDIO, discovers tool definitions, and dynamically generates\"\"\"\n ...\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPTransportType(Enum):\n \"\"\"Enum for MCP transport types.\"\"\"\n\n SSE = \"sse\"\n HTTP_STREAM = \"http_stream\"\n STDIO = \"stdio\"\n\nclass MCPToolDefinition(NamedTuple):\n \"\"\"Definition of an MCP tool.\"\"\"\n\n name: str\n description: Optional[str]\n input_schema: Dict[str, Any]\n output_schema: Optional[Dict[str, Any]] = None", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47651, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_factory.py\nclass MCPFactory:\n \"\"\"Factory for creating MCP tool classes.\"\"\"\n\n def __init__(\n self,\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n ):\n \"\"\"\n Initialize the factory.\n\n Args:\n mcp_endpoint: URL of the MCP server (for SSE/HTTP stream) or the full command to run the server (for STDIO)\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO)\n client_session: Optional pre-initialized ClientSession for reuse\n event_loop: Optional event loop for running asynchronous operations\n working_directory: Optional working directory to use when running STDIO commands\n \"\"\"\n self.mcp_endpoint = mcp_endpoint\n self.transport_type = transport_type\n self.client_session = client_session\n self.event_loop = event_loop\n self.schema_transformer = SchemaTransformer()\n self.working_directory = working_directory\n\n # Validate configuration\n if client_session is not None and event_loop is None:\n raise ValueError(\"When `client_session` is provided an `event_loop` must also be supplied.\")\n if not mcp_endpoint and client_session is None:\n raise ValueError(\"`mcp_endpoint` must be provided when no `client_session` is supplied.\")\n\n def create_tools(self) -> List[Type[BaseTool]]:\n \"\"\"\n Create tool classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated BaseTool subclasses\n \"\"\"\n tool_definitions = self._fetch_tool_definitions()\n if not tool_definitions:\n return []\n\n return self._create_tool_classes(tool_definitions)\n\n def _fetch_tool_definitions(self) -> List[MCPToolDefinition]:\n \"\"\"\n Fetch tool definitions using the appropriate method.\n\n Returns:\n List of tool definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_tool_definitions_from_session(self.client_session) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_tool_definitions())\n\n def _create_tool_classes(self, tool_definitions: List[MCPToolDefinition]) -> List[Type[BaseTool]]:\n \"\"\"\n Create tool classes from definitions.\n\n Args:\n tool_definitions: List of tool definitions\n\n Returns:\n List of dynamically generated BaseTool subclasses\n \"\"\"\n generated_tools = []\n\n for definition in tool_definitions:\n try:\n tool_name = definition.name\n tool_description = definition.description or f\"Dynamically generated tool for MCP tool: {tool_name}\"\n input_schema_dict = definition.input_schema\n\n # Create input schema\n InputSchema = self.schema_transformer.create_model_from_schema(\n input_schema_dict,\n f\"{tool_name}InputSchema\",\n tool_name,\n f\"Input schema for {tool_name}\",\n attribute_type=MCPAttributeType.TOOL,\n )\n\n # Create output schema - use MCP-provided schema if available, otherwise fallback to generic.\n # When a typed output schema is used, _has_typed_output_schema is set on the tool class\n # to enable structured content extraction at runtime (see result processing below).\n output_schema_dict: Optional[Dict[str, Any]] = definition.output_schema\n has_typed_output_schema = False\n if output_schema_dict:\n # Use the schema transformer to create a proper typed output schema\n OutputSchema = self.schema_transformer.create_model_from_schema(\n output_schema_dict,\n f\"{tool_name}OutputSchema\",\n tool_name,\n f\"Output schema for {tool_name}\",\n attribute_type=MCPAttributeType.TOOL,\n is_output_schema=True,\n )\n has_typed_output_schema = True\n else:\n # Fallback to generic output schema\n OutputSchema = type(\n f\"{tool_name}OutputSchema\", (MCPToolOutputSchema,), {\"__doc__\": f\"Output schema for {tool_name}\"}\n )\n\n # Async implementation\n async def run_tool_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_tool_name = self.mcp_tool_name\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n # Get arguments, excluding tool_name\n arguments = params.model_dump(exclude={\"tool_name\"}, exclude_none=True)\n\n async def _connect_and_call():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(f\"Executing tool '{bound_tool_name}' via STDIO: command='{command}', args={args}\")\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(f\"Executing tool '{bound_tool_name}' via HTTP Stream: endpoint={http_endpoint}\")\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Executing tool '{bound_tool_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n tool_result = await session.call_tool(name=bound_tool_name, arguments=call_args)\n return tool_result\n finally:\n await stack.aclose()\n\n async def _call_with_persistent_session():\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n return await persistent_session.call_tool(name=bound_tool_name, arguments=call_args)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n tool_result = await _call_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n tool_result = await _connect_and_call()\n\n # Process the result based on whether we have a typed output schema.\n # Extraction precedence for typed schemas:\n # 1. structuredContent attribute (MCP spec primary path)\n # 2. content[0].text parsed as JSON (some servers return JSON as text)\n # 3. content[0].data dict (structured data in content item)\n # 4. Dict with structuredContent/content keys\n # 5. Direct dict usage as fallback\n has_typed_schema = getattr(self, \"_has_typed_output_schema\", False)\n BoundOutputSchema = self.output_schema\n\n if has_typed_schema:\n # For typed output schemas, try to extract structured content\n # MCP tools with output schemas return structured data\n if isinstance(tool_result, BaseModel) and hasattr(tool_result, \"structuredContent\"):\n # Use structured content if available (MCP spec)\n structured_data = tool_result.structuredContent\n if isinstance(structured_data, dict):\n return BoundOutputSchema(**structured_data)\n elif hasattr(structured_data, \"model_dump\"):\n return BoundOutputSchema(**structured_data.model_dump())\n else:\n # Unexpected type for structuredContent\n logger.error(\n f\"Unexpected structuredContent type for tool '{bound_tool_name}': \"\n f\"got {type(structured_data).__name__}, expected dict or BaseModel. \"\n f\"Content: {structured_data!r}\"\n )\n raise TypeError(\n f\"MCP tool '{bound_tool_name}' returned structuredContent with unexpected type \"\n f\"{type(structured_data).__name__}. Expected dict or BaseModel.\"\n )\n elif isinstance(tool_result, BaseModel) and hasattr(tool_result, \"content\"):\n # Try to parse content as structured data\n content = tool_result.content\n # Ensure content is a list/tuple before indexing\n if content and isinstance(content, (list, tuple)) and len(content) > 0:\n first_content = content[0]\n # Check for text content that might be JSON\n if hasattr(first_content, \"text\"):\n try:\n parsed = json.loads(first_content.text)\n if isinstance(parsed, dict):\n return BoundOutputSchema(**parsed)\n else:\n logger.debug(\n f\"Tool '{bound_tool_name}' content parsed as JSON but was \"\n f\"{type(parsed).__name__}, not dict. Trying other extraction methods.\"\n )\n except json.JSONDecodeError as e:\n logger.debug(\n f\"Tool '{bound_tool_name}' content is not valid JSON: {e}. \"\n f\"Content preview: {first_content.text[:200]!r}...\"\n if len(first_content.text) > 200\n else f\"Content: {first_content.text!r}\"\n )\n except TypeError as e:\n logger.warning(\n f\"Tool '{bound_tool_name}' content.text has unexpected type \"\n f\"{type(first_content.text).__name__}: {e}\"\n )\n # Check for structured content in the content item\n if hasattr(first_content, \"data\") and isinstance(first_content.data, dict):\n return BoundOutputSchema(**first_content.data)\n elif isinstance(tool_result, dict):\n if \"structuredContent\" in tool_result:\n return BoundOutputSchema(**tool_result[\"structuredContent\"])\n elif \"content\" in tool_result:\n content = tool_result[\"content\"]\n if isinstance(content, dict):\n return BoundOutputSchema(**content)\n # Fallback: try to use tool_result directly if it's a dict\n if isinstance(tool_result, dict):\n return BoundOutputSchema(**tool_result)\n # If we have a typed schema but couldn't extract structured content,\n # this is an error - we cannot fall through to generic handling\n # because the typed schema doesn't have a 'result' field.\n logger.error(\n f\"Could not parse structured output for tool '{bound_tool_name}'. \"\n f\"Expected typed output but got: type={type(tool_result).__name__}, \"\n f\"value={tool_result!r}\"\n )\n raise ValueError(\n f\"MCP tool '{bound_tool_name}' has outputSchema but returned unparseable result. \"\n f\"Received type: {type(tool_result).__name__}. \"\n f\"Check MCP server implementation.\"\n )\n\n # Generic output schema handling (original behavior) - only for tools without typed schemas\n if isinstance(tool_result, BaseModel) and hasattr(tool_result, \"content\"):\n actual_result_content = tool_result.content\n elif isinstance(tool_result, dict) and \"content\" in tool_result:\n actual_result_content = tool_result[\"content\"]\n else:\n actual_result_content = tool_result\n\n return BoundOutputSchema(result=actual_result_content)\n\n except Exception as e:\n logger.error(f\"Error executing MCP tool '{bound_tool_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to execute MCP tool '{bound_tool_name}': {e}\") from e\n\n # Create sync wrapper\n def run_tool_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.arun(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to execute MCP tool '{tool_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.arun(params))\n\n # Create the tool class using types.new_class() instead of type()\n attrs = {\n \"arun\": run_tool_async,\n \"run\": run_tool_sync,\n \"__doc__\": tool_description,\n \"mcp_tool_name\": tool_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n \"_has_typed_output_schema\": has_typed_output_schema,\n }\n\n # Create the class using new_class() for proper generic type support\n tool_class = types.new_class(\n tool_name, (BaseTool[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n # since they might not be properly inherited with types.new_class\n setattr(tool_class, \"input_schema\", InputSchema)\n setattr(tool_class, \"output_schema\", OutputSchema)\n\n generated_tools.append(tool_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for tool '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_tools\n\n def create_orchestrator_schema(\n self,\n tools: Optional[List[Type[BaseTool]]] = None,\n resources: Optional[List[Type[BaseResource]]] = None,\n prompts: Optional[List[Type[BasePrompt]]] = None,\n ) -> Optional[Type[BaseIOSchema]]:\n \"\"\"\n Create an orchestrator schema for the given tools.\n\n Args:\n tools: List of tool classes\n resources: List of resource classes\n prompts: List of prompt classes\n\n Returns:\n Orchestrator schema or None if no tools provided\n \"\"\"\n if tools is None and resources is None and prompts is None:\n logger.warning(\"No tools/resources/prompts provided to create orchestrator schema\")\n return None\n if tools is None:\n tools = []\n if resources is None:\n resources = []\n if prompts is None:\n prompts = []\n\n tool_schemas = [ToolClass.input_schema for ToolClass in tools]\n resource_schemas = [ResourceClass.input_schema for ResourceClass in resources]\n prompt_schemas = [PromptClass.input_schema for PromptClass in prompts]\n\n # Build runtime Union types for each attribute group when present\n field_defs = {}\n\n if tool_schemas:\n ToolUnion = Union[tuple(tool_schemas)]\n field_defs[\"tool_parameters\"] = (\n ToolUnion,\n Field(\n ...,\n description=\"The parameters for the selected tool, matching its specific schema (which includes the 'tool_name').\",\n ),\n )\n\n if resource_schemas:\n ResourceUnion = Union[tuple(resource_schemas)]\n field_defs[\"resource_parameters\"] = (\n ResourceUnion,\n Field(\n ...,\n description=\"The parameters for the selected resource, matching its specific schema (which includes the 'resource_name').\",\n ),\n )\n\n if prompt_schemas:\n PromptUnion = Union[tuple(prompt_schemas)]\n field_defs[\"prompt_parameters\"] = (\n PromptUnion,\n Field(\n ...,\n description=\"The parameters for the selected prompt, matching its specific schema (which includes the 'prompt_name').\",\n ),\n )\n\n if not field_defs:\n logger.warning(\"No schemas available to create orchestrator union\")\n return None\n\n # Dynamically create the output schema with the appropriate fields\n orchestrator_schema = create_model(\n \"MCPOrchestratorOutputSchema\",\n __doc__=\"Output schema for the MCP Orchestrator Agent. Contains the parameters for the selected tool/resource/prompt.\",\n __base__=BaseIOSchema,\n **field_defs,\n )\n\n return orchestrator_schema\n\n def create_resources(self) -> List[Type[BaseResource]]:\n \"\"\"\n Create resource classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated resource classes\n \"\"\"\n resource_definitions = self._fetch_resource_definitions()\n if not resource_definitions:\n return []\n\n return self._create_resource_classes(resource_definitions)\n\n def _fetch_resource_definitions(self) -> List[MCPResourceDefinition]:\n \"\"\"\n Fetch resource definitions using the appropriate method.\n\n Returns:\n List of resource definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_resource_definitions_from_session(\n self.client_session\n ) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_resource_definitions())\n\n def _create_resource_classes(self, resource_definitions: List[MCPResourceDefinition]) -> List[Type[BaseResource]]:\n \"\"\"\n Create resource classes from definitions.\n\n Args:\n resource_definitions: List of resource definitions\n\n Returns:\n List of dynamically generated resource classes\n \"\"\"\n generated_resources = []\n\n for definition in resource_definitions:\n try:\n resource_name = definition.name\n resource_description = (\n definition.description or f\"Dynamically generated resource for MCP resource: {resource_name}\"\n )\n uri = definition.uri\n mime_type = definition.mime_type\n\n InputSchema = self.schema_transformer.create_model_from_schema(\n definition.input_schema,\n f\"{resource_name}InputSchema\",\n resource_name,\n f\"Input schema for {resource_name}\",\n attribute_type=MCPAttributeType.RESOURCE,\n )\n\n # Create output schema\n OutputSchema = type(\n f\"{resource_name}OutputSchema\",\n (MCPResourceOutputSchema,),\n {\"__doc__\": f\"Output schema for {resource_name}\"},\n )\n\n # Async implementation\n async def read_resource_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_uri = self.uri\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n arguments = params.model_dump(exclude={\"resource_name\"}, exclude_none=True)\n\n async def _connect_and_read():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(\n f\"Reading resource '{self.mcp_resource_name}' via STDIO: command='{command}', args={args}\"\n )\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(\n f\"Reading resource '{self.mcp_resource_name}' via HTTP Stream: endpoint={http_endpoint}\"\n )\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Reading resource '{self.mcp_resource_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Substitute URI placeholders with provided parameters when available.\n call_args = arguments if isinstance(arguments, dict) else {}\n # If params contain keys, format the URI template.\n try:\n concrete_uri = bound_uri.format(**call_args) if call_args else bound_uri\n except Exception:\n concrete_uri = bound_uri\n resource_result: mcp.types.ReadResourceResult = await session.read_resource(uri=concrete_uri)\n return resource_result\n finally:\n await stack.aclose()\n\n async def _read_with_persistent_session():\n call_args = arguments if isinstance(arguments, dict) else {}\n\n try:\n concrete_uri_p = bound_uri.format(**call_args) if call_args else bound_uri\n except Exception:\n concrete_uri_p = bound_uri\n\n return await persistent_session.read_resource(uri=concrete_uri_p)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n resource_result = await _read_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n resource_result = await _connect_and_read()\n\n # Process the result\n if isinstance(resource_result, BaseModel) and hasattr(resource_result, \"contents\"):\n actual_content = resource_result.contents\n # MCP stores mimeType in each content item, not on the result itself\n if actual_content and len(actual_content) > 0:\n # Get mimeType from the first content item\n first_content = actual_content[0]\n actual_mime = getattr(first_content, \"mimeType\", mime_type)\n else:\n actual_mime = mime_type\n elif isinstance(resource_result, dict) and \"contents\" in resource_result:\n actual_content = resource_result[\"contents\"]\n actual_mime = resource_result.get(\"mime_type\", mime_type)\n else:\n actual_content = resource_result\n actual_mime = mime_type\n\n return OutputSchema(content=actual_content, mime_type=actual_mime)\n\n except Exception as e:\n logger.error(f\"Error reading MCP resource '{self.mcp_resource_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to read MCP resource '{self.mcp_resource_name}': {e}\") from e\n\n # Create sync wrapper\n def read_resource_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.aread(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to read MCP resource '{resource_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.aread(params))\n\n # Create the resource class using types.new_class() instead of type()\n attrs = {\n \"aread\": read_resource_async,\n \"read\": read_resource_sync,\n \"__doc__\": resource_description,\n \"mcp_resource_name\": resource_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n \"uri\": uri,\n }\n\n # Create the class using new_class() for proper generic type support\n resource_class = types.new_class(\n resource_name, (BaseResource[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n setattr(resource_class, \"input_schema\", InputSchema)\n setattr(resource_class, \"output_schema\", OutputSchema)\n\n generated_resources.append(resource_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for resource '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_resources\n\n def create_prompts(self) -> List[Type[BasePrompt]]:\n \"\"\"\n Create prompt classes from the configured endpoint or session.\n\n Returns:\n List of dynamically generated prompt classes\n \"\"\"\n prompt_definitions = self._fetch_prompt_definitions()\n if not prompt_definitions:\n return []\n\n return self._create_prompt_classes(prompt_definitions)\n\n def _fetch_prompt_definitions(self) -> List[MCPPromptDefinition]:\n \"\"\"\n Fetch prompt definitions using the appropriate method.\n\n Returns:\n List of prompt definitions\n \"\"\"\n if self.client_session is not None:\n # Use existing session\n async def _gather_defs():\n return await MCPDefinitionService.fetch_prompt_definitions_from_session(\n self.client_session\n ) # pragma: no cover\n\n return cast(asyncio.AbstractEventLoop, self.event_loop).run_until_complete(_gather_defs()) # pragma: no cover\n else:\n # Create new connection\n service = MCPDefinitionService(\n self.mcp_endpoint,\n self.transport_type,\n self.working_directory,\n )\n return asyncio.run(service.fetch_prompt_definitions())\n\n def _create_prompt_classes(self, prompt_definitions: List[MCPPromptDefinition]) -> List[Type[BasePrompt]]:\n \"\"\"\n Create prompt classes from definitions.\n\n Args:\n prompt_definitions: List of prompt definitions\n\n Returns:\n List of dynamically generated prompt classes\n \"\"\"\n generated_prompts = []\n\n for definition in prompt_definitions:\n try:\n prompt_name = definition.name\n prompt_description = definition.description or f\"Dynamically generated prompt for MCP prompt: {prompt_name}\"\n\n InputSchema = self.schema_transformer.create_model_from_schema(\n definition.input_schema,\n f\"{prompt_name}InputSchema\",\n prompt_name,\n f\"Input schema for {prompt_name}\",\n attribute_type=MCPAttributeType.PROMPT,\n )\n\n # Create output schema\n OutputSchema = type(\n f\"{prompt_name}OutputSchema\", (MCPPromptOutputSchema,), {\"__doc__\": f\"Output schema for {prompt_name}\"}\n )\n\n # Async implementation\n async def generate_prompt_async(self, params: InputSchema) -> OutputSchema: # type: ignore\n bound_prompt_name = self.mcp_prompt_name\n bound_mcp_endpoint = self.mcp_endpoint # May be None when using external session\n bound_transport_type = self.transport_type\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n bound_working_directory = getattr(self, \"working_directory\", None)\n\n # Get arguments\n arguments = params.model_dump(exclude={\"prompt_name\"}, exclude_none=True)\n\n async def _connect_and_generate():\n stack = AsyncExitStack()\n try:\n if bound_transport_type == MCPTransportType.STDIO:\n # Split the command string into the command and its arguments\n command_parts = shlex.split(bound_mcp_endpoint)\n if not command_parts:\n raise ValueError(\"STDIO command string cannot be empty.\")\n command = command_parts[0]\n args = command_parts[1:]\n logger.debug(\n f\"Getting prompt '{bound_prompt_name}' via STDIO: command='{command}', args={args}\"\n )\n server_params = StdioServerParameters(\n command=command, args=args, env=None, cwd=bound_working_directory\n )\n stdio_transport = await stack.enter_async_context(stdio_client(server_params))\n read_stream, write_stream = stdio_transport\n elif bound_transport_type == MCPTransportType.HTTP_STREAM:\n # HTTP Stream transport - use trailing slash to avoid redirect\n # See: https://github.com/modelcontextprotocol/python-sdk/issues/732\n http_endpoint = f\"{bound_mcp_endpoint}/mcp/\"\n logger.debug(f\"Getting prompt '{bound_prompt_name}' via HTTP Stream: endpoint={http_endpoint}\")\n http_transport = await stack.enter_async_context(streamablehttp_client(http_endpoint))\n read_stream, write_stream, _ = http_transport\n elif bound_transport_type == MCPTransportType.SSE:\n # SSE transport (deprecated)\n sse_endpoint = f\"{bound_mcp_endpoint}/sse\"\n logger.debug(f\"Getting prompt '{bound_prompt_name}' via SSE: endpoint={sse_endpoint}\")\n sse_transport = await stack.enter_async_context(sse_client(sse_endpoint))\n read_stream, write_stream = sse_transport\n else:\n available_types = [t.value for t in MCPTransportType]\n raise ValueError(\n f\"Unknown transport type: {bound_transport_type}. Available transport types: {available_types}\"\n )\n\n session = await stack.enter_async_context(ClientSession(read_stream, write_stream))\n await session.initialize()\n\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n prompt_result = await session.get_prompt(name=bound_prompt_name, arguments=call_args)\n return prompt_result\n finally:\n await stack.aclose()\n\n async def _get_with_persistent_session():\n # Ensure arguments is a dict, even if empty\n call_args = arguments if isinstance(arguments, dict) else {}\n return await persistent_session.get_prompt(name=bound_prompt_name, arguments=call_args)\n\n try:\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n prompt_result = await _get_with_persistent_session()\n else:\n # Legacy behaviour – open a fresh connection per invocation.\n prompt_result = await _connect_and_generate()\n\n # Process the result\n messages = None\n if isinstance(prompt_result, BaseModel) and hasattr(prompt_result, \"messages\"):\n messages = prompt_result.messages\n elif isinstance(prompt_result, dict) and \"messages\" in prompt_result:\n messages = prompt_result[\"messages\"]\n else:\n raise Exception(\"Prompt response has no messages.\")\n\n texts = []\n for message in messages:\n if isinstance(message, BaseModel) and hasattr(message, \"content\"):\n content = message.content # type: ignore\n elif isinstance(message, dict) and \"content\" in message:\n content = message[\"content\"]\n else:\n content = message\n\n if isinstance(content, str):\n texts.append(content)\n elif isinstance(content, dict):\n texts.append(content.get(\"text\"))\n elif getattr(content, \"text\", None):\n texts.append(content.text) # type: ignore\n else:\n texts.append(str(content))\n final_content = \"\\n\\n\".join(texts)\n\n return OutputSchema(content=final_content)\n\n except Exception as e:\n logger.error(f\"Error getting MCP prompt '{bound_prompt_name}': {e}\", exc_info=True)\n raise RuntimeError(f\"Failed to get MCP prompt '{bound_prompt_name}': {e}\") from e\n\n # Create sync wrapper\n def generate_prompt_sync(self, params: InputSchema) -> OutputSchema: # type: ignore\n persistent_session: Optional[ClientSession] = getattr(self, \"_client_session\", None)\n loop: Optional[asyncio.AbstractEventLoop] = getattr(self, \"_event_loop\", None)\n\n if persistent_session is not None:\n # Use the always‑on session/loop supplied at construction time.\n try:\n return cast(asyncio.AbstractEventLoop, loop).run_until_complete(self.agenerate(params))\n except AttributeError as e:\n raise RuntimeError(f\"Failed to get MCP prompt '{prompt_name}': {e}\") from e\n else:\n # Legacy behaviour – run in new event loop.\n return asyncio.run(self.agenerate(params))\n\n # Create the prompt class using types.new_class() instead of type()\n attrs = {\n \"agenerate\": generate_prompt_async,\n \"generate\": generate_prompt_sync,\n \"__doc__\": prompt_description,\n \"mcp_prompt_name\": prompt_name,\n \"mcp_endpoint\": self.mcp_endpoint,\n \"transport_type\": self.transport_type,\n \"_client_session\": self.client_session,\n \"_event_loop\": self.event_loop,\n \"working_directory\": self.working_directory,\n }\n\n # Create the class using new_class() for proper generic type support\n prompt_class = types.new_class(\n prompt_name, (BasePrompt[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)\n )\n\n # Add the input_schema and output_schema class attributes explicitly\n setattr(prompt_class, \"input_schema\", InputSchema)\n setattr(prompt_class, \"output_schema\", OutputSchema)\n\n generated_prompts.append(prompt_class)\n\n except Exception as e:\n logger.error(f\"Error generating class for prompt '{definition.name}': {e}\", exc_info=True)\n continue\n\n return generated_prompts\n\ndef fetch_mcp_tools(\n mcp_endpoint: Optional[str] = None,\n transport_type: MCPTransportType = MCPTransportType.HTTP_STREAM,\n *,\n client_session: Optional[ClientSession] = None,\n event_loop: Optional[asyncio.AbstractEventLoop] = None,\n working_directory: Optional[str] = None,\n) -> List[Type[BaseTool]]:\n \"\"\"\n Connects to an MCP server via SSE, HTTP Stream or STDIO, discovers tool definitions, and dynamically generates\n synchronous Atomic Agents compatible BaseTool subclasses for each tool.\n Each generated tool will establish its own connection when its `run` method is called.\n\n Args:\n mcp_endpoint: URL of the MCP server or command for STDIO.\n transport_type: Type of transport to use (SSE, HTTP_STREAM, or STDIO).\n client_session: Optional pre-initialized ClientSession for reuse.\n event_loop: Optional event loop for running asynchronous operations.\n working_directory: Optional working directory for STDIO.\n \"\"\"\n factory = MCPFactory(mcp_endpoint, transport_type, client_session, event_loop, working_directory)\n return factory.create_tools()\n\n\n# Source: atomic-agents/atomic_agents/connectors/mcp/mcp_definition_service.py\nclass MCPTransportType(Enum):\n \"\"\"Enum for MCP transport types.\"\"\"\n\n SSE = \"sse\"\n HTTP_STREAM = \"http_stream\"\n STDIO = \"stdio\"\n\nclass MCPToolDefinition(NamedTuple):\n \"\"\"Definition of an MCP tool.\"\"\"\n\n name: str\n description: Optional[str]\n input_schema: Dict[str, Any]\n output_schema: Optional[Dict[str, Any]] = None", "n_chars_compressed": 4196, "compression_ratio": 0.08805691381083293}, "atomic-agents/tests/context/test_chat_history.py::145": {"resolved_imports": ["atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_get_message_count", "extracted_code": "", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 0}, "atomic-agents/tests/base/test_base_tool.py::76": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": [], "enclosing_function": "test_base_tool_input_schema", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::28": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_integer_type_with_default", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::33": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_boolean_type", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::21": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["Optional", "SchemaTransformer"], "enclosing_function": "test_number_type_optional", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::184": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema"], "enclosing_function": "test_searxng_search_tool_sync_run_method", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_format_tool_message.py::36": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_without_tool_id", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-agents/tests/utils/test_token_counter.py::88": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCounter", "patch"], "enclosing_function": "test_count_messages", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 5801, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_chars_compressed": 5801, "compression_ratio": 1.0}, "atomic-forge/tools/searxng_search/tests/test_searxng_search.py::61": {"resolved_imports": [], "used_names": ["AsyncMock", "SearXNGSearchTool", "SearXNGSearchToolConfig", "SearXNGSearchToolInputSchema", "SearXNGSearchToolOutputSchema", "pytest"], "enclosing_function": "test_searxng_search_tool_with_category", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/utils/test_token_counter.py::113": {"resolved_imports": ["atomic-agents/atomic_agents/utils/token_counter.py"], "used_names": ["TokenCounter", "patch"], "enclosing_function": "test_count_text", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 5801, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/token_counter.py\nclass TokenCounter:\n \"\"\"\n Utility class for counting tokens using LiteLLM's provider-agnostic tokenizer.\n\n This class provides methods for counting tokens in messages, text, tools,\n and retrieving model context limits. It uses LiteLLM's token_counter which\n automatically selects the appropriate tokenizer based on the model.\n\n Works with any model supported by LiteLLM including:\n - OpenAI (gpt-4, gpt-3.5-turbo, etc.)\n - Anthropic (claude-3-opus, claude-3-sonnet, etc.)\n - Google (gemini-pro, gemini-1.5-pro, etc.)\n - And 100+ other providers\n\n Example:\n ```python\n counter = TokenCounter()\n\n # Count tokens in messages\n messages = [{\"role\": \"user\", \"content\": \"Hello, world!\"}]\n count = counter.count_messages(\"gpt-4\", messages)\n\n # Count tokens with tools (for TOOLS mode)\n tools = [{\"type\": \"function\", \"function\": {...}}]\n count = counter.count_messages(\"gpt-4\", messages, tools=tools)\n\n # Get max tokens for a model\n max_tokens = counter.get_max_tokens(\"gpt-4\")\n ```\n \"\"\"\n\n def count_messages(\n self,\n model: str,\n messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> int:\n \"\"\"\n Count the number of tokens in a list of messages and optional tools.\n\n Args:\n model: The model identifier (e.g., \"gpt-4\", \"anthropic/claude-3-opus\").\n messages: List of message dictionaries with 'role' and 'content' keys.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n The number of tokens in the messages (and tools if provided).\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n if not model:\n raise ValueError(\"model is required for token counting\")\n\n try:\n from litellm import token_counter\n\n if tools:\n return token_counter(model=model, messages=messages, tools=tools)\n return token_counter(model=model, messages=messages)\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n except Exception as e:\n raise TokenCountError(f\"Failed to count tokens for model '{model}': {e}\") from e\n\n def count_text(self, model: str, text: str) -> int:\n \"\"\"\n Count the number of tokens in a text string.\n\n Args:\n model: The model identifier.\n text: The text to tokenize.\n\n Returns:\n The number of tokens in the text.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n messages = [{\"role\": \"user\", \"content\": text}]\n return self.count_messages(model, messages)\n\n def get_max_tokens(self, model: str) -> Optional[int]:\n \"\"\"\n Get the maximum context window size for a model.\n\n Args:\n model: The model identifier.\n\n Returns:\n The maximum number of tokens, or None if unknown.\n\n Raises:\n TypeError: If model is None or not a string.\n ImportError: If litellm is not installed.\n \"\"\"\n if not isinstance(model, str):\n raise TypeError(f\"model must be a string, got {type(model).__name__}\")\n\n try:\n from litellm import get_max_tokens\n except ImportError as e:\n raise ImportError(\"litellm is required for token counting. \" \"Install it with: pip install litellm\") from e\n\n try:\n return get_max_tokens(model)\n except Exception as e:\n logger.warning(f\"Could not determine max tokens for model '{model}': {e}\")\n return None\n\n def count_context(\n self,\n model: str,\n system_messages: List[Dict[str, Any]],\n history_messages: List[Dict[str, Any]],\n tools: Optional[List[Dict[str, Any]]] = None,\n ) -> TokenCountResult:\n \"\"\"\n Count tokens with breakdown by system prompt, history, and tools.\n\n Args:\n model: The model identifier.\n system_messages: System prompt messages (may be empty).\n history_messages: Conversation history messages.\n tools: Optional list of tool definitions (for TOOLS mode).\n\n Returns:\n TokenCountResult with breakdown and utilization metrics.\n\n Raises:\n TokenCountError: If token counting fails.\n \"\"\"\n system_tokens = self.count_messages(model, system_messages) if system_messages else 0\n history_tokens = self.count_messages(model, history_messages) if history_messages else 0\n\n # Count tool tokens separately if provided\n tools_tokens = 0\n if tools:\n # To count just the tools overhead, we count empty messages with tools\n # and subtract the base overhead\n empty_with_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}], tools=tools)\n empty_without_tools = self.count_messages(model, [{\"role\": \"user\", \"content\": \"\"}])\n tools_tokens = empty_with_tools - empty_without_tools\n\n total_tokens = system_tokens + history_tokens + tools_tokens\n\n max_tokens = self.get_max_tokens(model)\n # Prevent division by zero\n utilization = (total_tokens / max_tokens) if max_tokens and max_tokens > 0 else None\n\n return TokenCountResult(\n total=total_tokens,\n system_prompt=system_tokens,\n history=history_tokens,\n tools=tools_tokens,\n model=model,\n max_tokens=max_tokens,\n utilization=utilization,\n )", "n_chars_compressed": 5801, "compression_ratio": 1.0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::92": {"resolved_imports": [], "used_names": ["Mock", "patch"], "enclosing_function": "test_fetch_webpage_content_too_large", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/tavily_search/tests/test_tavily_seach.py::150": {"resolved_imports": [], "used_names": ["AsyncMock", "TavilySearchTool", "TavilySearchToolConfig", "TavilySearchToolInputSchema", "pytest"], "enclosing_function": "test_tavily_search_tool_with_max_results", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::61": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["Any", "SchemaTransformer"], "enclosing_function": "test_unknown_type", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-agents/tests/context/test_system_prompt_generator.py::64": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_generate_prompt_without_context_providers", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-forge/tools/webpage_scraper/tests/test_webpage_scraper.py::308": {"resolved_imports": [], "used_names": ["WebpageScraperToolConfig"], "enclosing_function": "test_tool_config", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-forge/tools/bocha_search/tests/test_bocha_search.py::222": {"resolved_imports": [], "used_names": ["BoChaSearchTool", "BoChaSearchToolConfig", "BoChaSearchToolInputSchema", "asyncio", "os", "pytest"], "enclosing_function": "test_bocha_search_tool_config_params_real_case_cn", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 0, "n_chars_extracted": 0}, "atomic-agents/tests/context/test_chat_history.py::212": {"resolved_imports": ["atomic-agents/atomic_agents/context/chat_history.py", "atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["ChatHistory"], "enclosing_function": "test_dump_and_load_comprehensive", "extracted_code": "# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\n \"\"\"\n Manages the chat history for an AI agent.\n\n Attributes:\n history (List[Message]): A list of messages representing the chat history.\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n current_turn_id (Optional[str]): The ID of the current turn.\n \"\"\"\n\n def __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n\n def initialize_turn(self) -> None:\n \"\"\"\n Initializes a new turn by generating a random turn ID.\n \"\"\"\n self.current_turn_id = str(uuid.uuid4())\n\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"\n Adds a message to the chat history and manages overflow.\n\n Args:\n role (str): The role of the message sender.\n content (BaseIOSchema): The content of the message.\n \"\"\"\n if self.current_turn_id is None:\n self.initialize_turn()\n\n message = Message(\n role=role,\n content=content,\n turn_id=self.current_turn_id,\n )\n self.history.append(message)\n self._manage_overflow()\n\n def _manage_overflow(self) -> None:\n \"\"\"\n Manages the chat history overflow based on max_messages constraint.\n \"\"\"\n if self.max_messages is not None:\n while len(self.history) > self.max_messages:\n self.history.pop(0)\n\n def get_history(self) -> List[Dict]:\n \"\"\"\n Retrieves the chat history, handling both regular and multimodal content.\n\n Returns:\n List[Dict]: The list of messages in the chat history as dictionaries.\n Each dictionary has 'role' and 'content' keys, where 'content' contains\n either a single JSON string or a mixed array of JSON and multimodal objects.\n\n Note:\n This method supports multimodal content at any nesting depth by\n recursively extracting multimodal objects and using Pydantic's\n model_dump_json(exclude=...) for proper serialization of remaining fields.\n \"\"\"\n history = []\n for message in self.history:\n input_content = message.content\n multimodal_objects, exclude_spec = self._extract_multimodal_info(input_content)\n\n if multimodal_objects:\n processed_content = []\n content_json = input_content.model_dump_json(exclude=exclude_spec)\n if content_json and content_json != \"{}\":\n processed_content.append(content_json)\n processed_content.extend(multimodal_objects)\n history.append({\"role\": message.role, \"content\": processed_content})\n else:\n content_json = input_content.model_dump_json()\n history.append({\"role\": message.role, \"content\": content_json})\n\n return history\n\n @staticmethod\n def _extract_multimodal_info(obj):\n \"\"\"\n Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\n\n Walks the object tree to find all Instructor multimodal types (Image, Audio, PDF)\n at any nesting depth, collecting them into a flat list and building an exclude\n specification that can be passed to model_dump_json(exclude=...).\n\n Args:\n obj: The object to inspect (BaseIOSchema, list, dict, or primitive).\n\n Returns:\n tuple: (multimodal_objects, exclude_spec) where:\n - multimodal_objects: flat list of all multimodal objects found\n - exclude_spec: Pydantic exclude dict, True (exclude entirely), or None\n \"\"\"\n if isinstance(obj, INSTRUCTOR_MULTIMODAL_TYPES):\n return [obj], True\n\n if hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n all_objects = []\n exclude = {}\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n field_value = getattr(obj, field_name)\n objects, sub_exclude = ChatHistory._extract_multimodal_info(field_value)\n if objects:\n all_objects.extend(objects)\n exclude[field_name] = sub_exclude\n return all_objects, (exclude if exclude else None)\n\n if isinstance(obj, (list, tuple)):\n all_objects = []\n exclude = {}\n for i, item in enumerate(obj):\n objects, sub_exclude = ChatHistory._extract_multimodal_info(item)\n if objects:\n all_objects.extend(objects)\n exclude[i] = sub_exclude\n if not all_objects:\n return [], None\n # If every item in the list is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n if isinstance(obj, dict):\n all_objects = []\n exclude = {}\n for k, v in obj.items():\n objects, sub_exclude = ChatHistory._extract_multimodal_info(v)\n if objects:\n all_objects.extend(objects)\n exclude[k] = sub_exclude\n if not all_objects:\n return [], None\n # If every value in the dict is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n return [], None\n\n def copy(self) -> \"ChatHistory\":\n \"\"\"\n Creates a copy of the chat history.\n\n Returns:\n ChatHistory: A copy of the chat history.\n \"\"\"\n new_history = ChatHistory(max_messages=self.max_messages)\n new_history.load(self.dump())\n new_history.current_turn_id = self.current_turn_id\n return new_history\n\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"\n Returns the current turn ID.\n\n Returns:\n Optional[str]: The current turn ID, or None if not set.\n \"\"\"\n return self.current_turn_id\n\n def delete_turn_id(self, turn_id: int):\n \"\"\"\n Delete messages from the history by its turn ID.\n\n Args:\n turn_id (int): The turn ID of the message to delete.\n\n Returns:\n str: A success message with the deleted turn ID.\n\n Raises:\n ValueError: If the specified turn ID is not found in the history.\n \"\"\"\n initial_length = len(self.history)\n self.history = [msg for msg in self.history if msg.turn_id != turn_id]\n\n if len(self.history) == initial_length:\n raise ValueError(f\"Turn ID {turn_id} not found in history.\")\n\n # Update current_turn_id if necessary\n if not len(self.history):\n self.current_turn_id = None\n elif turn_id == self.current_turn_id:\n # Always update to the last message's turn_id\n self.current_turn_id = self.history[-1].turn_id\n\n def get_message_count(self) -> int:\n \"\"\"\n Returns the number of messages in the chat history.\n\n Returns:\n int: The number of messages.\n \"\"\"\n return len(self.history)\n\n def dump(self) -> str:\n \"\"\"\n Serializes the entire ChatHistory instance to a JSON string.\n\n Returns:\n str: A JSON string representation of the ChatHistory.\n \"\"\"\n serialized_history = []\n for message in self.history:\n content_class = message.content.__class__\n serialized_message = {\n \"role\": message.role,\n \"content\": {\n \"class_name\": f\"{content_class.__module__}.{content_class.__name__}\",\n \"data\": message.content.model_dump_json(),\n },\n \"turn_id\": message.turn_id,\n }\n serialized_history.append(serialized_message)\n\n history_data = {\n \"history\": serialized_history,\n \"max_messages\": self.max_messages,\n \"current_turn_id\": self.current_turn_id,\n }\n return json.dumps(history_data)\n\n def load(self, serialized_data: str) -> None:\n \"\"\"\n Deserializes a JSON string and loads it into the ChatHistory instance.\n\n Args:\n serialized_data (str): A JSON string representation of the ChatHistory.\n\n Raises:\n ValueError: If the serialized data is invalid or cannot be deserialized.\n \"\"\"\n try:\n history_data = json.loads(serialized_data)\n self.history = []\n self.max_messages = history_data[\"max_messages\"]\n self.current_turn_id = history_data[\"current_turn_id\"]\n\n for message_data in history_data[\"history\"]:\n content_info = message_data[\"content\"]\n content_class = self._get_class_from_string(content_info[\"class_name\"])\n content_instance = content_class.model_validate_json(content_info[\"data\"])\n\n # Process any Image objects to convert string paths back to Path objects\n self._process_multimodal_paths(content_instance)\n\n message = Message(role=message_data[\"role\"], content=content_instance, turn_id=message_data[\"turn_id\"])\n self.history.append(message)\n except (json.JSONDecodeError, KeyError, AttributeError, TypeError) as e:\n raise ValueError(f\"Invalid serialized data: {e}\")\n\n @staticmethod\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"\n Retrieves a class object from its string representation.\n\n Args:\n class_string (str): The fully qualified class name.\n\n Returns:\n Type[BaseIOSchema]: The class object.\n\n Raises:\n AttributeError: If the class cannot be found.\n \"\"\"\n module_name, class_name = class_string.rsplit(\".\", 1)\n module = __import__(module_name, fromlist=[class_name])\n return getattr(module, class_name)\n\n def _process_multimodal_paths(self, obj):\n \"\"\"\n Process multimodal objects to convert string paths to Path objects.\n\n Note: this is necessary only for PDF and Image instructor types. The from_path\n behavior is slightly different for Audio as it keeps the source as a string.\n\n Args:\n obj: The object to process.\n\n \"\"\"\n if isinstance(obj, (Image, PDF)) and isinstance(obj.source, str):\n # Check if the string looks like a file path (not a URL or base64 data)\n if not obj.source.startswith((\"http://\", \"https://\", \"data:\")):\n obj.source = Path(obj.source)\n elif isinstance(obj, list):\n # Process each item in the list\n for item in obj:\n self._process_multimodal_paths(item)\n elif isinstance(obj, dict):\n # Process each value in the dictionary\n for value in obj.values():\n self._process_multimodal_paths(value)\n elif hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n # Process each field of the Pydantic model\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n self._process_multimodal_paths(getattr(obj, field_name))\n elif hasattr(obj, \"__dict__\") and not isinstance(obj, Enum):\n # Process each attribute of the object\n for attr_name, attr_value in obj.__dict__.items():\n if attr_name != \"__pydantic_fields_set__\": # Skip pydantic internal fields\n self._process_multimodal_paths(attr_value)", "n_imports_parsed": 9, "n_files_resolved": 2, "n_chars_extracted": 12409, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/chat_history.py\nclass ChatHistory:\n \"\"\"\n Manages the chat history for an AI agent.\n\n Attributes:\n history (List[Message]): A list of messages representing the chat history.\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n current_turn_id (Optional[str]): The ID of the current turn.\n \"\"\"\n\n def __init__(self, max_messages: Optional[int] = None):\n \"\"\"\n Initializes the ChatHistory with an empty history and optional constraints.\n\n Args:\n max_messages (Optional[int]): Maximum number of messages to keep in history.\n When exceeded, oldest messages are removed first.\n \"\"\"\n self.history: List[Message] = []\n self.max_messages = max_messages\n self.current_turn_id: Optional[str] = None\n\n def initialize_turn(self) -> None:\n \"\"\"\n Initializes a new turn by generating a random turn ID.\n \"\"\"\n self.current_turn_id = str(uuid.uuid4())\n\n def add_message(\n self,\n role: str,\n content: BaseIOSchema,\n ) -> None:\n \"\"\"\n Adds a message to the chat history and manages overflow.\n\n Args:\n role (str): The role of the message sender.\n content (BaseIOSchema): The content of the message.\n \"\"\"\n if self.current_turn_id is None:\n self.initialize_turn()\n\n message = Message(\n role=role,\n content=content,\n turn_id=self.current_turn_id,\n )\n self.history.append(message)\n self._manage_overflow()\n\n def _manage_overflow(self) -> None:\n \"\"\"\n Manages the chat history overflow based on max_messages constraint.\n \"\"\"\n if self.max_messages is not None:\n while len(self.history) > self.max_messages:\n self.history.pop(0)\n\n def get_history(self) -> List[Dict]:\n \"\"\"\n Retrieves the chat history, handling both regular and multimodal content.\n\n Returns:\n List[Dict]: The list of messages in the chat history as dictionaries.\n Each dictionary has 'role' and 'content' keys, where 'content' contains\n either a single JSON string or a mixed array of JSON and multimodal objects.\n\n Note:\n This method supports multimodal content at any nesting depth by\n recursively extracting multimodal objects and using Pydantic's\n model_dump_json(exclude=...) for proper serialization of remaining fields.\n \"\"\"\n history = []\n for message in self.history:\n input_content = message.content\n multimodal_objects, exclude_spec = self._extract_multimodal_info(input_content)\n\n if multimodal_objects:\n processed_content = []\n content_json = input_content.model_dump_json(exclude=exclude_spec)\n if content_json and content_json != \"{}\":\n processed_content.append(content_json)\n processed_content.extend(multimodal_objects)\n history.append({\"role\": message.role, \"content\": processed_content})\n else:\n content_json = input_content.model_dump_json()\n history.append({\"role\": message.role, \"content\": content_json})\n\n return history\n\n @staticmethod\n def _extract_multimodal_info(obj):\n \"\"\"\n Recursively extract multimodal objects and build a Pydantic-compatible exclude spec.\n\n Walks the object tree to find all Instructor multimodal types (Image, Audio, PDF)\n at any nesting depth, collecting them into a flat list and building an exclude\n specification that can be passed to model_dump_json(exclude=...).\n\n Args:\n obj: The object to inspect (BaseIOSchema, list, dict, or primitive).\n\n Returns:\n tuple: (multimodal_objects, exclude_spec) where:\n - multimodal_objects: flat list of all multimodal objects found\n - exclude_spec: Pydantic exclude dict, True (exclude entirely), or None\n \"\"\"\n if isinstance(obj, INSTRUCTOR_MULTIMODAL_TYPES):\n return [obj], True\n\n if hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n all_objects = []\n exclude = {}\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n field_value = getattr(obj, field_name)\n objects, sub_exclude = ChatHistory._extract_multimodal_info(field_value)\n if objects:\n all_objects.extend(objects)\n exclude[field_name] = sub_exclude\n return all_objects, (exclude if exclude else None)\n\n if isinstance(obj, (list, tuple)):\n all_objects = []\n exclude = {}\n for i, item in enumerate(obj):\n objects, sub_exclude = ChatHistory._extract_multimodal_info(item)\n if objects:\n all_objects.extend(objects)\n exclude[i] = sub_exclude\n if not all_objects:\n return [], None\n # If every item in the list is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n if isinstance(obj, dict):\n all_objects = []\n exclude = {}\n for k, v in obj.items():\n objects, sub_exclude = ChatHistory._extract_multimodal_info(v)\n if objects:\n all_objects.extend(objects)\n exclude[k] = sub_exclude\n if not all_objects:\n return [], None\n # If every value in the dict is fully multimodal, exclude the entire field\n if len(exclude) == len(obj) and all(v is True for v in exclude.values()):\n return all_objects, True\n return all_objects, exclude\n\n return [], None\n\n def copy(self) -> \"ChatHistory\":\n \"\"\"\n Creates a copy of the chat history.\n\n Returns:\n ChatHistory: A copy of the chat history.\n \"\"\"\n new_history = ChatHistory(max_messages=self.max_messages)\n new_history.load(self.dump())\n new_history.current_turn_id = self.current_turn_id\n return new_history\n\n def get_current_turn_id(self) -> Optional[str]:\n \"\"\"\n Returns the current turn ID.\n\n Returns:\n Optional[str]: The current turn ID, or None if not set.\n \"\"\"\n return self.current_turn_id\n\n def delete_turn_id(self, turn_id: int):\n \"\"\"\n Delete messages from the history by its turn ID.\n\n Args:\n turn_id (int): The turn ID of the message to delete.\n\n Returns:\n str: A success message with the deleted turn ID.\n\n Raises:\n ValueError: If the specified turn ID is not found in the history.\n \"\"\"\n initial_length = len(self.history)\n self.history = [msg for msg in self.history if msg.turn_id != turn_id]\n\n if len(self.history) == initial_length:\n raise ValueError(f\"Turn ID {turn_id} not found in history.\")\n\n # Update current_turn_id if necessary\n if not len(self.history):\n self.current_turn_id = None\n elif turn_id == self.current_turn_id:\n # Always update to the last message's turn_id\n self.current_turn_id = self.history[-1].turn_id\n\n def get_message_count(self) -> int:\n \"\"\"\n Returns the number of messages in the chat history.\n\n Returns:\n int: The number of messages.\n \"\"\"\n return len(self.history)\n\n def dump(self) -> str:\n \"\"\"\n Serializes the entire ChatHistory instance to a JSON string.\n\n Returns:\n str: A JSON string representation of the ChatHistory.\n \"\"\"\n serialized_history = []\n for message in self.history:\n content_class = message.content.__class__\n serialized_message = {\n \"role\": message.role,\n \"content\": {\n \"class_name\": f\"{content_class.__module__}.{content_class.__name__}\",\n \"data\": message.content.model_dump_json(),\n },\n \"turn_id\": message.turn_id,\n }\n serialized_history.append(serialized_message)\n\n history_data = {\n \"history\": serialized_history,\n \"max_messages\": self.max_messages,\n \"current_turn_id\": self.current_turn_id,\n }\n return json.dumps(history_data)\n\n def load(self, serialized_data: str) -> None:\n \"\"\"\n Deserializes a JSON string and loads it into the ChatHistory instance.\n\n Args:\n serialized_data (str): A JSON string representation of the ChatHistory.\n\n Raises:\n ValueError: If the serialized data is invalid or cannot be deserialized.\n \"\"\"\n try:\n history_data = json.loads(serialized_data)\n self.history = []\n self.max_messages = history_data[\"max_messages\"]\n self.current_turn_id = history_data[\"current_turn_id\"]\n\n for message_data in history_data[\"history\"]:\n content_info = message_data[\"content\"]\n content_class = self._get_class_from_string(content_info[\"class_name\"])\n content_instance = content_class.model_validate_json(content_info[\"data\"])\n\n # Process any Image objects to convert string paths back to Path objects\n self._process_multimodal_paths(content_instance)\n\n message = Message(role=message_data[\"role\"], content=content_instance, turn_id=message_data[\"turn_id\"])\n self.history.append(message)\n except (json.JSONDecodeError, KeyError, AttributeError, TypeError) as e:\n raise ValueError(f\"Invalid serialized data: {e}\")\n\n @staticmethod\n def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:\n \"\"\"\n Retrieves a class object from its string representation.\n\n Args:\n class_string (str): The fully qualified class name.\n\n Returns:\n Type[BaseIOSchema]: The class object.\n\n Raises:\n AttributeError: If the class cannot be found.\n \"\"\"\n module_name, class_name = class_string.rsplit(\".\", 1)\n module = __import__(module_name, fromlist=[class_name])\n return getattr(module, class_name)\n\n def _process_multimodal_paths(self, obj):\n \"\"\"\n Process multimodal objects to convert string paths to Path objects.\n\n Note: this is necessary only for PDF and Image instructor types. The from_path\n behavior is slightly different for Audio as it keeps the source as a string.\n\n Args:\n obj: The object to process.\n\n \"\"\"\n if isinstance(obj, (Image, PDF)) and isinstance(obj.source, str):\n # Check if the string looks like a file path (not a URL or base64 data)\n if not obj.source.startswith((\"http://\", \"https://\", \"data:\")):\n obj.source = Path(obj.source)\n elif isinstance(obj, list):\n # Process each item in the list\n for item in obj:\n self._process_multimodal_paths(item)\n elif isinstance(obj, dict):\n # Process each value in the dictionary\n for value in obj.values():\n self._process_multimodal_paths(value)\n elif hasattr(obj, \"__class__\") and hasattr(obj.__class__, \"model_fields\"):\n # Process each field of the Pydantic model\n for field_name in obj.__class__.model_fields:\n if hasattr(obj, field_name):\n self._process_multimodal_paths(getattr(obj, field_name))\n elif hasattr(obj, \"__dict__\") and not isinstance(obj, Enum):\n # Process each attribute of the object\n for attr_name, attr_value in obj.__dict__.items():\n if attr_name != \"__pydantic_fields_set__\": # Skip pydantic internal fields\n self._process_multimodal_paths(attr_value)", "n_chars_compressed": 12409, "compression_ratio": 1.0}, "atomic-agents/tests/utils/test_format_tool_message.py::75": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_consistent_output", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-agents/tests/connectors/mcp/test_schema_transformer.py::228": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py"], "used_names": ["SchemaTransformer"], "enclosing_function": "test_output_schema_no_tool_name_field", "extracted_code": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7778, "extracted_code_full": "# Source: atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py\nclass SchemaTransformer:\n \"\"\"Class for transforming JSON schemas to Pydantic models.\"\"\"\n\n @staticmethod\n def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:\n \"\"\"Resolve a $ref to a Pydantic model.\"\"\"\n # Extract ref name from path like \"#/$defs/MyObject\" or \"#/definitions/ANode\"\n ref_name = ref_path.split(\"/\")[-1]\n\n if ref_name in model_cache:\n return model_cache[ref_name]\n\n # Look for the referenced schema in $defs or definitions\n defs = root_schema.get(\"$defs\", root_schema.get(\"definitions\", {}))\n if ref_name in defs:\n ref_schema = defs[ref_name]\n # Create model for the referenced schema\n model_name = ref_schema.get(\"title\", ref_name)\n # Avoid infinite recursion by adding placeholder first\n model_cache[ref_name] = Any\n model = SchemaTransformer._create_nested_model(ref_schema, model_name, root_schema, model_cache)\n model_cache[ref_name] = model\n return model\n\n logger.warning(f\"Could not resolve $ref: {ref_path}\")\n return Any\n\n @staticmethod\n def _create_nested_model(\n schema: Dict[str, Any], model_name: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]\n ) -> Type:\n \"\"\"Create a nested Pydantic model from a schema.\"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\", {})\n\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, root_schema, model_cache)\n\n return create_model(model_name, **fields)\n\n @staticmethod\n def json_to_pydantic_field(\n prop_schema: Dict[str, Any],\n required: bool,\n root_schema: Optional[Dict[str, Any]] = None,\n model_cache: Optional[Dict[str, Type]] = None,\n ) -> Tuple[Type, Field]:\n \"\"\"\n Convert a JSON schema property to a Pydantic field.\n\n Args:\n prop_schema: JSON schema for the property\n required: Whether the field is required\n root_schema: Full root schema for resolving $refs\n model_cache: Cache for resolved models\n\n Returns:\n Tuple of (type, Field)\n \"\"\"\n if root_schema is None:\n root_schema = {}\n if model_cache is None:\n model_cache = {}\n\n description = prop_schema.get(\"description\")\n default = prop_schema.get(\"default\")\n python_type: Any = Any\n\n # Handle $ref\n if \"$ref\" in prop_schema:\n python_type = SchemaTransformer._resolve_ref(prop_schema[\"$ref\"], root_schema, model_cache)\n # Handle oneOf/anyOf (unions)\n elif \"oneOf\" in prop_schema or \"anyOf\" in prop_schema:\n union_schemas = prop_schema.get(\"oneOf\", prop_schema.get(\"anyOf\", []))\n if union_schemas:\n union_types = []\n for union_schema in union_schemas:\n if \"$ref\" in union_schema:\n union_types.append(SchemaTransformer._resolve_ref(union_schema[\"$ref\"], root_schema, model_cache))\n else:\n # Recursively resolve the union member\n member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)\n union_types.append(member_type)\n\n if len(union_types) == 1:\n python_type = union_types[0]\n else:\n python_type = Union[tuple(union_types)]\n # Handle regular types\n else:\n json_type = prop_schema.get(\"type\")\n if json_type in JSON_TYPE_MAP:\n python_type = JSON_TYPE_MAP[json_type]\n\n if json_type == \"array\":\n items_schema = prop_schema.get(\"items\", {})\n if \"$ref\" in items_schema:\n item_type = SchemaTransformer._resolve_ref(items_schema[\"$ref\"], root_schema, model_cache)\n elif \"oneOf\" in items_schema or \"anyOf\" in items_schema:\n # Handle arrays of unions\n item_type, _ = SchemaTransformer.json_to_pydantic_field(items_schema, True, root_schema, model_cache)\n elif items_schema.get(\"type\") in JSON_TYPE_MAP:\n item_type = JSON_TYPE_MAP[items_schema[\"type\"]]\n else:\n item_type = Any\n python_type = List[item_type]\n\n elif json_type == \"object\":\n python_type = Dict[str, Any]\n\n field_kwargs = {\"description\": description}\n if required:\n field_kwargs[\"default\"] = ...\n elif default is not None:\n field_kwargs[\"default\"] = default\n else:\n python_type = Optional[python_type]\n field_kwargs[\"default\"] = None\n\n return (python_type, Field(**field_kwargs))\n\n @staticmethod\n def create_model_from_schema(\n schema: Dict[str, Any],\n model_name: str,\n tool_name_literal: str,\n docstring: Optional[str] = None,\n attribute_type: str = MCPAttributeType.TOOL,\n is_output_schema: bool = False,\n ) -> Type[BaseIOSchema]:\n \"\"\"\n Dynamically create a Pydantic model from a JSON schema.\n\n Args:\n schema: JSON schema\n model_name: Name for the model\n tool_name_literal: Tool name to use for the Literal type\n docstring: Optional docstring for the model\n attribute_type: Type of MCP attribute (tool, resource, prompt)\n is_output_schema: If True, skip adding the tool_name/resource_name/prompt_name literal field.\n Output schemas represent tool responses and don't need an identifier field since\n the tool has already been selected and executed. Input schemas need the identifier\n for discriminated unions when selecting among multiple tools in an orchestrator.\n\n Returns:\n Pydantic model class\n \"\"\"\n fields = {}\n required_fields = set(schema.get(\"required\", []))\n properties = schema.get(\"properties\")\n model_cache: Dict[str, Type] = {}\n\n if properties:\n for prop_name, prop_schema in properties.items():\n is_required = prop_name in required_fields\n fields[prop_name] = SchemaTransformer.json_to_pydantic_field(prop_schema, is_required, schema, model_cache)\n elif schema.get(\"type\") == \"object\" and not properties:\n pass\n elif schema:\n logger.warning(\n f\"Schema for {model_name} is not a typical object with properties. Fields might be empty beyond tool_name.\"\n )\n\n # Only add the attribute identifier field for input schemas\n if not is_output_schema:\n tool_name_type = cast(Type[str], Literal[tool_name_literal])\n fields[f\"{attribute_type}_name\"] = (\n tool_name_type,\n Field(..., description=f\"Required identifier for the {tool_name_literal} {attribute_type}.\"),\n )\n\n # Create the model\n model = create_model(\n model_name,\n __base__=BaseIOSchema,\n __doc__=docstring or f\"Dynamically generated Pydantic model for {model_name}\",\n __config__={\"title\": tool_name_literal},\n **fields,\n )\n\n return model", "n_chars_compressed": 7778, "compression_ratio": 1.0}, "atomic-agents/tests/context/test_system_prompt_generator.py::38": {"resolved_imports": ["atomic-agents/atomic_agents/context/system_prompt_generator.py"], "used_names": ["SystemPromptGenerator"], "enclosing_function": "test_system_prompt_generator_custom_initialization", "extracted_code": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1806, "extracted_code_full": "# Source: atomic-agents/atomic_agents/context/system_prompt_generator.py\nclass SystemPromptGenerator:\n def __init__(\n self,\n background: Optional[List[str]] = None,\n steps: Optional[List[str]] = None,\n output_instructions: Optional[List[str]] = None,\n context_providers: Optional[Dict[str, BaseDynamicContextProvider]] = None,\n ):\n self.background = background or [\"This is a conversation with a helpful and friendly AI assistant.\"]\n self.steps = steps or []\n self.output_instructions = output_instructions or []\n self.context_providers = context_providers or {}\n\n self.output_instructions.extend(\n [\n \"Always respond using the proper JSON schema.\",\n \"Always use the available additional information and context to enhance the response.\",\n ]\n )\n\n def generate_prompt(self) -> str:\n sections = [\n (\"IDENTITY and PURPOSE\", self.background),\n (\"INTERNAL ASSISTANT STEPS\", self.steps),\n (\"OUTPUT INSTRUCTIONS\", self.output_instructions),\n ]\n\n prompt_parts = []\n\n for title, content in sections:\n if content:\n prompt_parts.append(f\"# {title}\")\n prompt_parts.extend(f\"- {item}\" for item in content)\n prompt_parts.append(\"\")\n\n if self.context_providers:\n prompt_parts.append(\"# EXTRA INFORMATION AND CONTEXT\")\n for provider in self.context_providers.values():\n info = provider.get_info()\n if info:\n prompt_parts.append(f\"## {provider.title}\")\n prompt_parts.append(info)\n prompt_parts.append(\"\")\n\n return \"\\n\".join(prompt_parts).strip()", "n_chars_compressed": 1806, "compression_ratio": 1.0}, "atomic-agents/tests/base/test_base_tool.py::37": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseToolConfig"], "enclosing_function": "test_base_tool_config_with_values", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 524, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 523, "compression_ratio": 0.9980916030534351}, "atomic-agents/tests/utils/test_format_tool_message.py::37": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py", "atomic-agents/atomic_agents/utils/format_tool_message.py"], "used_names": ["format_tool_message"], "enclosing_function": "test_format_tool_message_without_tool_id", "extracted_code": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 908, "extracted_code_full": "# Source: atomic-agents/atomic_agents/utils/format_tool_message.py\ndef format_tool_message(tool_call: Type[BaseModel], tool_id: Optional[str] = None) -> Dict:\n \"\"\"\n Formats a message for a tool call.\n\n Args:\n tool_call (Type[BaseModel]): The Pydantic model instance representing the tool call.\n tool_id (str, optional): The unique identifier for the tool call. If not provided, a random UUID will be generated.\n\n Returns:\n Dict: A formatted message dictionary for the tool call.\n \"\"\"\n if tool_id is None:\n tool_id = str(uuid.uuid4())\n\n # Get the tool name from the Config.title if available, otherwise use the class name\n return {\n \"id\": tool_id,\n \"type\": \"function\",\n \"function\": {\n \"name\": tool_call.__class__.__name__,\n \"arguments\": json.dumps(tool_call.model_dump(), separators=(\", \", \": \")),\n },\n }", "n_chars_compressed": 908, "compression_ratio": 1.0}, "atomic-agents/tests/base/test_base_tool.py::120": {"resolved_imports": ["atomic-agents/atomic_agents/base/__init__.py"], "used_names": ["BaseIOSchema", "BaseTool"], "enclosing_function": "test_base_tool_schema_resolution", "extracted_code": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1181, "extracted_code_full": "# Source: atomic-agents/atomic_agents/base/__init__.py\n\"\"\"Base classes for Atomic Agents.\"\"\"\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n\n\nfrom .base_io_schema import BaseIOSchema\nfrom .base_tool import BaseTool, BaseToolConfig\nfrom .base_resource import BaseResource, BaseResourceConfig\nfrom .base_prompt import BasePrompt, BasePromptConfig\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n__all__ = [\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]\n\n \"BaseIOSchema\",\n \"BaseTool\",\n \"BaseToolConfig\",\n \"BaseResource\",\n \"BaseResourceConfig\",\n \"BasePrompt\",\n \"BasePromptConfig\",\n]", "n_chars_compressed": 1181, "compression_ratio": 1.0}}}