Building AI agents, atomically
black formatting
KennyVaneetvelde5f24da26afd6
diff --git a/atomic-examples/progressive-disclosure/progressive_disclosure/agents/orchestrator_agent.py b/atomic-examples/progressive-disclosure/progressive_disclosure/agents/orchestrator_agent.pyindex 2052a25..e6857aa 100644--- a/atomic-examples/progressive-disclosure/progressive_disclosure/agents/orchestrator_agent.py+++ b/atomic-examples/progressive-disclosure/progressive_disclosure/agents/orchestrator_agent.py@@ -74,6 +74,7 @@ def create_orchestrator_output_schema(ActionUnion = Union[all_schemas] # type: ignore[valid-type]if parallel:+class ParallelOrchestratorOutputSchema(BaseIOSchema):"""Orchestrator output schema supporting parallel tool execution."""@@ -90,6 +91,7 @@ def create_orchestrator_output_schema(return ParallelOrchestratorOutputSchemaelse:+class DynamicOrchestratorOutputSchema(BaseIOSchema):"""Dynamically generated orchestrator output schema."""@@ -193,26 +195,18 @@ class OrchestratorFactory:)# Filter to only the requested tools- filtered_tools = [- tool for tool in all_tools- if getattr(tool, "mcp_tool_name", None) in tool_names- ]+ filtered_tools = [tool for tool in all_tools if getattr(tool, "mcp_tool_name", None) in tool_names]if not filtered_tools:# If no MCP tools match, create a minimal orchestratorreturn self._create_minimal_orchestrator(), {}# Build schema-to-class mapping for execution- tool_schema_to_class: Dict[Type[BaseIOSchema], Type[BaseTool]] = {- tool.input_schema: tool for tool in filtered_tools- }+ tool_schema_to_class: Dict[Type[BaseIOSchema], Type[BaseTool]] = {tool.input_schema: tool for tool in filtered_tools}# Create the dynamic output schema with only filtered toolstool_input_schemas = tuple(tool.input_schema for tool in filtered_tools)- output_schema = create_orchestrator_output_schema(- tool_input_schemas,- parallel=self.parallel_execution- )+ output_schema = create_orchestrator_output_schema(tool_input_schemas, parallel=self.parallel_execution)# Build tool descriptions for the system prompttool_descriptions = []@@ -368,9 +362,7 @@ def execute_orchestrator_loop(tool_output = tool_instance.run(action)# Add result to history- result_message = OrchestratorInputSchema(- query=f"Tool '{tool_name}' executed. Result: {tool_output.result}"- )+ result_message = OrchestratorInputSchema(query=f"Tool '{tool_name}' executed. Result: {tool_output.result}")orchestrator.history.add_message("system", result_message)# Continue the loop@@ -487,6 +479,7 @@ def execute_orchestrator_loop_parallel(try:# Use sync run method - it handles async internally for MCP toolsimport warnings+with warnings.catch_warnings():warnings.simplefilter("ignore", RuntimeWarning)tool_output = tool_instance.run(action)@@ -505,10 +498,7 @@ def execute_orchestrator_loop_parallel(# Execute all tools in parallelresults = []with ThreadPoolExecutor(max_workers=max_parallel_workers) as executor:- future_to_action = {- executor.submit(execute_single_tool, action): action- for action in tool_actions- }+ future_to_action = {executor.submit(execute_single_tool, action): action for action in tool_actions}for future in as_completed(future_to_action):results.append(future.result())diff --git a/atomic-examples/progressive-disclosure/progressive_disclosure/agents/tool_finder_agent.py b/atomic-examples/progressive-disclosure/progressive_disclosure/agents/tool_finder_agent.pyindex 7aeeb65..e94493e 100644--- a/atomic-examples/progressive-disclosure/progressive_disclosure/agents/tool_finder_agent.py+++ b/atomic-examples/progressive-disclosure/progressive_disclosure/agents/tool_finder_agent.py@@ -201,42 +201,54 @@ if __name__ == "__main__":# Create a test registryregistry = ToolRegistry()- registry.register(ToolMetadata(- name="add_numbers",- description="Add two numbers together",- keywords=["add", "sum", "plus", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="subtract_numbers",- description="Subtract one number from another",- keywords=["subtract", "minus", "difference", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="multiply_numbers",- description="Multiply two numbers together",- keywords=["multiply", "times", "product", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="divide_numbers",- description="Divide one number by another",- keywords=["divide", "quotient", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="uppercase",- description="Convert text to uppercase",- keywords=["upper", "capitalize", "text"],- category="text",- ))- registry.register(ToolMetadata(- name="reverse_text",- description="Reverse the characters in text",- keywords=["reverse", "backwards", "text"],- category="text",- ))+ registry.register(+ ToolMetadata(+ name="add_numbers",+ description="Add two numbers together",+ keywords=["add", "sum", "plus", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="subtract_numbers",+ description="Subtract one number from another",+ keywords=["subtract", "minus", "difference", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="multiply_numbers",+ description="Multiply two numbers together",+ keywords=["multiply", "times", "product", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="divide_numbers",+ description="Divide one number by another",+ keywords=["divide", "quotient", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="uppercase",+ description="Convert text to uppercase",+ keywords=["upper", "capitalize", "text"],+ category="text",+ )+ )+ registry.register(+ ToolMetadata(+ name="reverse_text",+ description="Reverse the characters in text",+ keywords=["reverse", "backwards", "text"],+ category="text",+ )+ )# Create clientclient = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))diff --git a/atomic-examples/progressive-disclosure/progressive_disclosure/main.py b/atomic-examples/progressive-disclosure/progressive_disclosure/main.pyindex 3eba6f4..a5d969d 100644--- a/atomic-examples/progressive-disclosure/progressive_disclosure/main.py+++ b/atomic-examples/progressive-disclosure/progressive_disclosure/main.py@@ -61,6 +61,7 @@ from progressive_disclosure.agents.orchestrator_agent import (@dataclassclass ServerConfig:"""Configuration for an MCP server."""+name: strcommand: strcategory: str # For tool categorization@@ -76,23 +77,13 @@ class ProgressiveDisclosureConfig:parallel_execution: bool = True # Enable parallel tool execution# Three MCP servers demonstrating multi-server progressive disclosure- servers: List[ServerConfig] = field(default_factory=lambda: [- ServerConfig(- name="math-server",- command="uv run pd-math-server",- category="math"- ),- ServerConfig(- name="text-server",- command="uv run pd-text-server",- category="text"- ),- ServerConfig(- name="data-server",- command="uv run pd-data-server",- category="data"- ),- ])+ servers: List[ServerConfig] = field(+ default_factory=lambda: [+ ServerConfig(name="math-server", command="uv run pd-math-server", category="math"),+ ServerConfig(name="text-server", command="uv run pd-text-server", category="text"),+ ServerConfig(name="data-server", command="uv run pd-data-server", category="data"),+ ]+ )def __post_init__(self):if not self.openai_api_key:@@ -119,18 +110,10 @@ class MCPServerManager:self.exit_stacks[config.name] = exit_stackcommand_parts = shlex.split(config.command)- server_params = StdioServerParameters(- command=command_parts[0],- args=command_parts[1:],- env=None- )+ server_params = StdioServerParameters(command=command_parts[0], args=command_parts[1:], env=None)- read_stream, write_stream = await exit_stack.enter_async_context(- stdio_client(server_params)- )- session = await exit_stack.enter_async_context(- ClientSession(read_stream, write_stream)- )+ read_stream, write_stream = await exit_stack.enter_async_context(stdio_client(server_params))+ session = await exit_stack.enter_async_context(ClientSession(read_stream, write_stream))await session.initialize()return session@@ -223,11 +206,13 @@ def main():console = Console()config = ProgressiveDisclosureConfig()- console.print(Panel.fit(- "[bold cyan]Progressive Disclosure Demo[/bold cyan]\n"- "[dim]Demonstrating Anthropic's pattern with 3 MCP servers (24 total tools)[/dim]",- border_style="cyan"- ))+ console.print(+ Panel.fit(+ "[bold cyan]Progressive Disclosure Demo[/bold cyan]\n"+ "[dim]Demonstrating Anthropic's pattern with 3 MCP servers (24 total tools)[/dim]",+ border_style="cyan",+ )+ )# Initialize instructor clientclient = instructor.from_openai(openai.OpenAI(api_key=config.openai_api_key))@@ -269,11 +254,13 @@ def main():for tool in server_manager.tools_by_server.get(server_config.name, []):name = getattr(tool, "mcp_tool_name", tool.__name__)description = tool.__doc__ or ""- mcp_definitions.append(MCPToolDefinition(- name=name,- description=description,- input_schema={},- ))+ mcp_definitions.append(+ MCPToolDefinition(+ name=name,+ description=description,+ input_schema={},+ )+ )registry.register_from_mcp(mcp_definitions)@@ -336,7 +323,9 @@ def main():stats.search_queries_made += len(finder_result.search_queries_used)stats.tools_selected = len(finder_result.selected_tools)- console.print(f"[green]Selected {len(finder_result.selected_tools)} tools:[/green] {finder_result.selected_tools}")+ console.print(+ f"[green]Selected {len(finder_result.selected_tools)} tools:[/green] {finder_result.selected_tools}"+ )console.print(f"[dim]Reasoning: {finder_result.reasoning}[/dim]")# Phase 2: Dynamic Orchestrator Creation@@ -389,11 +378,13 @@ def main():# Show savings summarysavings_pct = stats.tools_filtered_percentageparallel_info = " | ⚡ Parallel mode" if config.parallel_execution else ""- console.print(Panel(- f"[dim]Progressive Disclosure: {len(finder_result.selected_tools)}/{len(all_tools)} tools loaded "- f"({savings_pct:.0f}% context reduction){parallel_info}[/dim]",- border_style="dim",- ))+ console.print(+ Panel(+ f"[dim]Progressive Disclosure: {len(finder_result.selected_tools)}/{len(all_tools)} tools loaded "+ f"({savings_pct:.0f}% context reduction){parallel_info}[/dim]",+ border_style="dim",+ )+ )# Reset histories for next queryfinder_agent.history.history = []@@ -404,6 +395,7 @@ def main():except Exception as e:console.print(f"[red]Error:[/red] {str(e)}")import traceback+console.print(f"[dim]{traceback.format_exc()}[/dim]")finally:diff --git a/atomic-examples/progressive-disclosure/progressive_disclosure/registry/tool_registry.py b/atomic-examples/progressive-disclosure/progressive_disclosure/registry/tool_registry.pyindex 02334d3..c25c6a9 100644--- a/atomic-examples/progressive-disclosure/progressive_disclosure/registry/tool_registry.py+++ b/atomic-examples/progressive-disclosure/progressive_disclosure/registry/tool_registry.py@@ -95,20 +95,98 @@ class ToolRegistry:# Common stop words to filter outstop_words = {- "the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for",- "of", "with", "by", "from", "as", "is", "was", "are", "were", "been",- "be", "have", "has", "had", "do", "does", "did", "will", "would",- "could", "should", "may", "might", "must", "shall", "can", "this",- "that", "these", "those", "it", "its", "they", "them", "their",- "we", "us", "our", "you", "your", "i", "me", "my", "he", "she",- "his", "her", "which", "who", "whom", "what", "when", "where",- "why", "how", "all", "each", "every", "both", "few", "more",- "most", "other", "some", "such", "no", "not", "only", "own",- "same", "so", "than", "too", "very", "just", "also", "now",+ "the",+ "a",+ "an",+ "and",+ "or",+ "but",+ "in",+ "on",+ "at",+ "to",+ "for",+ "of",+ "with",+ "by",+ "from",+ "as",+ "is",+ "was",+ "are",+ "were",+ "been",+ "be",+ "have",+ "has",+ "had",+ "do",+ "does",+ "did",+ "will",+ "would",+ "could",+ "should",+ "may",+ "might",+ "must",+ "shall",+ "can",+ "this",+ "that",+ "these",+ "those",+ "it",+ "its",+ "they",+ "them",+ "their",+ "we",+ "us",+ "our",+ "you",+ "your",+ "i",+ "me",+ "my",+ "he",+ "she",+ "his",+ "her",+ "which",+ "who",+ "whom",+ "what",+ "when",+ "where",+ "why",+ "how",+ "all",+ "each",+ "every",+ "both",+ "few",+ "more",+ "most",+ "other",+ "some",+ "such",+ "no",+ "not",+ "only",+ "own",+ "same",+ "so",+ "than",+ "too",+ "very",+ "just",+ "also",+ "now",}# Extract words- words = re.findall(r'\b[a-zA-Z]+\b', description.lower())+ words = re.findall(r"\b[a-zA-Z]+\b", description.lower())# Filter and deduplicatekeywords = []diff --git a/atomic-examples/progressive-disclosure/progressive_disclosure/tools/search_tools.py b/atomic-examples/progressive-disclosure/progressive_disclosure/tools/search_tools.pyindex e074d3f..03fa403 100644--- a/atomic-examples/progressive-disclosure/progressive_disclosure/tools/search_tools.py+++ b/atomic-examples/progressive-disclosure/progressive_disclosure/tools/search_tools.py@@ -227,24 +227,30 @@ if __name__ == "__main__":# Create a test registryregistry = ToolRegistry()- registry.register(ToolMetadata(- name="AddNumbers",- description="Add two numbers together",- keywords=["add", "sum", "plus", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="SubtractNumbers",- description="Subtract one number from another",- keywords=["subtract", "minus", "difference", "arithmetic"],- category="math",- ))- registry.register(ToolMetadata(- name="SearchWeb",- description="Search the web for information",- keywords=["search", "web", "query", "find"],- category="search",- ))+ registry.register(+ ToolMetadata(+ name="AddNumbers",+ description="Add two numbers together",+ keywords=["add", "sum", "plus", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="SubtractNumbers",+ description="Subtract one number from another",+ keywords=["subtract", "minus", "difference", "arithmetic"],+ category="math",+ )+ )+ registry.register(+ ToolMetadata(+ name="SearchWeb",+ description="Search the web for information",+ keywords=["search", "web", "query", "find"],+ category="search",+ )+ )# Test searchsearch_tool = SearchToolsTool(SearchToolsConfig(registry=registry))diff --git a/atomic-examples/progressive-disclosure/servers/math_server/math_server/server.py b/atomic-examples/progressive-disclosure/servers/math_server/math_server/server.pyindex b647f13..7483061 100644--- a/atomic-examples/progressive-disclosure/servers/math_server/math_server/server.py+++ b/atomic-examples/progressive-disclosure/servers/math_server/math_server/server.py@@ -40,7 +40,7 @@ def divide_numbers(a: float, b: float) -> float:@mcp.tooldef power(base: float, exponent: float) -> float:"""Raise base to the power of exponent (base ** exponent). Use for exponentiation."""- return base ** exponent+ return base**exponent@mcp.tool