Skip to content

Building AI agents, atomically

auto-formatted and linted

Koichi KAWAMURAc83266303d48
diff --git a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
index 29c7245..a63b211 100644
--- a/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
+++ b/atomic-agents/atomic_agents/lib/factories/mcp_tool_factory.py
@@ -205,15 +205,12 @@ class MCPToolFactory:
"_event_loop": self.event_loop,
"working_directory": self.working_directory,
}
-
+
# Create the class using new_class() for proper generic type support
tool_class = types.new_class(
- tool_name,
- (BaseTool[InputSchema, OutputSchema],),
- {},
- lambda ns: ns.update(attrs)
+ tool_name, (BaseTool[InputSchema, OutputSchema],), {}, lambda ns: ns.update(attrs)
)
-
+
# Add the input_schema and output_schema class attributes explicitly
# since they might not be properly inherited with types.new_class
setattr(tool_class, "input_schema", InputSchema)
diff --git a/atomic-examples/deep-research/deep_research/agents/query_agent.py b/atomic-examples/deep-research/deep_research/agents/query_agent.py
index e7d741f..6978925 100644
--- a/atomic-examples/deep-research/deep_research/agents/query_agent.py
+++ b/atomic-examples/deep-research/deep_research/agents/query_agent.py
@@ -5,7 +5,7 @@ from pydantic import Field
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
-from deep_research.tools.searxng_search import SearXNGSearchTool, SearXNGSearchToolInputSchema
+from deep_research.tools.searxng_search import SearXNGSearchToolInputSchema
class QueryAgentInputSchema(BaseIOSchema):
diff --git a/atomic-examples/deep-research/deep_research/tools/searxng_search.py b/atomic-examples/deep-research/deep_research/tools/searxng_search.py
index 6825485..d07e23a 100644
--- a/atomic-examples/deep-research/deep_research/tools/searxng_search.py
+++ b/atomic-examples/deep-research/deep_research/tools/searxng_search.py
@@ -210,4 +210,4 @@ if __name__ == "__main__":
output = search_tool_instance.run(search_input)
- rich_console.print(output)
\ No newline at end of file
+ rich_console.print(output)
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
index d743fa2..a7f09c3 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
@@ -83,7 +83,7 @@ class OrchestratorOutputSchema(BaseIOSchema):
action: ActionUnion = Field( # type: ignore[reportInvalidTypeForm]
..., description="The chosen action: either a tool's input schema instance or a final response schema instance."
)
-
+
model_config = {"arbitrary_types_allowed": True}
@@ -91,25 +91,25 @@ class OrchestratorOutputSchema(BaseIOSchema):
def format_math_expressions(text):
"""
Format LaTeX-style math expressions for better readability in the terminal.
-
+
Args:
text (str): Text containing LaTeX-style math expressions
-
+
Returns:
str: Text with formatted math expressions
"""
# Replace \( and \) with formatted brackets
- text = re.sub(r'\\[\(\)]', '', text)
-
+ text = re.sub(r"\\[\(\)]", "", text)
+
# Replace LaTeX multiplication symbol with a plain x
- text = text.replace('\\times', '×')
-
+ text = text.replace("\\times", "×")
+
# Format other common LaTeX symbols
- text = text.replace('\\cdot', '·')
- text = text.replace('\\div', '÷')
- text = text.replace('\\sqrt', '√')
- text = text.replace('\\pi', 'π')
-
+ text = text.replace("\\cdot", "·")
+ text = text.replace("\\div", "÷")
+ text = text.replace("\\sqrt", "√")
+ text = text.replace("\\pi", "π")
+
return text
@@ -166,7 +166,7 @@ def main():
"4. Maintain a professional and helpful tone in all responses.",
"5. Break down complex queries into sequential tool calls before giving the final answer via `FinalResponseSchema`.",
],
- )
+ ),
)
)
console.print("[green]Successfully created orchestrator agent.[/green]")
@@ -182,65 +182,75 @@ def main():
try:
# Initial run with user query
orchestrator_output = orchestrator_agent.run(MCPOrchestratorInputSchema(query=query))
-
+
# Debug output to see what's actually in the output
- console.print(f"[dim]Debug - orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}")
-
+ console.print(
+ f"[dim]Debug - orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}"
+ )
+
# The model is returning a BaseAgentOutputSchema instead of OrchestratorOutputSchema
# We need to handle this case by creating a FinalResponseSchema directly
- if hasattr(orchestrator_output, 'chat_message') and not hasattr(orchestrator_output, 'action'):
+ if hasattr(orchestrator_output, "chat_message") and not hasattr(orchestrator_output, "action"):
console.print("[yellow]Note: Converting BaseAgentOutputSchema to FinalResponseSchema[/yellow]")
action_instance = FinalResponseSchema(response_text=orchestrator_output.chat_message)
reasoning = "Response generated directly from chat model"
# Handle the original expected format if it exists
- elif hasattr(orchestrator_output, 'action'):
+ elif hasattr(orchestrator_output, "action"):
action_instance = orchestrator_output.action
- reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, 'reasoning') else "No reasoning provided"
+ reasoning = (
+ orchestrator_output.reasoning if hasattr(orchestrator_output, "reasoning") else "No reasoning provided"
+ )
else:
console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
continue
-
+
console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
# Keep executing until we get a final response
while not isinstance(action_instance, FinalResponseSchema):
# Handle the case where action_instance is a dictionary
if isinstance(action_instance, dict):
- console.print("[yellow]Warning: Received dictionary instead of schema object. Attempting to convert...[/yellow]")
+ console.print(
+ "[yellow]Warning: Received dictionary instead of schema object. Attempting to convert...[/yellow]"
+ )
console.print(f"[dim]Dictionary contents: {action_instance}[/dim]")
-
+
# Special handling for function-call format {"recipient_name": "functions.toolname", "parameters": {...}}
if "recipient_name" in action_instance and "parameters" in action_instance:
console.print("[yellow]Detected function call format with recipient_name and parameters[/yellow]")
recipient = action_instance.get("recipient_name", "")
parameters = action_instance.get("parameters", {})
-
+
# Extract tool name from recipient (format might be "functions.toolname")
tool_parts = recipient.split(".")
if len(tool_parts) > 1:
tool_name = tool_parts[-1] # Take last part after the dot
- console.print(f"[yellow]Extracted tool name '{tool_name}' from recipient '{recipient}'[/yellow]")
-
+ console.print(
+ f"[yellow]Extracted tool name '{tool_name}' from recipient '{recipient}'[/yellow]"
+ )
+
# Special case for calculator
if tool_name.lower() == "calculate":
tool_name = "Calculator"
- console.print(f"[yellow]Mapped 'calculate' to 'Calculator' tool[/yellow]")
-
+ console.print("[yellow]Mapped 'calculate' to 'Calculator' tool[/yellow]")
+
# Try to find a matching tool class by name
matching_tool = next((t for t in tools if t.mcp_tool_name.lower() == tool_name.lower()), None)
-
+
if matching_tool:
try:
# Create an instance using the parameters
action_instance = matching_tool.input_schema(**parameters)
- console.print(f"[green]Successfully created {matching_tool.input_schema.__name__} from function call format[/green]")
+ console.print(
+ f"[green]Successfully created {matching_tool.input_schema.__name__} from function call format[/green]"
+ )
continue
except Exception as e:
console.print(f"[red]Error creating schema from function parameters: {e}[/red]")
-
+
# Try to find a tool_name in the dictionary (original approach)
tool_name = action_instance.get("tool_name")
-
+
# If tool_name is not found, try alternative approaches to identify the tool
if not tool_name:
# Approach 1: Look for a field that might contain a tool name
@@ -248,52 +258,73 @@ def main():
if "tool" in key.lower():
tool_name = action_instance.get(key)
if tool_name:
- console.print(f"[yellow]Found potential tool name '{tool_name}' in field '{key}'[/yellow]")
- break
-
+ console.print(
+ f"[yellow]Found potential tool name '{tool_name}' in field '{key}'[/yellow]"
+ )
+
# Approach 2: Try to match dictionary fields with tool schemas
if not tool_name:
console.print("[yellow]Trying to match dictionary fields with available tools...[/yellow]")
best_match = None
best_match_score = 0
-
+
for ToolClass in tools:
if not hasattr(ToolClass, "input_schema"):
continue
-
+
# Try to create a sample instance to get field names
try:
- schema_fields = set(ToolClass.input_schema.__annotations__.keys() if hasattr(ToolClass.input_schema, "__annotations__") else [])
+ schema_fields = set(
+ ToolClass.input_schema.__annotations__.keys()
+ if hasattr(ToolClass.input_schema, "__annotations__")
+ else []
+ )
dict_fields = set(action_instance.keys())
-
+
# Count matching fields
matching_fields = len(schema_fields.intersection(dict_fields))
if matching_fields > best_match_score and matching_fields > 0:
best_match_score = matching_fields
best_match = ToolClass
- console.print(f"[dim]Found {matching_fields} matching fields with {ToolClass.mcp_tool_name}[/dim]")
+ console.print(
+ f"[dim]Found {matching_fields} matching fields with {ToolClass.mcp_tool_name}[/dim]"
+ )
except Exception as e:
- console.print(f"[dim]Error checking {getattr(ToolClass, 'mcp_tool_name', 'unknown tool')}: {str(e)}[/dim]")
-
+ console.print(
+ f"[dim]Error checking {getattr(ToolClass, 'mcp_tool_name', 'unknown tool')}: {str(e)}[/dim]"
+ )
+
if best_match:
tool_name = best_match.mcp_tool_name
- console.print(f"[yellow]Best matching tool: {tool_name} with {best_match_score} matching fields[/yellow]")
-
+ console.print(
+ f"[yellow]Best matching tool: {tool_name} with {best_match_score} matching fields[/yellow]"
+ )
+
if not tool_name:
# Final fallback: Check if this might be a final response
- if any(key in action_instance for key in ["response_text", "text", "response", "message", "content"]):
- response_content = action_instance.get("response_text") or action_instance.get("text") or action_instance.get("response") or action_instance.get("message") or action_instance.get("content") or "No message content found"
+ if any(
+ key in action_instance for key in ["response_text", "text", "response", "message", "content"]
+ ):
+ response_content = (
+ action_instance.get("response_text")
+ or action_instance.get("text")
+ or action_instance.get("response")
+ or action_instance.get("message")
+ or action_instance.get("content")
+ or "No message content found"
+ )
console.print("[yellow]Appears to be a final response. Converting directly.[/yellow]")
action_instance = FinalResponseSchema(response_text=response_content)
continue
-
+
console.print("[red]Error: Could not determine tool type from dictionary[/red]")
# Create a final response with an error message
action_instance = FinalResponseSchema(
- response_text="I encountered an internal error. The tool could not be determined from the response. Please try rephrasing your question."
+ response_text="I encountered an internal error. The tool could not be determined from the response. "
+ "Please try rephrasing your question."
)
break
-
+
# Try to find a matching tool class by name
matching_tool = next((t for t in tools if t.mcp_tool_name == tool_name), None)
if not matching_tool:
@@ -303,20 +334,24 @@ def main():
response_text=f"I encountered an internal error. Could not find tool named '{tool_name}'."
)
break
-
+
# Create an instance of the input schema with the dictionary data
try:
# Remove tool_name if it's not a field in the schema
params = {}
has_annotations = hasattr(matching_tool.input_schema, "__annotations__")
-
+
for k, v in action_instance.items():
# Include the key-value pair if it's not "tool_name" or if it's a valid field in the schema
- if k not in ["tool_name"] or (has_annotations and k in matching_tool.input_schema.__annotations__.keys()):
+ if k not in ["tool_name"] or (
+ has_annotations and k in matching_tool.input_schema.__annotations__.keys()
+ ):
params[k] = v
-
+
action_instance = matching_tool.input_schema(**params)
- console.print(f"[green]Successfully converted dictionary to {matching_tool.input_schema.__name__}[/green]")
+ console.print(
+ f"[green]Successfully converted dictionary to {matching_tool.input_schema.__name__}[/green]"
+ )
except Exception as e:
console.print(f"[red]Error creating schema instance: {e}[/red]")
# Create a final response with an error message
@@ -324,7 +359,7 @@ def main():
response_text=f"I encountered an internal error when trying to use the {tool_name} tool: {str(e)}"
)
break
-
+
schema_type = type(action_instance)
ToolClass = tool_schema_to_class_map.get(schema_type)
if not ToolClass:
@@ -337,7 +372,7 @@ def main():
tool_name = ToolClass.mcp_tool_name
console.print(f"[blue]Executing tool:[/blue] {tool_name}")
- console.print(f"[dim]Parameters:[/dim] " f"{action_instance.model_dump()}")
+ console.print(f"[dim]Parameters: {action_instance.model_dump()}")
tool_instance = ToolClass()
tool_output = tool_instance.run(action_instance)
@@ -345,36 +380,43 @@ def main():
# Add tool result to agent memory
result_message = MCPOrchestratorInputSchema(
- query=(f"Tool {tool_name} executed with result: " f"{tool_output.result}")
+ query=f"Tool {tool_name} executed with result: {tool_output.result}"
)
orchestrator_agent.memory.add_message("system", result_message)
# Run the agent again without parameters to continue the flow
orchestrator_output = orchestrator_agent.run()
-
+
# Debug output for subsequent responses
- console.print(f"[dim]Debug - subsequent orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}")
-
+ console.print(
+ f"[dim]Debug - subsequent orchestrator_output type: {type(orchestrator_output)}, fields: {orchestrator_output.model_dump()}"
+ )
+
# Handle different response formats
- if hasattr(orchestrator_output, 'chat_message') and not hasattr(orchestrator_output, 'action'):
+ if hasattr(orchestrator_output, "chat_message") and not hasattr(orchestrator_output, "action"):
console.print("[yellow]Note: Converting BaseAgentOutputSchema to FinalResponseSchema[/yellow]")
action_instance = FinalResponseSchema(response_text=orchestrator_output.chat_message)
reasoning = "Response generated directly from chat model"
- elif hasattr(orchestrator_output, 'action'):
+ elif hasattr(orchestrator_output, "action"):
action_instance = orchestrator_output.action
- reasoning = orchestrator_output.reasoning if hasattr(orchestrator_output, 'reasoning') else "No reasoning provided"
+ reasoning = (
+ orchestrator_output.reasoning
+ if hasattr(orchestrator_output, "reasoning")
+ else "No reasoning provided"
+ )
else:
console.print("[yellow]Warning: Unexpected response format. Unable to process.[/yellow]")
break
-
+
console.print(f"[cyan]Orchestrator reasoning:[/cyan] {reasoning}")
# Final response from the agent
- response_text = getattr(action_instance, 'response_text',
- getattr(action_instance, 'chat_message', str(action_instance)))
+ response_text = getattr(
+ action_instance, "response_text", getattr(action_instance, "chat_message", str(action_instance))
+ )
md = Markdown(response_text)
# Render the response as markdown
- console.print(f"[bold blue]Agent: [/bold blue]")
+ console.print("[bold blue]Agent: [/bold blue]")
console.print(md)
except Exception as e:
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
index 85d72ca..1843861 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
@@ -114,7 +114,7 @@ class OrchestratorOutputSchema(BaseIOSchema):
action: ActionUnion = Field( # type: ignore[reportInvalidTypeForm]
..., description="The chosen action: either a tool's input schema instance or a final response schema instance."
)
-
+
model_config = {"arbitrary_types_allowed": True}
@@ -159,7 +159,7 @@ def main():
"4. Maintain a professional and helpful tone in all responses.",
"5. Break down complex queries into sequential tool calls before giving the final answer via `FinalResponseSchema`.",
],
- )
+ ),
)
)
console.print("[green]Successfully created orchestrator agent.[/green]")
diff --git a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
index e3eed86..0512406 100644
--- a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
+++ b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
@@ -3,7 +3,6 @@ import openai
from pydantic import Field
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
-from atomic_agents.lib.components.agent_memory import AgentMemory
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptContextProviderBase
from orchestration_agent.tools.searxng_search import (
@@ -90,12 +89,8 @@ orchestrator_agent_config = BaseAgentConfig(
],
),
)
-orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](
- config=orchestrator_agent_config
-)
-orchestrator_agent_final = BaseAgent[OrchestratorInputSchema, FinalAnswerSchema](
- config=orchestrator_agent_config
-)
+orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](config=orchestrator_agent_config)
+orchestrator_agent_final = BaseAgent[OrchestratorInputSchema, FinalAnswerSchema](config=orchestrator_agent_config)
# Register the current date provider
orchestrator_agent.register_context_provider("current_date", CurrentDateProvider("Current Date"))
@@ -184,6 +179,4 @@ if __name__ == "__main__":
final_answer = orchestrator_agent.run(input_schema)
console.print(f"\n[bold blue]Final Answer:[/bold blue] {final_answer.final_answer}")
# Reset the agent to the original
- orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](
- config=orchestrator_agent_config
- )
+ orchestrator_agent = BaseAgent[OrchestratorInputSchema, OrchestratorOutputSchema](config=orchestrator_agent_config)
diff --git a/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py b/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
index 9dfb8dc..edf3d7d 100644
--- a/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
+++ b/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
@@ -62,7 +62,8 @@ system_prompt_generator = SystemPromptGenerator(
"Analyze the user's input to understand the context and intent.",
"Formulate a relevant and informative response based on the assistant's knowledge.",
"Generate 3 suggested follow-up questions for the user to explore the topic further.",
- "When you get a simple number from the user, choose the corresponding question from the last list of suggested questions and answer it. Note that the first question is 1, the second is 2, and so on."
+ "When you get a simple number from the user, choose the corresponding question from the last list of "
+ "suggested questions and answer it. Note that the first question is 1, the second is 2, and so on.",
],
output_instructions=[
"Provide clear, concise, and accurate information in response to user queries.",
diff --git a/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py b/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
index 898571a..162cbfb 100644
--- a/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
+++ b/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
@@ -63,7 +63,7 @@ system_prompt_generator = SystemPromptGenerator(
"Analyze the user's input to understand the context and intent.",
"Formulate a relevant and informative response based on the assistant's knowledge.",
"Generate 3 suggested follow-up questions for the user to explore the topic further.",
- "When you get a simple number from the user, choose the corresponding question from the last list of suggested questions and answer it. Note that the first question is 1, the second is 2, and so on."
+ "When you get a simple number from the user, choose the corresponding question from the last list of suggested questions and answer it. Note that the first question is 1, the second is 2, and so on.",
],
output_instructions=[
"Provide clear, concise, and accurate information in response to user queries.",
diff --git a/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py b/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
index 78ec17d..ea9e0b3 100644
--- a/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
+++ b/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
@@ -4,8 +4,6 @@ import instructor
import openai
from rich.console import Console
from rich.live import Live
-from rich.panel import Panel
-from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich.text import Text
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig, BaseAgentInputSchema
@@ -70,11 +68,11 @@ async def exec_agent(message: str, idx: int, progress_dict: dict):
async with sem:
user_input = BaseAgentInputSchema(chat_message=message)
agent.reset_memory()
-
+
# Track streaming progress
partial_data = {}
progress_dict[idx] = {"status": "Processing", "data": partial_data, "message": message}
-
+
partial_response = None
# Actually demonstrate streaming by processing each partial response
async for partial_response in agent.run_async_stream(user_input):
@@ -84,54 +82,54 @@ async def exec_agent(message: str, idx: int, progress_dict: dict):
for field in ["name", "age", "pronouns", "profession"]:
if field in response_dict and response_dict[field]:
partial_data[field] = response_dict[field]
-
+
# Update progress dictionary to display changes in real-time
progress_dict[idx]["data"] = partial_data.copy()
# Small sleep to simulate processing and make streaming more visible
await asyncio.sleep(0.05)
-
+
assert partial_response
# Final response with complete data
response = PersonSchema(**partial_response.model_dump())
progress_dict[idx]["status"] = "Complete"
progress_dict[idx]["data"] = response.model_dump()
-
+
return response
def generate_status_table(progress_dict: dict) -> Table:
"""Generate a rich table showing the current processing status."""
table = Table(title="Asynchronous Stream Processing Demo")
-
+
table.add_column("ID", justify="center")
table.add_column("Status", justify="center")
table.add_column("Input", style="cyan")
table.add_column("Current Data", style="green")
-
+
for idx, info in progress_dict.items():
# Format the partial data nicely
data_str = ""
if info["data"]:
for k, v in info["data"].items():
data_str += f"{k}: {v}\n"
-
+
status_style = "yellow" if info["status"] == "Processing" else "green"
-
+
# Add row with current processing information
table.add_row(
f"{idx + 1}",
f"[{status_style}]{info['status']}[/{status_style}]",
Text(info["message"][:30] + "..." if len(info["message"]) > 30 else info["message"]),
- data_str or "Waiting..."
+ data_str or "Waiting...",
)
-
+
return table
async def process_all(dataset: list[str]):
"""Process all items in dataset with visual progress tracking."""
progress_dict = {} # Track processing status for visualization
-
+
# Create tasks for each message processing
tasks = []
for idx, message in enumerate(dataset):
@@ -140,17 +138,17 @@ async def process_all(dataset: list[str]):
# Create task without awaiting it
task = asyncio.create_task(exec_agent(message, idx, progress_dict))
tasks.append(task)
-
+
# Display live updating status while tasks run
with Live(generate_status_table(progress_dict), refresh_per_second=10) as live:
while not all(task.done() for task in tasks):
# Update the live display with current progress
live.update(generate_status_table(progress_dict))
await asyncio.sleep(0.1)
-
+
# Final update after all tasks complete
live.update(generate_status_table(progress_dict))
-
+
# Gather all results when complete
responses = await asyncio.gather(*tasks)
return responses
@@ -159,22 +157,17 @@ async def process_all(dataset: list[str]):
if __name__ == "__main__":
console.print("[bold blue]Starting Asynchronous Stream Processing Demo[/bold blue]")
console.print(f"Processing {len(dataset)} items with max {MAX_CONCURRENT} concurrent requests\n")
-
+
responses = asyncio.run(process_all(dataset))
-
+
# Display final results in a structured table
results_table = Table(title="Processing Results")
results_table.add_column("Name", style="cyan")
results_table.add_column("Age", justify="center")
results_table.add_column("Pronouns")
results_table.add_column("Profession")
-
+
for resp in responses:
- results_table.add_row(
- resp.name,
- str(resp.age),
- "/".join(resp.pronouns),
- resp.profession
- )
-
+ results_table.add_row(resp.name, str(resp.age), "/".join(resp.pronouns), resp.profession)
+
console.print(results_table)
diff --git a/atomic-examples/web-search-agent/web_search_agent/agents/query_agent.py b/atomic-examples/web-search-agent/web_search_agent/agents/query_agent.py
index 2c6a732..6ebcb2e 100644
--- a/atomic-examples/web-search-agent/web_search_agent/agents/query_agent.py
+++ b/atomic-examples/web-search-agent/web_search_agent/agents/query_agent.py
@@ -5,8 +5,6 @@ from typing import List
from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
-from web_search_agent.tools.searxng_search import SearXNGSearchTool
-
class QueryAgentInputSchema(BaseIOSchema):
"""This is the input schema for the QueryAgent."""
diff --git a/atomic-examples/web-search-agent/web_search_agent/main.py b/atomic-examples/web-search-agent/web_search_agent/main.py
index f0ee760..4eae84b 100644
--- a/atomic-examples/web-search-agent/web_search_agent/main.py
+++ b/atomic-examples/web-search-agent/web_search_agent/main.py
@@ -12,7 +12,7 @@ from web_search_agent.tools.searxng_search import (
SearXNGSearchTool,
SearXNGSearchToolConfig,
SearXNGSearchToolInputSchema,
- SearXNGSearchToolOutputSchema
+ SearXNGSearchToolOutputSchema,
)
from web_search_agent.agents.query_agent import QueryAgentInputSchema, query_agent
@@ -34,7 +34,7 @@ search_tool = SearXNGSearchTool(config=SearXNGSearchToolConfig(base_url=os.geten
class SearchResultsProvider(SystemPromptContextProviderBase):
- def __init__(self, title: str, search_results: SearXNGSearchToolOutputSchema|Exception):
+ def __init__(self, title: str, search_results: SearXNGSearchToolOutputSchema | Exception):
super().__init__(title=title)
self.search_results = search_results
@@ -121,5 +121,3 @@ while True:
console.print(f"[bold blue]Follow-up Question:[/bold blue] {instruction}")
except ValueError:
pass
-
-
diff --git a/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py b/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
index 3bc1d99..2d9cd60 100644
--- a/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
+++ b/atomic-examples/youtube-summarizer/youtube_summarizer/tools/youtube_transcript_scraper.py
@@ -1,10 +1,7 @@
import os
-import re
-from typing import List, Optional, Dict, Any
-import asyncio
-from concurrent.futures import ThreadPoolExecutor
+from typing import List, Optional, Any
-from pydantic import Field, BaseModel, HttpUrl
+from pydantic import Field, BaseModel
from datetime import datetime
from googleapiclient.discovery import build
@@ -13,9 +10,6 @@ from youtube_transcript_api import (
TranscriptsDisabled,
YouTubeTranscriptApi,
)
-import requests
-from bs4 import BeautifulSoup
-
from atomic_agents.agents.base_agent import BaseIOSchema
from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig
diff --git a/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py b/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
index 02d0869..21a07a9 100644
--- a/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
+++ b/atomic-examples/youtube-to-recipe/youtube_to_recipe/tools/youtube_transcript_scraper.py
@@ -1,8 +1,5 @@
import os
-import re
from typing import List, Optional
-import asyncio
-from concurrent.futures import ThreadPoolExecutor
from pydantic import Field, BaseModel
from datetime import datetime
@@ -13,9 +10,6 @@ from youtube_transcript_api import (
TranscriptsDisabled,
YouTubeTranscriptApi,
)
-import requests
-from bs4 import BeautifulSoup
-
from atomic_agents.agents.base_agent import BaseIOSchema
from atomic_agents.lib.base.base_tool import BaseTool, BaseToolConfig
@@ -180,7 +174,7 @@ if __name__ == "__main__":
load_dotenv()
rich_console = Console()
- search_tool_instance = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig(api_key=api_key))
+ search_tool_instance = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig())
search_input = YouTubeTranscriptTool.input_schema(video_url="https://www.youtube.com/watch?v=t1e8gqXLbsU", language="en")
diff --git a/atomic-forge/tools/calculator/tool/calculator.py b/atomic-forge/tools/calculator/tool/calculator.py
index 37581d3..c3df30b 100644
--- a/atomic-forge/tools/calculator/tool/calculator.py
+++ b/atomic-forge/tools/calculator/tool/calculator.py
@@ -1,5 +1,4 @@
-import numexpr
-from typing import Optional, Dict, Any
+from typing import Dict, Any
from pydantic import Field
from sympy import sympify