orka.agents.base_agent moduleο
π§ Agents Domain - Intelligent Processing Unitsο
This module defines the foundation for all OrKa agents - the cognitive building blocks of your AI workflows. Agents are specialized processing units that transform inputs into structured outputs while maintaining context and handling errors gracefully.
Core Agent Philosophy: Think of agents as expert consultants in your workflow - each with specialized knowledge and capabilities, working together to solve complex problems. They provide:
π― Specialized Intelligence: Each agent excels at specific tasks
π§ Context Awareness: Maintains conversation and processing context
π Error Resilience: Graceful failure handling with fallback strategies
β‘ Performance: Async execution with concurrency control
π§ Flexibility: Support for both cloud LLMs and local models
Agent Types: - Classification Agents: Route and categorize inputs intelligently - Answer Builders: Synthesize complex information into coherent responses - Binary Agents: Make precise true/false decisions - Memory Agents: Store and retrieve contextual information - Tool Agents: Integrate with external services and APIs
Real-world Applications: - Customer service workflows with intelligent routing - Content moderation with multi-stage validation - Research assistants that combine search and synthesis - Conversational AI with persistent memory
- class orka.agents.base_agent.BaseAgent(agent_id: str, registry: Registry | None = None, prompt: str | None = None, queue: list[str] | None = None, timeout: float | None = 30.0, max_concurrency: int = 10, **kwargs)[source]ο
Bases:
object
Agent Base Classesο
This module defines the foundation for all OrKa agents - the processing units that transform inputs into outputs within orchestrated workflows.
Agent Architectureο
OrKa provides two agent patterns to support different implementation needs:
Modern Async Pattern (BaseAgent) - Full async/await support for concurrent execution - Structured output handling with automatic error wrapping - Built-in timeout and concurrency control - Lifecycle hooks for initialization and cleanup - Context-aware execution with trace information
Legacy Sync Pattern (LegacyBaseAgent) - Simple synchronous execution model - Compatible with existing agent implementations - Direct result return without output wrapping - Backward compatibility for older agents
Core Conceptsο
Agent Lifecycle: 1. Initialization: Set up resources and validate configuration 2. Execution: Process inputs with context awareness 3. Result Handling: Structure outputs for downstream processing 4. Cleanup: Release resources and maintain system health
Context Management: - Agents receive context dictionaries containing input data and metadata - Trace IDs are automatically added for debugging and monitoring - Previous outputs from other agents are available in the context - Error information is captured and structured for debugging
Concurrency Control: - Built-in concurrency manager limits parallel executions - Configurable timeout handling prevents hanging operations - Thread-safe execution for multi-agent workflows - Resource pooling for efficient memory usage
Implementation Patternsο
Modern Agent Example: ```python from orka.agents.base_agent import BaseAgent
- class MyModernAgent(BaseAgent):
- async def _run_impl(self, ctx):
input_data = ctx.get(βinputβ) # Process input asynchronously result = await self.process_async(input_data) return result
Legacy Agent Example: ```python from orka.agents.base_agent import LegacyBaseAgent
- class MyLegacyAgent(LegacyBaseAgent):
- def run(self, input_data):
# Simple synchronous processing return self.process_sync(input_data)
Error Handlingο
Modern Agents: - Exceptions are automatically caught and wrapped in Output objects - Error details are preserved for debugging - Status indicators show success/failure state - Metadata includes agent identification
Legacy Agents: - Exceptions propagate directly to the orchestrator - Simple error handling for backward compatibility - Direct return values without wrapping
Integration Featuresο
Registry Integration: - Agents can access shared resources through the registry - Dependency injection for memory, embedders, and other services - Lazy initialization of expensive resources
Orchestrator Integration: - Agents are automatically discovered and instantiated - Configuration is passed through constructor parameters - Results flow seamlessly between agents in workflows
Monitoring and Debugging: - Automatic trace ID generation for request tracking - Execution timing and performance metrics - Comprehensive logging for troubleshooting
- __init__(agent_id: str, registry: Registry | None = None, prompt: str | None = None, queue: list[str] | None = None, timeout: float | None = 30.0, max_concurrency: int = 10, **kwargs)[source]ο
Initialize the base agent with common properties.
- Parameters:
agent_id (str) β Unique identifier for the agent
registry (Registry, optional) β Resource registry for dependency injection
prompt (str, optional) β Prompt or instruction for the agent (legacy)
queue (List[str], optional) β Queue of agents or nodes (legacy)
timeout (Optional[float]) β Maximum execution time in seconds
max_concurrency (int) β Maximum number of concurrent executions
**kwargs β Additional parameters specific to the agent type
- async initialize() None [source]ο
Initialize the agent and its resources.
This method is called automatically before the first execution and should be overridden by derived classes to set up any required resources.
- async run(ctx: Context | Any) Output | Any [source]ο
Run the agent with the given context.
This method handles the execution workflow including: - Lazy initialization of the agent - Adding trace information to the context - Managing concurrency and timeouts - Standardizing error handling and result formatting
- Parameters:
ctx β The execution context containing input and metadata. Can be a Context object for modern agents or any input for legacy agents.
- Returns:
Standardized output for modern agents or direct result for legacy agents
- Return type:
Output or Any
- class orka.agents.base_agent.LegacyBaseAgent(agent_id, prompt, queue, **kwargs)[source]ο
Bases:
ABC
,BaseAgent
Abstract base class for legacy agents in the OrKa framework. Provides compatibility with the older synchronous agent pattern.
New agent implementations should use BaseAgent directly with async methods. This class exists only for backward compatibility.
- __init__(agent_id, prompt, queue, **kwargs)[source]ο
Initialize the legacy base agent.
- Parameters:
agent_id (str) β Unique identifier for the agent.
prompt (str) β Prompt or instruction for the agent.
queue (list) β Queue of agents or nodes to be processed.
**kwargs β Additional parameters specific to the agent type.
- abstractmethod run(input_data)[source]ο
Abstract method to run the agentβs reasoning process. Must be implemented by all concrete agent classes.
- Parameters:
input_data β Input data for the agent to process.
- Returns:
The result of the agentβs processing.
- Raises:
NotImplementedError β If not implemented by a subclass.