8.8 KiB
8.8 KiB
Agent API Reference
This reference document provides detailed API documentation for the Agent class and related components in CleverAgents.
Table of Contents
- Agent Class API
- Agent Methods and Properties
- Configuration Options
- Lifecycle Hooks
- Error Codes and Exceptions
Agent Class API
Class Definition
class Agent:
"""
Base class for all agents in CleverAgents.
An agent is an autonomous entity that can perceive its environment,
reason about goals and available actions, and execute plans.
"""
Constructor
def __init__(
self,
name: str,
description: str = "",
version: str = "1.0.0",
config: Optional[Dict[str, Any]] = None
) -> None:
"""
Initialize an agent.
Args:
name: Unique identifier for the agent
description: Human-readable description of the agent
version: Version string for the agent
config: Optional configuration dictionary
"""
Agent Methods and Properties
Core Methods
execute()
def execute(
self,
goal: str,
context: Optional[Dict[str, Any]] = None,
constraints: Optional[Dict[str, Any]] = None,
timeout: Optional[int] = None
) -> Dict[str, Any]:
"""
Execute the agent on a goal.
Args:
goal: The goal to accomplish
context: Optional context information
constraints: Optional execution constraints
timeout: Optional timeout in seconds
Returns:
Execution result dictionary
Raises:
AgentError: If execution fails
TimeoutError: If execution exceeds timeout
"""
initialize()
def initialize(
self,
config: Dict[str, Any]
) -> None:
"""
Initialize the agent with configuration.
Args:
config: Configuration dictionary
Raises:
ConfigurationError: If configuration is invalid
"""
cleanup()
def cleanup() -> None:
"""
Clean up agent resources.
Should be called when the agent is no longer needed.
"""
Skill Methods
add_skill()
def add_skill(
self,
skill: Skill
) -> None:
"""
Add a skill to the agent.
Args:
skill: Skill instance to add
Raises:
ValueError: If skill name already exists
"""
execute_skill()
def execute_skill(
self,
skill_name: str,
parameters: Dict[str, Any]
) -> Dict[str, Any]:
"""
Execute a skill.
Args:
skill_name: Name of the skill to execute
parameters: Parameters for the skill
Returns:
Skill execution result
Raises:
SkillNotFoundError: If skill doesn't exist
SkillExecutionError: If skill execution fails
"""
Tool Methods
add_tool()
def add_tool(
self,
tool: Tool
) -> None:
"""
Add a tool to the agent.
Args:
tool: Tool instance to add
Raises:
ValueError: If tool name already exists
"""
execute_tool()
def execute_tool(
self,
tool_name: str,
parameters: Dict[str, Any]
) -> Dict[str, Any]:
"""
Execute a tool.
Args:
tool_name: Name of the tool to execute
parameters: Parameters for the tool
Returns:
Tool execution result
Raises:
ToolNotFoundError: If tool doesn't exist
ToolExecutionError: If tool execution fails
"""
Properties
name
@property
def name(self) -> str:
"""Get the agent name."""
description
@property
def description(self) -> str:
"""Get the agent description."""
version
@property
def version(self) -> str:
"""Get the agent version."""
skills
@property
def skills(self) -> Dict[str, Skill]:
"""Get registered skills."""
tools
@property
def tools(self) -> Dict[str, Tool]:
"""Get registered tools."""
Configuration Options
Core Configuration
agent:
# Agent identity
name: string # Required: Agent name
description: string # Optional: Agent description
version: string # Optional: Agent version (default: "1.0.0")
# Execution settings
max_iterations: integer # Maximum execution iterations (default: 10)
timeout: integer # Timeout in seconds (default: 300)
temperature: float # LLM temperature (default: 0.7)
# Model configuration
model:
provider: string # LLM provider (openai, anthropic, etc.)
name: string # Model name
api_key: string # API key (can use env vars)
# Resource limits
resources:
memory_limit: string # Memory limit (e.g., "2GB")
cpu_limit: string # CPU limit (e.g., "2")
timeout: integer # Timeout in seconds
Lifecycle Hooks
Agents support the following lifecycle hooks:
on_initialize()
def on_initialize(self) -> None:
"""Called after agent initialization."""
on_execution_start()
def on_execution_start(self) -> None:
"""Called when execution begins."""
on_execution_end()
def on_execution_end(self, result: Dict[str, Any]) -> None:
"""Called when execution completes."""
on_error()
def on_error(self, error: Exception) -> None:
"""Called when an error occurs."""
on_cleanup()
def on_cleanup(self) -> None:
"""Called during cleanup."""
Error Codes and Exceptions
Exception Hierarchy
AgentError (base exception)
├── SkillExecutionError
├── ToolExecutionError
├── ResourceExhaustedError
├── TimeoutError
├── ValidationError
├── ConfigurationError
└── SkillNotFoundError
AgentError
Base exception for all agent-related errors.
class AgentError(Exception):
"""Base exception for agent errors."""
pass
SkillExecutionError
Raised when skill execution fails.
class SkillExecutionError(AgentError):
"""Raised when skill execution fails."""
def __init__(
self,
skill_name: str,
message: str,
cause: Optional[Exception] = None
):
self.skill_name = skill_name
self.message = message
self.cause = cause
ToolExecutionError
Raised when tool execution fails.
class ToolExecutionError(AgentError):
"""Raised when tool execution fails."""
def __init__(
self,
tool_name: str,
message: str,
cause: Optional[Exception] = None
):
self.tool_name = tool_name
self.message = message
self.cause = cause
ResourceExhaustedError
Raised when resource limits are exceeded.
class ResourceExhaustedError(AgentError):
"""Raised when resource limits are exceeded."""
def __init__(
self,
resource_type: str,
limit: Any,
current: Any
):
self.resource_type = resource_type
self.limit = limit
self.current = current
TimeoutError
Raised when execution timeout is exceeded.
class TimeoutError(AgentError):
"""Raised when execution timeout is exceeded."""
def __init__(
self,
timeout: int,
elapsed: int
):
self.timeout = timeout
self.elapsed = elapsed
ValidationError
Raised when input validation fails.
class ValidationError(AgentError):
"""Raised when input validation fails."""
def __init__(
self,
field: str,
message: str
):
self.field = field
self.message = message
Usage Examples
Basic Agent Usage
from cleveragents.agents import Agent
# Create agent
agent = Agent(
name="my_agent",
description="My custom agent",
version="1.0.0"
)
# Initialize
agent.initialize({
"max_iterations": 10,
"timeout": 300
})
# Execute
result = agent.execute(
goal="Analyze the provided document",
context={"document": "..."}
)
# Cleanup
agent.cleanup()
With Skills and Tools
# Add skills
agent.add_skill(DocumentAnalysisSkill())
agent.add_skill(SummarizationSkill())
# Add tools
agent.add_tool(FileReaderTool())
agent.add_tool(DatabaseWriterTool())
# Execute skill
result = agent.execute_skill(
"document_analysis",
{"document": content}
)
# Execute tool
result = agent.execute_tool(
"file_reader",
{"file_path": "/path/to/file.txt"}
)