Agent-Driven Codebase Search
Overview¶
Demonstrates how agents can autonomously search codebases by: - Searching for files matching patterns - Reading relevant files - Synthesizing information into answers - Using subagents for specialized tasks
This example shows the agent determining search strategy, executing searches, and analyzing results without predefined workflows. The agent decides which files to read based on search results.
Key concepts:
- SearchFilesTool: Search for files by pattern or content
- ReadFileTool: Read file contents
- UseSubagents: Spawn specialized subagents for subtasks
- AgentConsoleLogger: Provides visibility into agent execution stages
Example¶
<?php
require 'examples/boot.php';
use Cognesy\Agents\AgentBuilder\AgentBuilder;
use Cognesy\Agents\AgentBuilder\Capabilities\File\UseFileTools;
use Cognesy\Agents\AgentBuilder\Capabilities\Subagent\UseSubagents;
use Cognesy\Agents\AgentTemplate\Definitions\AgentDefinition;
use Cognesy\Agents\AgentTemplate\Definitions\AgentDefinitionRegistry;
use Cognesy\Agents\Core\Collections\NameList;
use Cognesy\Agents\Core\Data\AgentState;
use Cognesy\Agents\Events\AgentConsoleLogger;
use Cognesy\Messages\Messages;
// Create console logger for execution visibility
$logger = new AgentConsoleLogger(
useColors: true,
showTimestamps: true,
showContinuation: true,
showToolArgs: true, // Show search patterns and file paths
);
// Configure working directory
$workDir = dirname(__DIR__, 3);
// Register specialized subagents
$registry = new AgentDefinitionRegistry();
$registry->register(new AgentDefinition(
name: 'reader',
description: 'Reads files and extracts relevant information',
systemPrompt: 'You read files and extract relevant information. Be thorough and precise.',
tools: NameList::fromArray(['read_file']),
));
$registry->register(new AgentDefinition(
name: 'searcher',
description: 'Searches for files matching patterns',
systemPrompt: 'You search for files matching patterns. Use glob patterns effectively.',
tools: NameList::fromArray(['search_files']),
));
// Build main orchestration agent
$agent = AgentBuilder::base()
->withCapability(new UseFileTools($workDir))
->withCapability(new UseSubagents(provider: $registry))
->build()
->wiretap($logger->wiretap());
// Ask a question that requires search
$question = "Find all test files related to Agent capabilities and tell me what they test";
$state = AgentState::empty()->withMessages(
Messages::fromString($question)
);
echo "=== Agent Execution Log ===\n\n";
// Execute agent until completion
$finalState = $agent->execute($state);
echo "\n=== Result ===\n";
$answer = $finalState->finalResponse()->toString() ?: 'No answer';
echo "Answer: {$answer}\n";
echo "Steps: {$finalState->stepCount()}\n";
echo "Tokens: {$finalState->usage()->total()}\n";
echo "Status: {$finalState->status()->value}\n";
?>