AgentLoop::execute()
Overview¶
The simplest way to run an agent: AgentLoop::execute() runs the loop to completion and
returns the final AgentState. The loop sends messages to the LLM, processes any tool calls,
and repeats until the LLM produces a final response with no pending tool calls.
Key concepts:
- AgentLoop::default(): Creates a minimal agent loop with sensible defaults
- AgentState::empty(): Creates an empty immutable state container
- execute(): Runs the full loop and returns the final state
- AgentEventConsoleObserver: Attach via wiretap() to see execution lifecycle events
- finalResponse(): Access the agent's final text output
Example¶
<?php
require 'examples/boot.php';
use Cognesy\Agents\AgentLoop;
use Cognesy\Agents\Data\AgentState;
use Cognesy\Agents\Events\Support\AgentEventConsoleObserver;
use Cognesy\Messages\Messages;
// AgentEventConsoleObserver shows execution lifecycle events on the console
$logger = new AgentEventConsoleObserver(
useColors: true,
showTimestamps: true,
showContinuation: true,
);
// Create a default agent loop (no tools, just LLM conversation)
$loop = AgentLoop::default()
->wiretap($logger->wiretap());
// Prepare initial state with a user message
$state = AgentState::empty()->withMessages(
Messages::fromString('What are the three primary colors? Answer in one sentence.')
);
// Execute the loop to completion
echo "=== Agent Execution ===\n\n";
$finalState = $loop->execute($state);
// Read the result
echo "\n=== Result ===\n";
$response = $finalState->finalResponse()->toString() ?: 'No response';
echo "Answer: {$response}\n";
echo "Agent ID: {$finalState->agentId()->toString()}\n";
echo "Execution ID: {$finalState->execution()?->executionId()->toString()}\n";
echo "Last Step ID: {$finalState->lastStep()?->stepId()->toString()}\n";
echo "Steps: {$finalState->stepCount()}\n";
echo "Tokens used: {$finalState->usage()->total()}\n";
echo "Status: {$finalState->status()->value}\n";
if ($finalState->status()->value !== 'completed') {
echo "Skipping assertions because execution status is {$finalState->status()->value}.\n";
exit(1);
}
// Assertions
assert($finalState->status() === \Cognesy\Agents\Enums\ExecutionStatus::Completed);
assert(!empty($finalState->finalResponse()->toString()), 'Expected non-empty response');
assert($finalState->stepCount() >= 1, 'Expected at least 1 step');
assert($finalState->usage()->total() > 0, 'Expected token usage > 0');
?>