The MicroAgent is a lightweight, specialized agent designed for single-purpose tasks within the MAKER framework. It serves as the atomic unit of complex multi-agent systems, providing focused, consistent, and efficient execution of specific subtasks.
MicroAgents are the building blocks that enable the Massively Decomposed Agentic Processes (MDAP) approach, which can solve tasks requiring millions of steps with near-zero error rates through extreme decomposition and parallel voting.
- 🎯 Single Responsibility: Each agent has one specific role and does it well
- 🔄 Specialized Roles: Five distinct roles for different task types
- 📊 High Consistency: Low temperature (0.1) for deterministic outputs
- 🔁 Retry Logic: Built-in exponential backoff for reliability
- ⚡ Lightweight: Minimal overhead for fast execution
- 🔧 Customizable: Custom system prompts and configuration options
- 📝 PSR-3 Logging: Full observability and debugging support
The MicroAgent is included in the claude-php-agent package. Ensure you have the package installed:
composer require your-org/claude-php-agentuse ClaudeAgents\Agents\MicroAgent;
use ClaudePhp\ClaudePhp;
$client = new ClaudePhp(apiKey: 'your-api-key');
$microAgent = new MicroAgent($client, [
'role' => 'executor',
]);
// Execute a simple task
$result = $microAgent->execute('Calculate 15% tip on $67.43');
echo $result; // "$10.11"MicroAgents support five specialized roles, each optimized for specific task types:
The executor role is designed for direct task execution with precise, concise responses.
$executor = new MicroAgent($client, [
'role' => 'executor',
]);
$result = $executor->execute('Calculate the area of a circle with radius 5');Best For:
- Direct calculations
- Simple transformations
- Atomic operations
- Quick lookups
System Prompt:
"You are a focused executor. Execute tasks precisely and concisely."
The decomposer role breaks complex tasks into minimal, clear subtasks.
$decomposer = new MicroAgent($client, [
'role' => 'decomposer',
]);
$subtasks = $decomposer->execute(
'Break down the task of deploying a web application into subtasks'
);Best For:
- Task planning
- Breaking down complex processes
- Creating step-by-step procedures
- Identifying dependencies
System Prompt:
"You are a precise task decomposer. Break tasks into minimal, clear subtasks."
The composer role synthesizes multiple subtask results into coherent final answers.
$composer = new MicroAgent($client, [
'role' => 'composer',
]);
$result = $composer->execute(
"Combine these results: \n1. Server started\n2. Database connected\n3. Tests passed"
);Best For:
- Result aggregation
- Summary generation
- Report composition
- Multi-source synthesis
System Prompt:
"You are a result composer. Synthesize subtask results coherently."
The validator role verifies that results meet requirements and are correct.
$validator = new MicroAgent($client, [
'role' => 'validator',
]);
$isValid = $validator->execute(
'Validate this calculation: 15% of $67.43 = $10.11'
);Best For:
- Result verification
- Correctness checking
- Requirement validation
- Quality assurance
System Prompt:
"You are a validator. Verify that results meet requirements."
The discriminator role chooses the best solution from multiple alternatives.
$discriminator = new MicroAgent($client, [
'role' => 'discriminator',
]);
$bestOption = $discriminator->execute(
"Choose between: A) Fast but expensive, B) Slow but cheap, C) Balanced"
);Best For:
- Option selection
- Trade-off evaluation
- Voting systems
- Decision making
System Prompt:
"You are a discriminator. Choose the best solution from alternatives."
The MicroAgent accepts configuration options in its constructor:
$microAgent = new MicroAgent($client, [
'role' => 'executor', // Agent role
'model' => 'claude-sonnet-4-5', // Claude model
'max_tokens' => 2048, // Max response tokens
'temperature' => 0.1, // Sampling temperature
'logger' => $logger, // PSR-3 logger
]);| Option | Type | Default | Description |
|---|---|---|---|
role |
string | 'executor' |
Agent role (decomposer, executor, composer, validator, discriminator) |
model |
string | 'claude-sonnet-4-5' |
Claude model to use |
max_tokens |
int | 2048 |
Maximum tokens per response |
temperature |
float | 0.1 |
Sampling temperature (0.0-1.0) |
logger |
LoggerInterface | NullLogger |
PSR-3 compatible logger |
You can override the default system prompt for specialized behavior:
$microAgent = new MicroAgent($client, [
'role' => 'executor',
]);
$microAgent->setSystemPrompt(
'You are a code reviewer. Analyze code for bugs and suggest improvements.'
);
$review = $microAgent->execute($codeToReview);For critical tasks, use the built-in retry mechanism:
$microAgent = new MicroAgent($client);
try {
// Retries up to 3 times with exponential backoff: 0.1s, 0.2s, 0.4s
$result = $microAgent->executeWithRetry(
prompt: 'Critical calculation task',
maxRetries: 3
);
} catch (\Throwable $e) {
echo "All retry attempts failed: {$e->getMessage()}";
}Backoff Schedule:
- Attempt 1: Immediate
- Attempt 2: 100ms delay
- Attempt 3: 200ms delay
- Attempt 4: 400ms delay
$microAgent = new MicroAgent($client, [
'role' => 'validator',
]);
$role = $microAgent->getRole(); // "validator"$decomposer = new MicroAgent($client, ['role' => 'decomposer']);
$subtasks = $decomposer->execute('Plan a database migration');
// Process each subtask with executor agents
foreach (parseSubtasks($subtasks) as $task) {
$executor = new MicroAgent($client, ['role' => 'executor']);
$result = $executor->execute($task);
}// Generate multiple candidates in parallel
$candidates = [];
for ($i = 0; $i < 5; $i++) {
$agent = new MicroAgent($client, ['role' => 'executor']);
$candidates[] = $agent->execute('Solve this problem: ...');
}
// Vote on best answer
$discriminator = new MicroAgent($client, ['role' => 'discriminator']);
$bestAnswer = $discriminator->execute(
'Choose the best solution: ' . implode("\n", $candidates)
);$executor = new MicroAgent($client, ['role' => 'executor']);
$result = $executor->execute('Calculate compound interest...');
$validator = new MicroAgent($client, ['role' => 'validator']);
$isValid = $validator->execute("Verify this calculation: {$result}");
if (strpos($isValid, 'VALID') !== false) {
echo "Result validated: {$result}";
}$subtaskResults = [
$agent1->execute('Analyze performance'),
$agent2->execute('Check security'),
$agent3->execute('Review code quality'),
];
$composer = new MicroAgent($client, ['role' => 'composer']);
$finalReport = $composer->execute(
'Synthesize these analysis results: ' . implode("\n", $subtaskResults)
);MicroAgents are the foundation of the MAKER (Massively Decomposed Agentic Processes) framework. The MakerAgent orchestrates multiple MicroAgents to solve complex tasks with near-zero error rates.
use ClaudeAgents\Agents\MakerAgent;
$makerAgent = new MakerAgent($client, [
'voting_k' => 3, // First-to-ahead-by-3 voting
'enable_red_flagging' => true, // Detect uncertain responses
]);
// Internally, MakerAgent creates and coordinates multiple MicroAgents
$result = $makerAgent->run('Complex multi-step task...');Key MAKER Components:
- Decomposer MicroAgents: Break tasks into subtasks with voting
- Executor MicroAgents: Execute atomic subtasks in parallel
- Validator MicroAgents: Verify results at each step
- Composer MicroAgents: Synthesize subtask results
- Discriminator MicroAgents: Choose winning answers from votes
MicroAgents default to temperature 0.1 for maximum consistency:
// High consistency (default)
$agent = new MicroAgent($client, ['temperature' => 0.1]);
// For creative tasks, increase temperature
$agent = new MicroAgent($client, ['temperature' => 0.7]);Recommended Temperatures:
- 0.0-0.2: Calculations, validation, deterministic tasks
- 0.3-0.5: Balanced creativity and consistency
- 0.6-1.0: Creative writing, brainstorming
Adjust max_tokens based on expected response length:
// Short responses (calculations, yes/no)
$agent = new MicroAgent($client, ['max_tokens' => 512]);
// Medium responses (explanations)
$agent = new MicroAgent($client, ['max_tokens' => 2048]);
// Long responses (detailed analysis)
$agent = new MicroAgent($client, ['max_tokens' => 4096]);For maximum performance, execute multiple MicroAgents in parallel using async libraries:
// Sequential (slow)
$results = [];
foreach ($tasks as $task) {
$agent = new MicroAgent($client);
$results[] = $agent->execute($task);
}
// Parallel (fast) - pseudocode with async library
$promises = [];
foreach ($tasks as $task) {
$agent = new MicroAgent($client);
$promises[] = async($agent->execute($task));
}
$results = await_all($promises);Enable logging to monitor MicroAgent behavior:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('micro_agent');
$logger->pushHandler(new StreamHandler('path/to/micro_agent.log', Logger::DEBUG));
$microAgent = new MicroAgent($client, [
'role' => 'executor',
'logger' => $logger,
]);
$result = $microAgent->execute('Task');Log Events:
- Agent creation with configuration
- Task execution start
- Response received with token usage
- Errors and retry attempts
- Execution time metrics
$microAgent = new MicroAgent($client);
try {
$result = $microAgent->execute('Task');
} catch (\ClaudePhp\Exceptions\ApiException $e) {
// API errors (rate limits, invalid keys, etc.)
echo "API Error: {$e->getMessage()}";
} catch (\ClaudePhp\Exceptions\NetworkException $e) {
// Network connectivity issues
echo "Network Error: {$e->getMessage()}";
} catch (\Throwable $e) {
// Other errors
echo "Error: {$e->getMessage()}";
}Match the role to your task type:
// ✅ Good: Right role for the task
$decomposer = new MicroAgent($client, ['role' => 'decomposer']);
$subtasks = $decomposer->execute('Break down deployment process');
// ❌ Bad: Wrong role
$executor = new MicroAgent($client, ['role' => 'executor']);
$subtasks = $executor->execute('Break down deployment process');MicroAgents work best with focused, single-purpose tasks:
// ✅ Good: Atomic task
$result = $microAgent->execute('Calculate 15% tip on $67.43');
// ❌ Bad: Too complex for a single MicroAgent
$result = $microAgent->execute(
'Plan a party, calculate costs, send invitations, and order supplies'
);// ✅ Good: Retry critical calculations
$result = $microAgent->executeWithRetry('Critical calculation', 3);
// ⚠️ Caution: Don't retry idempotent operations that could cause duplicates
$result = $microAgent->execute('Send email notification');// ✅ Good: Low temperature for consistency
$calculator = new MicroAgent($client, [
'role' => 'executor',
'temperature' => 0.1,
]);
// The same input will produce nearly identical output
for ($i = 0; $i < 10; $i++) {
$result = $calculator->execute('15% of $67.43');
// All results will be very similar
}// ✅ Good: Use specialized agents together
$decomposer = new MicroAgent($client, ['role' => 'decomposer']);
$subtasks = $decomposer->execute($complexTask);
foreach (parseSubtasks($subtasks) as $subtask) {
$executor = new MicroAgent($client, ['role' => 'executor']);
$results[] = $executor->execute($subtask);
}
$composer = new MicroAgent($client, ['role' => 'composer']);
$finalResult = $composer->execute('Combine: ' . implode("\n", $results));$executor = new MicroAgent($client, ['role' => 'executor']);
$tip = $executor->execute('Calculate 18% tip on $123.45');
echo $tip; // "$22.22"$decomposer = new MicroAgent($client, ['role' => 'decomposer']);
$plan = $decomposer->execute(
'Break down the process of deploying a Laravel application to AWS'
);
echo $plan;
// 1. Set up AWS account and configure IAM
// 2. Create RDS database instance
// 3. Set up EC2 instance or use Elastic Beanstalk
// ...$validator = new MicroAgent($client, ['role' => 'validator']);
$isValid = $validator->execute(
'Validate: The square root of 144 is 12'
);
echo $isValid; // "VALID - The calculation is correct"$discriminator = new MicroAgent($client, ['role' => 'discriminator']);
$choice = $discriminator->execute(
"Choose the best approach:\n" .
"A) Microservices - Complex but scalable\n" .
"B) Monolith - Simple but harder to scale\n" .
"C) Modular monolith - Balanced approach"
);
echo $choice; // "Option C is best because..."$expert = new MicroAgent($client, ['role' => 'executor']);
$expert->setSystemPrompt(
'You are a PHP expert. Provide concise, production-ready code examples.'
);
$code = $expert->execute('Show me how to validate an email in PHP');
echo $code;
// filter_var($email, FILTER_VALIDATE_EMAIL) !== false- MakerAgent: Orchestrates multiple MicroAgents with voting
- AgentInterface: Base interface for all agents
- AgentResult: Standardized result container
public function __construct(ClaudePhp $client, array $options = [])Parameters:
$client(ClaudePhp): The Claude API client$options(array): Configuration options
Options:
role(string): Agent role - 'decomposer', 'executor', 'composer', 'validator', 'discriminator'model(string): Claude model namemax_tokens(int): Maximum tokens per responsetemperature(float): Sampling temperature (0.0-1.0)logger(LoggerInterface): PSR-3 logger
Execute the micro-agent's task.
Parameters:
$prompt(string): The task to execute
Returns:
string: The agent's response
Throws:
\Throwable: On execution failure
Execute with retry logic and exponential backoff.
Parameters:
$prompt(string): The task to execute$maxRetries(int): Maximum retry attempts
Returns:
string: The agent's response
Throws:
\Throwable: If all retry attempts fail
Get the micro-agent's role.
Returns:
string: The agent's role
Set a custom system prompt.
Parameters:
$prompt(string): The custom system prompt
Returns:
self: The agent instance for method chaining
Problem: Getting different answers for the same task
Solution: Lower the temperature
$agent = new MicroAgent($client, ['temperature' => 0.0]);Problem: Agent responses are cut off
Solution: Increase max_tokens
$agent = new MicroAgent($client, ['max_tokens' => 4096]);Problem: Hitting API rate limits
Solution: Add retry logic and delays
$result = $agent->executeWithRetry($task, 5);Problem: Agent not performing task correctly
Solution: Verify you're using the appropriate role
// For breaking down tasks
$agent = new MicroAgent($client, ['role' => 'decomposer']);
// For executing tasks
$agent = new MicroAgent($client, ['role' => 'executor']);This component is part of the claude-php-agent package and follows the same license.
For issues, questions, or contributions, please refer to the main project repository.