Skip to content

Building AI agents, atomically

flake8 & black

KennyVaneetveldeab3209436b7b
diff --git a/atomic-agents/atomic_agents/agents/atomic_agent.py b/atomic-agents/atomic_agents/agents/atomic_agent.py
index 7aa9387..74e0dd7 100644
--- a/atomic-agents/atomic_agents/agents/atomic_agent.py
+++ b/atomic-agents/atomic_agents/agents/atomic_agent.py
@@ -1,6 +1,6 @@
import instructor
from pydantic import BaseModel, Field
-from typing import Optional, Type, Generator, AsyncGenerator, get_args, Dict, List, Callable, Any
+from typing import Optional, Type, Generator, AsyncGenerator, get_args, Dict, List, Callable
import logging
from atomic_agents.context.chat_history import ChatHistory
from atomic_agents.context.system_prompt_generator import (
@@ -98,13 +98,13 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
Hook System:
The AtomicAgent integrates with Instructor's hook system to provide comprehensive monitoring
and error handling capabilities. Supported events include:
-
+
- 'parse:error': Triggered when Pydantic validation fails
- - 'completion:kwargs': Triggered before completion request
+ - 'completion:kwargs': Triggered before completion request
- 'completion:response': Triggered after completion response
- 'completion:error': Triggered on completion errors
- 'completion:last_attempt': Triggered on final retry attempt
-
+
Hook Methods:
- register_hook(event, handler): Register a hook handler for an event
- unregister_hook(event, handler): Remove a hook handler
@@ -116,14 +116,14 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
```python
# Basic usage
agent = AtomicAgent[InputSchema, OutputSchema](config)
-
+
# Register parse error hook for intelligent retry handling
def handle_parse_error(error):
print(f"Validation failed: {error}")
# Implement custom retry logic, logging, etc.
-
+
agent.register_hook("parse:error", handle_parse_error)
-
+
# Now parse:error hooks will fire on validation failures
response = agent.run(user_input)
```
@@ -144,7 +144,7 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
self.initial_history = self.history.copy()
self.current_user_input = None
self.model_api_parameters = config.model_api_parameters or {}
-
+
# Hook management attributes
self._hook_handlers: Dict[str, List[Callable]] = {}
self._hooks_enabled: bool = True
@@ -361,7 +361,7 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
def register_hook(self, event: str, handler: Callable) -> None:
"""
Registers a hook handler for a specific event.
-
+
Args:
event (str): The event name (e.g., 'parse:error', 'completion:kwargs', etc.)
handler (Callable): The callback function to handle the event
@@ -369,49 +369,49 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
if event not in self._hook_handlers:
self._hook_handlers[event] = []
self._hook_handlers[event].append(handler)
-
+
# Register with instructor client if it supports hooks
- if hasattr(self.client, 'on'):
+ if hasattr(self.client, "on"):
self.client.on(event, handler)
def unregister_hook(self, event: str, handler: Callable) -> None:
"""
Unregisters a hook handler for a specific event.
-
+
Args:
event (str): The event name
handler (Callable): The callback function to remove
"""
if event in self._hook_handlers and handler in self._hook_handlers[event]:
self._hook_handlers[event].remove(handler)
-
+
# Remove from instructor client if it supports hooks
- if hasattr(self.client, 'off'):
+ if hasattr(self.client, "off"):
self.client.off(event, handler)
def clear_hooks(self, event: Optional[str] = None) -> None:
"""
Clears hook handlers for a specific event or all events.
-
+
Args:
event (Optional[str]): The event name to clear, or None to clear all
"""
if event:
if event in self._hook_handlers:
# Clear from instructor client first
- if hasattr(self.client, 'clear'):
+ if hasattr(self.client, "clear"):
self.client.clear(event)
self._hook_handlers[event].clear()
else:
# Clear all hooks
- if hasattr(self.client, 'clear'):
+ if hasattr(self.client, "clear"):
self.client.clear()
self._hook_handlers.clear()
def _dispatch_hook(self, event: str, *args, **kwargs) -> None:
"""
Internal method to dispatch hook events with error isolation.
-
+
Args:
event (str): The event name
*args: Arguments to pass to handlers
@@ -419,7 +419,7 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
"""
if not self._hooks_enabled or event not in self._hook_handlers:
return
-
+
for handler in self._hook_handlers[event]:
try:
handler(*args, **kwargs)
diff --git a/atomic-agents/tests/agents/test_atomic_agent.py b/atomic-agents/tests/agents/test_atomic_agent.py
index ba9075c..aab24be 100644
--- a/atomic-agents/tests/agents/test_atomic_agent.py
+++ b/atomic-agents/tests/agents/test_atomic_agent.py
@@ -391,13 +391,15 @@ async def test_model_from_chunks_async_patched():
assert results == expected_values
+
# Hook System Tests
+
def test_hook_initialization(agent):
"""Test that hook system is properly initialized."""
# Verify hook attributes exist and are properly initialized
- assert hasattr(agent, '_hook_handlers')
- assert hasattr(agent, '_hooks_enabled')
+ assert hasattr(agent, "_hook_handlers")
+ assert hasattr(agent, "_hooks_enabled")
assert isinstance(agent._hook_handlers, dict)
assert agent._hooks_enabled is True
assert len(agent._hook_handlers) == 0
@@ -407,16 +409,16 @@ def test_hook_registration(agent):
"""Test hook registration and unregistration functionality."""
# Test registration
handler_called = []
-
+
def test_handler(error):
handler_called.append(error)
-
+
agent.register_hook("parse:error", test_handler)
-
+
# Verify internal storage
assert "parse:error" in agent._hook_handlers
assert test_handler in agent._hook_handlers["parse:error"]
-
+
# Test unregistration
agent.unregister_hook("parse:error", test_handler)
assert test_handler not in agent._hook_handlers["parse:error"]
@@ -428,17 +430,17 @@ def test_hook_registration_with_instructor_client(mock_instructor):
mock_instructor.on = Mock()
mock_instructor.off = Mock()
mock_instructor.clear = Mock()
-
+
config = AgentConfig(client=mock_instructor, model="gpt-4o-mini")
agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)
-
+
def test_handler(error):
pass
-
+
# Test registration delegates to instructor client
agent.register_hook("parse:error", test_handler)
mock_instructor.on.assert_called_once_with("parse:error", test_handler)
-
+
# Test unregistration delegates to instructor client
agent.unregister_hook("parse:error", test_handler)
mock_instructor.off.assert_called_once_with("parse:error", test_handler)
@@ -448,26 +450,26 @@ def test_multiple_hook_handlers(agent):
"""Test multiple handlers for the same event."""
handler1_calls = []
handler2_calls = []
-
+
def handler1(error):
handler1_calls.append(error)
-
+
def handler2(error):
handler2_calls.append(error)
-
+
# Register multiple handlers
agent.register_hook("parse:error", handler1)
agent.register_hook("parse:error", handler2)
-
+
# Verify both are registered
assert len(agent._hook_handlers["parse:error"]) == 2
assert handler1 in agent._hook_handlers["parse:error"]
assert handler2 in agent._hook_handlers["parse:error"]
-
+
# Test dispatch to both handlers
test_error = Exception("test error")
agent._dispatch_hook("parse:error", test_error)
-
+
assert len(handler1_calls) == 1
assert len(handler2_calls) == 1
assert handler1_calls[0] is test_error
@@ -476,19 +478,20 @@ def test_multiple_hook_handlers(agent):
def test_hook_clear_specific_event(agent):
"""Test clearing hooks for a specific event."""
+
def handler1():
pass
-
+
def handler2():
pass
-
+
# Register handlers for different events
agent.register_hook("parse:error", handler1)
agent.register_hook("completion:error", handler2)
-
+
# Clear specific event
agent.clear_hooks("parse:error")
-
+
# Verify only parse:error was cleared
assert len(agent._hook_handlers["parse:error"]) == 0
assert handler2 in agent._hook_handlers["completion:error"]
@@ -496,19 +499,20 @@ def test_hook_clear_specific_event(agent):
def test_hook_clear_all_events(agent):
"""Test clearing all hooks."""
+
def handler1():
pass
-
+
def handler2():
pass
-
+
# Register handlers for different events
agent.register_hook("parse:error", handler1)
agent.register_hook("completion:error", handler2)
-
+
# Clear all hooks
agent.clear_hooks()
-
+
# Verify all hooks are cleared
assert len(agent._hook_handlers) == 0
@@ -517,12 +521,12 @@ def test_hook_enable_disable(agent):
"""Test hook enable/disable functionality."""
# Test initial state
assert agent.hooks_enabled is True
-
+
# Test disable
agent.disable_hooks()
assert agent.hooks_enabled is False
assert agent._hooks_enabled is False
-
+
# Test enable
agent.enable_hooks()
assert agent.hooks_enabled is True
@@ -532,19 +536,19 @@ def test_hook_enable_disable(agent):
def test_hook_dispatch_when_disabled(agent):
"""Test that hooks don't execute when disabled."""
handler_called = []
-
+
def test_handler(error):
handler_called.append(error)
-
+
agent.register_hook("parse:error", test_handler)
-
+
# Disable hooks
agent.disable_hooks()
-
+
# Dispatch should not call handler
agent._dispatch_hook("parse:error", Exception("test"))
assert len(handler_called) == 0
-
+
# Re-enable and test
agent.enable_hooks()
agent._dispatch_hook("parse:error", Exception("test"))
@@ -554,27 +558,27 @@ def test_hook_dispatch_when_disabled(agent):
def test_hook_error_isolation(agent):
"""Test that hook handler errors don't interrupt main flow."""
good_handler_called = []
-
+
def bad_handler(error):
raise RuntimeError("Handler error")
-
+
def good_handler(error):
good_handler_called.append(error)
-
+
# Register both handlers
agent.register_hook("test:event", bad_handler)
agent.register_hook("test:event", good_handler)
-
+
# Dispatch should not raise exception
- with patch('logging.getLogger') as mock_logger:
+ with patch("logging.getLogger") as mock_logger:
mock_log = Mock()
mock_logger.return_value = mock_log
-
+
agent._dispatch_hook("test:event", Exception("test"))
-
+
# Verify error was logged
mock_log.warning.assert_called_once()
-
+
# Verify good handler still executed
assert len(good_handler_called) == 1
@@ -587,9 +591,10 @@ def test_hook_dispatch_nonexistent_event(agent):
def test_hook_unregister_nonexistent_handler(agent):
"""Test unregistering handler that doesn't exist."""
+
def test_handler():
pass
-
+
# Should not raise exception
agent.unregister_hook("parse:error", test_handler)
@@ -602,72 +607,72 @@ def test_agent_initialization_includes_hooks(mock_instructor, mock_history, mock
history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
)
-
+
agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)
-
+
# Verify hook system is initialized
- assert hasattr(agent, '_hook_handlers')
- assert hasattr(agent, '_hooks_enabled')
+ assert hasattr(agent, "_hook_handlers")
+ assert hasattr(agent, "_hooks_enabled")
assert agent._hooks_enabled is True
assert isinstance(agent._hook_handlers, dict)
assert len(agent._hook_handlers) == 0
-
+
# Verify hook management methods exist
- assert hasattr(agent, 'register_hook')
- assert hasattr(agent, 'unregister_hook')
- assert hasattr(agent, 'clear_hooks')
- assert hasattr(agent, 'enable_hooks')
- assert hasattr(agent, 'disable_hooks')
- assert hasattr(agent, 'hooks_enabled')
- assert hasattr(agent, '_dispatch_hook')
+ assert hasattr(agent, "register_hook")
+ assert hasattr(agent, "unregister_hook")
+ assert hasattr(agent, "clear_hooks")
+ assert hasattr(agent, "enable_hooks")
+ assert hasattr(agent, "disable_hooks")
+ assert hasattr(agent, "hooks_enabled")
+ assert hasattr(agent, "_dispatch_hook")
def test_backward_compatibility_no_breaking_changes(mock_instructor, mock_history, mock_system_prompt_generator):
"""Test that hook system addition doesn't break existing functionality."""
config = AgentConfig(
client=mock_instructor,
- model="gpt-4o-mini",
+ model="gpt-4o-mini",
history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
)
-
+
agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)
-
+
# Test that all existing attributes still exist and work
assert agent.client == mock_instructor
assert agent.model == "gpt-4o-mini"
assert agent.history == mock_history
assert agent.system_prompt_generator == mock_system_prompt_generator
-
+
# Test that existing methods still work
agent.reset_history()
-
+
# Properties should work
assert agent.input_schema == BasicChatInputSchema
assert agent.output_schema == BasicChatOutputSchema
-
+
# Run method should work (with hooks enabled by default)
user_input = BasicChatInputSchema(chat_message="test")
response = agent.run(user_input)
-
+
# Verify the call was made correctly
mock_instructor.chat.completions.create.assert_called()
-
+
# Test context provider methods still work
from atomic_agents.context import BaseDynamicContextProvider
-
+
class TestProvider(BaseDynamicContextProvider):
def get_info(self):
return "test"
-
+
provider = TestProvider(title="Test")
agent.register_context_provider("test", provider)
-
+
retrieved = agent.get_context_provider("test")
assert retrieved == provider
-
+
agent.unregister_context_provider("test")
-
+
# Should raise KeyError for non-existent provider
with pytest.raises(KeyError):
agent.get_context_provider("test")
diff --git a/atomic-examples/hooks-example/hooks_example/main.py b/atomic-examples/hooks-example/hooks_example/main.py
index d2f8958..d559547 100644
--- a/atomic-examples/hooks-example/hooks_example/main.py
+++ b/atomic-examples/hooks-example/hooks_example/main.py
@@ -17,23 +17,20 @@ Run with: python main.py
import os
import time
import logging
-from typing import Dict, Any
-from datetime import datetime
import instructor
import openai
from rich.console import Console
from rich.panel import Panel
-from rich.text import Text
from rich.table import Table
-from pydantic import BaseModel, Field, ValidationError
+from pydantic import Field, ValidationError
from atomic_agents import AtomicAgent, AgentConfig
from atomic_agents.context import ChatHistory
from atomic_agents.base.base_io_schema import BaseIOSchema
# Configure logging
-logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
+logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Initialize Rich console for pretty output
@@ -47,29 +44,36 @@ metrics = {
"parse_errors": 0,
"retry_attempts": 0,
"total_response_time": 0.0,
- "start_time": time.time()
+ "start_time": time.time(),
}
# Global variable to track request start times
_request_start_time = None
+
class UserQuery(BaseIOSchema):
"""User input schema for the agent."""
+
chat_message: str = Field(..., description="User's question or message")
+
class AgentResponse(BaseIOSchema):
"""Agent response schema with confidence scoring."""
+
chat_message: str = Field(..., description="Agent's response to the user")
confidence: float = Field(..., ge=0.0, le=1.0, description="Confidence score (0.0-1.0)")
reasoning: str = Field(..., description="Brief explanation of the reasoning")
+
class DetailedResponse(BaseIOSchema):
"""More complex response schema to test validation."""
+
chat_message: str = Field(..., description="Primary response")
alternative_suggestions: list[str] = Field(default_factory=list, description="Alternative suggestions")
confidence_level: str = Field(..., description="Must be 'low', 'medium', or 'high'")
requires_followup: bool = Field(default=False, description="Whether follow-up is needed")
+
def setup_api_key() -> str:
"""Setup and validate API key."""
api_key = os.getenv("OPENAI_API_KEY")
@@ -79,19 +83,18 @@ def setup_api_key() -> str:
exit(1)
return api_key
+
def display_metrics():
"""Display current performance metrics."""
runtime = time.time() - metrics["start_time"]
- avg_response_time = (metrics["total_response_time"] / metrics["total_requests"]
- if metrics["total_requests"] > 0 else 0)
-
- success_rate = (metrics["successful_requests"] / metrics["total_requests"] * 100
- if metrics["total_requests"] > 0 else 0)
-
+ avg_response_time = metrics["total_response_time"] / metrics["total_requests"] if metrics["total_requests"] > 0 else 0
+
+ success_rate = metrics["successful_requests"] / metrics["total_requests"] * 100 if metrics["total_requests"] > 0 else 0
+
table = Table(title="๐Ÿ” Hook System Performance Metrics", style="cyan")
table.add_column("Metric", style="bold")
table.add_column("Value", style="green")
-
+
table.add_row("Runtime", f"{runtime:.1f}s")
table.add_row("Total Requests", str(metrics["total_requests"]))
table.add_row("Successful Requests", str(metrics["successful_requests"]))
@@ -100,46 +103,50 @@ def display_metrics():
table.add_row("Retry Attempts", str(metrics["retry_attempts"]))
table.add_row("Success Rate", f"{success_rate:.1f}%")
table.add_row("Avg Response Time", f"{avg_response_time:.2f}s")
-
+
console.print(table)
+
# Hook functions for comprehensive monitoring and error handling
+
def on_parse_error(error):
"""Handle parse errors with detailed logging and metrics update."""
metrics["parse_errors"] += 1
metrics["failed_requests"] += 1
-
+
logger.error(f"๐Ÿšจ Parse error occurred: {type(error).__name__}: {error}")
-
+
if isinstance(error, ValidationError):
- console.print(f"[bold red]โŒ Validation Error:[/bold red]")
+ console.print("[bold red]โŒ Validation Error:[/bold red]")
for err in error.errors():
- field_path = " -> ".join(str(x) for x in err['loc'])
+ field_path = " -> ".join(str(x) for x in err["loc"])
console.print(f" โ€ข Field '{field_path}': {err['msg']}")
logger.error(f"Validation error in field '{field_path}': {err['msg']}")
else:
console.print(f"[bold red]โŒ Parse Error:[/bold red] {error}")
-
+
# In a production system, you might:
# - Send error to monitoring service
# - Trigger alerts for high error rates
# - Store detailed error context for analysis
+
def on_completion_kwargs(**kwargs):
"""Monitor outgoing API calls."""
global _request_start_time
metrics["total_requests"] += 1
-
+
# Log API call details (without sensitive information)
- model = kwargs.get('model', 'unknown')
- messages_count = len(kwargs.get('messages', []))
-
+ model = kwargs.get("model", "unknown")
+ messages_count = len(kwargs.get("messages", []))
+
logger.info(f"๐Ÿš€ API call starting - Model: {model}, Messages: {messages_count}")
-
+
# Store start time for response time calculation
_request_start_time = time.time()
+
def on_completion_response(response, **kwargs):
"""Monitor API responses and calculate metrics."""
global _request_start_time
@@ -148,95 +155,100 @@ def on_completion_response(response, **kwargs):
metrics["total_response_time"] += response_time
logger.info(f"โœ… API call completed in {response_time:.2f}s")
_request_start_time = None # Reset for next request
-
+
# Log response details
- if hasattr(response, 'usage'):
+ if hasattr(response, "usage"):
usage = response.usage
- logger.info(f"๐Ÿ“Š Token usage - Prompt: {usage.prompt_tokens}, "
- f"Completion: {usage.completion_tokens}, "
- f"Total: {usage.total_tokens}")
-
+ logger.info(
+ f"๐Ÿ“Š Token usage - Prompt: {usage.prompt_tokens}, "
+ f"Completion: {usage.completion_tokens}, "
+ f"Total: {usage.total_tokens}"
+ )
+
metrics["successful_requests"] += 1
+
def on_completion_error(error, **kwargs):
"""Handle API errors with retry logic."""
global _request_start_time
metrics["failed_requests"] += 1
metrics["retry_attempts"] += 1
-
+
# Reset start time on error
if _request_start_time:
_request_start_time = None
-
+
logger.error(f"๐Ÿ”ฅ API error: {type(error).__name__}: {error}")
console.print(f"[bold red]๐Ÿ”ฅ API Error:[/bold red] {error}")
-
+
# In a production system, you might implement:
# - Exponential backoff retry logic
# - Fallback to different models
# - Circuit breaker patterns
# - Dead letter queues for failed requests
+
def create_agent_with_hooks(schema_type: type, system_prompt: str = None) -> AtomicAgent:
"""Create an AtomicAgent with comprehensive hook setup."""
api_key = setup_api_key()
client = instructor.from_openai(openai.OpenAI(api_key=api_key))
-
+
# Create agent with configuration
config = AgentConfig(
client=client,
model="gpt-4o-mini", # Using a reliable model for demonstrations
history=ChatHistory(),
- system_prompt=system_prompt
+ system_prompt=system_prompt,
)
-
+
agent = AtomicAgent[UserQuery, schema_type](config)
-
+
# Register comprehensive hook suite
agent.register_hook("parse:error", on_parse_error)
agent.register_hook("completion:kwargs", on_completion_kwargs)
agent.register_hook("completion:response", on_completion_response)
agent.register_hook("completion:error", on_completion_error)
-
+
console.print("[bold green]โœ… Agent created with comprehensive hook monitoring[/bold green]")
return agent
+
def demonstrate_basic_hooks():
"""Demonstrate basic hook functionality with simple responses."""
console.print(Panel("๐Ÿ”ง Basic Hook System Demonstration", style="bold blue"))
-
+
# Create agent with basic schema
agent = create_agent_with_hooks(
- AgentResponse,
- "You are a helpful assistant. Always provide confident, well-reasoned responses."
+ AgentResponse, "You are a helpful assistant. Always provide confident, well-reasoned responses."
)
-
+
test_queries = [
"What is the capital of France?",
"Explain quantum computing in simple terms.",
- "What are the benefits of renewable energy?"
+ "What are the benefits of renewable energy?",
]
-
+
for query_text in test_queries:
console.print(f"\n[bold cyan]Query:[/bold cyan] {query_text}")
-
+
try:
query = UserQuery(chat_message=query_text)
response = agent.run(query)
-
+
console.print(f"[bold green]Response:[/bold green] {response.chat_message}")
console.print(f"[bold yellow]Confidence:[/bold yellow] {response.confidence:.2f}")
console.print(f"[bold magenta]Reasoning:[/bold magenta] {response.reasoning}")
-
+
except Exception as e:
console.print(f"[bold red]Error processing query:[/bold red] {e}")
-
+
display_metrics()
+
def demonstrate_validation_errors():
"""Demonstrate hook system handling validation errors."""
console.print(Panel("๐Ÿšจ Validation Error Handling Demonstration", style="bold red"))
-
+
# Create agent with strict validation schema
agent = create_agent_with_hooks(
DetailedResponse,
@@ -246,48 +258,48 @@ def demonstrate_validation_errors():
- Confidence level (exactly 'low', 'medium', or 'high')
- Whether follow-up is needed (boolean)
- Be very strict about the confidence_level field - it must be exactly one of the three allowed values."""
+ Be very strict about the confidence_level field - it must be exactly one of the three allowed values.""",
)
-
+
# Queries designed to potentially trigger validation errors
validation_test_queries = [
"Give me a simple yes or no answer about whether the sky is blue.",
"Provide a complex analysis of climate change with multiple perspectives.",
]
-
+
for query_text in validation_test_queries:
console.print(f"\n[bold cyan]Query:[/bold cyan] {query_text}")
-
+
try:
query = UserQuery(chat_message=query_text)
response = agent.run(query)
-
+
console.print(f"[bold green]Main Answer:[/bold green] {response.chat_message}")
console.print(f"[bold yellow]Confidence Level:[/bold yellow] {response.confidence_level}")
console.print(f"[bold magenta]Alternatives:[/bold magenta] {response.alternative_suggestions}")
console.print(f"[bold cyan]Needs Follow-up:[/bold cyan] {response.requires_followup}")
-
+
except Exception as e:
console.print(f"[bold red]Handled error:[/bold red] {e}")
-
+
display_metrics()
+
def demonstrate_interactive_mode():
"""Interactive demonstration where users can test the hook system."""
console.print(Panel("๐ŸŽฎ Interactive Hook System Testing", style="bold magenta"))
-
+
agent = create_agent_with_hooks(
- AgentResponse,
- "You are a helpful assistant. Provide clear, confident responses with reasoning."
+ AgentResponse, "You are a helpful assistant. Provide clear, confident responses with reasoning."
)
-
+
console.print("[bold green]Welcome to the interactive hook system demo![/bold green]")
console.print("Type your questions below. Use /metrics to see performance data, /exit to quit.")
-
+
while True:
try:
user_input = console.input("\n[bold blue]Your question:[/bold blue] ")
-
+
if user_input.lower() in ["/exit", "/quit"]:
console.print("Exiting interactive mode...")
break
@@ -296,30 +308,32 @@ def demonstrate_interactive_mode():
continue
elif user_input.strip() == "":
continue
-
+
query = UserQuery(chat_message=user_input)
start_time = time.time()
-
+
response = agent.run(query)
-
+
response_time = time.time() - start_time
-
+
console.print(f"\n[bold green]Answer:[/bold green] {response.chat_message}")
console.print(f"[bold yellow]Confidence:[/bold yellow] {response.confidence:.2f}")
console.print(f"[bold magenta]Reasoning:[/bold magenta] {response.reasoning}")
console.print(f"[dim]Response time: {response_time:.2f}s[/dim]")
-
+
except KeyboardInterrupt:
console.print("\nExiting on user interrupt...")
break
except Exception as e:
console.print(f"[bold red]Error:[/bold red] {e}")
+
def main():
"""Main demonstration function."""
console.print(Panel.fit("๐ŸŽฏ AtomicAgent Hook System Comprehensive Demo", style="bold green"))
-
- console.print("""
+
+ console.print(
+ """
[bold cyan]This demonstration showcases:[/bold cyan]
โ€ข ๐Ÿ” Comprehensive monitoring with hooks
โ€ข ๐Ÿ›ก๏ธ Robust error handling and validation
@@ -328,22 +342,23 @@ def main():
[bold yellow]The hook system provides zero-overhead monitoring when hooks aren't registered,
and powerful insights when they are enabled.[/bold yellow]
- """)
-
+ """
+ )
+
try:
# Run basic demonstration
demonstrate_basic_hooks()
-
- console.print("\n" + "="*50)
-
- # Run validation error demonstration
+
+ console.print("\n" + "=" * 50)
+
+ # Run validation error demonstration
demonstrate_validation_errors()
-
- console.print("\n" + "="*50)
-
+
+ console.print("\n" + "=" * 50)
+
# Interactive mode
demonstrate_interactive_mode()
-
+
except KeyboardInterrupt:
console.print("\n[bold yellow]Demo interrupted by user.[/bold yellow]")
except Exception as e:
@@ -351,11 +366,12 @@ and powerful insights when they are enabled.[/bold yellow]
logger.error(f"Demo error: {e}", exc_info=True)
finally:
# Final metrics display
- console.print("\n" + "="*50)
+ console.print("\n" + "=" * 50)
console.print(Panel("๐Ÿ“Š Final Performance Summary", style="bold green"))
display_metrics()
-
- console.print("""
+
+ console.print(
+ """
[bold green]โœ… Hook system demonstration complete![/bold green]
[bold cyan]Key takeaways:[/bold cyan]
@@ -369,7 +385,9 @@ and powerful insights when they are enabled.[/bold yellow]
โ€ข Add monitoring service integration
โ€ข Explore advanced error recovery patterns
โ€ข Build custom metrics dashboards
- """)
+ """
+ )
+
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()