PHP code example of filippo-toso / pi

1. Go to this page and download the library: Download filippo-toso/pi library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

filippo-toso / pi example snippets


use FilippoToso\Pi\Facades\Pi;

$agent = Pi::create();
$answer = $agent->ask('What is the capital of France?');
echo $answer; // "The capital of France is Paris."
$agent->close();

$agent = Pi::create();
$agent->prompt('Write a haiku about Laravel');

foreach ($agent->stream() as $event) {
    if ($text = $event->getTextDelta()) {
        echo $text;
    }
}

$agent->close();

$agent = Pi::create();
$agent->prompt('Refactor the User model');

$fullText = $agent->streamWith(
    onText: fn(string $delta) => echo $delta,
    onThinking: fn(string $delta) => logger()->debug("Thinking: $delta"),
    onToolStart: fn(array $data) => logger()->info("Tool started: {$data['toolName']}"),
    onToolEnd: fn(array $data) => logger()->info("Tool finished: {$data['toolName']}"),
    onEvent: fn($event) => null, // access every raw event
);

$agent->close();

$agent = Pi::create([
    'provider' => 'openai',
    'model' => 'o3',
    'working_dir' => '/path/to/project',
    'timeout' => 120,
    'session' => true,
    'session_dir' => storage_path('pi-sessions'),
    'env' => [
        'OPENAI_API_KEY' => config('services.openai.key'),
    ],
]);

// Via facade
$agent = Pi::create();
$agent = Pi::create(['provider' => 'anthropic', 'model' => 'claude-sonnet-4-20250514']);

// Via dependency injection
public function __construct(private PiAgentFactory $factory) {}
$agent = $this->factory->create();

// Send a prompt (non-blocking, use stream() to consume events)
$agent->prompt('Hello!');

// Send with images
$agent->prompt('What is in this image?', images: [
    ['type' => 'image', 'data' => base64_encode($imageData), 'mimeType' => 'image/png'],
]);

// Send while agent is already streaming
$agent->prompt('New instruction', streamingBehavior: 'steer');
$agent->prompt('After you finish...', streamingBehavior: 'followUp');

// Simple blocking ask
$text = $agent->ask('What is 2+2?');

// Steering (while agent is running)
$agent->steer('Focus on error handling instead');

// Follow-up (after agent finishes)
$agent->followUp('Now summarize what you did');

// Abort current operation
$agent->abort();

$agent->prompt('Do something');

foreach ($agent->stream() as $event) {
    match ($event->type) {
        'message_update' => handleDelta($event->getTextDelta()),
        'tool_execution_start' => handleToolStart($event->data),
        'tool_execution_end' => handleToolEnd($event->data),
        'agent_end' => handleComplete($event->getMessages()),
        default => null,
    };
}

$agent->setModel('anthropic', 'claude-sonnet-4-20250514');
$agent->cycleModel();
$models = $agent->getAvailableModels();

$agent->setThinkingLevel('high');   // off, minimal, low, medium, high, xhigh
$agent->cycleThinkingLevel();

// Execute a command (output la');
echo $result['output'];
echo $result['exitCode'];

// Abort a running command
$agent->abortBash();

$state = $agent->getState();
$stats = $agent->getSessionStats();
$messages = $agent->getMessages();

$agent->newSession();
$agent->switchSession('/path/to/session.jsonl');
$agent->setSessionName('my-feature-work');

// Forking
$forkable = $agent->getForkMessages();
$agent->fork($forkable[0]['entryId']);

// Export
$htmlPath = $agent->exportHtml('/tmp/session.html');

// Last assistant text
$lastText = $agent->getLastAssistantText();

$agent->compact();
$agent->compact(customInstructions: 'Focus on code changes');
$agent->setAutoCompaction(true);

$agent->setAutoRetry(true);
$agent->abortRetry();

// Steering: deliver all queued messages at once, or one per turn
$agent->setSteeringMode('all');           // or 'one-at-a-time'
$agent->setFollowUpMode('one-at-a-time'); // or 'all'

$commands = $agent->getCommands();
// Returns: [['name' => 'fix-tests', 'source' => 'prompt', ...], ...]

// Invoke a command via prompt
$agent->prompt('/fix-tests');

// When streaming, handle extension UI requests
foreach ($agent->stream() as $event) {
    if ($event->isExtensionUiRequest()) {
        $method = $event->data['method'];
        $id = $event->data['id'];

        match ($method) {
            'select' => $agent->respondToExtensionUi($id, ['value' => 'Allow']),
            'confirm' => $agent->respondToExtensionUi($id, ['confirmed' => true]),
            'input' => $agent->respondToExtensionUi($id, ['value' => 'user input']),
            'notify' => null, // fire-and-forget, no response needed
            default => $agent->respondToExtensionUi($id, ['cancelled' => true]),
        };
    }
}

// Send any raw command
$response = $agent->sendCommand(['type' => 'get_state']);

// Fire-and-forget (no response waiting)
$agent->sendRaw(['type' => 'abort']);

// Read a single event
$event = $agent->readEvent(timeout: 5.0);

// Access the underlying connection
$connection = $agent->getConnection();
$stderrOutput = $connection->readStderr();

$agent->isRunning(); // Check if the pi process is alive
$agent->close();     // Terminate the subprocess (also called on __destruct)

$event->type;                   // Event type string
$event->isResponse();           // Is this a command response?
$event->isExtensionUiRequest(); // Is this an extension UI request?
$event->getTextDelta();         // Get text delta string (or null)
$event->getDelta();             // Get full assistantMessageEvent array
$event->getMessage();           // Get message from turn_end/message_start/message_end
$event->getMessages();          // Get messages from agent_end
$event->toArray();              // Get raw data array

use FilippoToso\Pi\Exceptions\PiException;
use FilippoToso\Pi\Exceptions\PiCommandException;
use FilippoToso\Pi\Exceptions\PiConnectionException;

try {
    $agent = Pi::create();
    $answer = $agent->ask('Hello');
} catch (PiConnectionException $e) {
    // Process failed to start, pipe broken, timeout
} catch (PiCommandException $e) {
    // Command returned success: false
    echo $e->command; // The command type that failed
} catch (PiException $e) {
    // Base exception for all pi errors
}
bash
php artisan vendor:publish --tag=pi-config