PHP code example of helgesverre / pagent

1. Go to this page and download the library: Download helgesverre/pagent 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/ */

    

helgesverre / pagent example snippets




stant = agent('assistant')
    ->provider('openai')
    ->system('You are a concise and helpful PHP assistant.')
    ->temperature(0.3);

$response = $assistant->prompt('Explain readonly properties in PHP.');

echo $response->content;

$response = agent('assistant')->prompt('Show a short example.');

$agent = agent('writer')
    ->provider('anthropic')
    ->model('your-model-id')
    ->maxTokens(1_000);

use Pagent\Providers\Ollama;

$local = agent('local')
    ->provider(new Ollama([
        'base_url' => 'http://127.0.0.1:11434',
        'timeout' => 180,
    ]))
    ->model('qwen3:8b');

$response = openai()->prompt('Return a JSON object with a status field.', [
    'model' => 'your-model-id',
    'response_format' => ['type' => 'json_object'],
]);

use Pagent\Providers\OpenAI;
use Pagent\Providers\RetryingProvider;

$provider = RetryingProvider::wrap(new OpenAI, maxAttempts: 3);

use Pagent\Exceptions\PagentException;

try {
    $response = agent('writer')->prompt('Draft an outline.');
} catch (PagentException $exception) {
    // Provider, configuration, lifecycle, tool, and workflow failures.
}

// Zen uses https://opencode.ai/zen/v1 and x-preview-f-free.
$zen = opencode();
$zenResponse = $zen->prompt('Hello!');

// Go uses https://opencode.ai/zen/go/v1 and ox-alpha-free.
$go = opencode(['gateway' => 'go']);
$goResponse = $go->prompt('Hello!');

// A model using the Responses protocol.
$responses = opencode([
    'protocol' => 'responses',
]);

// Or select protocols by model while keeping a chat-completions default.
$mixed = opencode([
    'model_protocols' => ['your-responses-model' => 'responses'],
]);

// String aliases are available for agent configuration.
$coder = agent('coder')
    ->provider('opencode-go')
    ->model('ox-alpha-free');

$support = agent('order-support')
    ->provider('openai')
    ->system('Use the available tools to answer questions about orders.')
    ->tool(
        'find_order',
        'Find an order by its identifier',
        function (string $orderId, bool $42?');

use Pagent\Tools\FileRead;
use Pagent\Tools\Glob;
use Pagent\Tools\Grep;

$codebase = agent('codebase-assistant')
    ->provider('anthropic')
    ->tools([
        new Glob(baseDir: __DIR__),
        new Grep(baseDir: __DIR__),
        new FileRead(baseDir: __DIR__),
    ]);

$response = $codebase->prompt('Find the classes that implement the Provider contract.');

$assistant->streamTo('Write a short introduction to PHP generators.', function ($chunk): void {
    if ($chunk->isText()) {
        echo $chunk->content;
        flush();
    }
});

$stream = $assistant->stream('Summarize dependency injection in three points.');

foreach ($stream->getStream() as $chunk) {
    if ($chunk->isText()) {
        echo $chunk->content;
    }
}

$support = agent('support')
    ->provider('anthropic')
    ->memory('sqlite', ['path' => __DIR__.'/storage/conversations.db'])
    ->sessionId('customer-42')
    ->contextWindow(20_000);

$support->prompt('My order number is ORD-1042.');
$response = $support->prompt('What order are we discussing?');

$assistant = agent('public-assistant')
    ->provider('openai')
    ->guard('pii')
    ->guard('contentFilter')
    ->guard('promptInjection')
    ->fallback(fn (Throwable $error): string => 'This request cannot be processed.');

use Pagent\Middleware\RateLimitMiddleware;

$assistant
    ->middleware('logging')
    ->middleware(new RateLimitMiddleware(maxRequests: 60));

agent('researcher')
    ->provider('anthropic')
    ->system('Research the topic and return concise notes.');

agent('editor')
    ->provider('openai')
    ->system('Turn the supplied notes into a polished summary.');

$summary = pipeline('article')
    ->agent('researcher')
    ->agent('editor')
    ->run('How PHP fibers support cooperative concurrency');

$provider = mock([
    'What is the order status?' => 'The order has shipped.',
]);

$agent = agent('test-support')
    ->provider($provider)
    ->build();

$response = $agent->prompt('What is the order status?');

assert($response->content === 'The order has shipped.');

use Pagent\Evaluation\Dataset;
use Pagent\Evaluation\Metrics\KeywordMetric;

$result = evaluate('test-support')
    ->dataset(Dataset::fromArray([
        ['input' => 'What is the order status?', 'expected' => 'shipped'],
    ]))
    ->metric('status', new KeywordMetric(['shipped']))
    ->run();

echo $result->getAverageScore('status');

$assistant = agent('metered-assistant')
    ->provider('openai')
    ->trackUsage();

$assistant->prompt('Explain PHP attributes.');

$usage = $assistant->getUsage();

telemetry_console(verbose: true);

agent('traced-assistant')
    ->provider('anthropic')
    ->telemetry()
    ->prompt('Explain the repository pattern.');
bash
php examples/01-basic-chat.php