PHP code example of particle-academy / prism-harness

1. Go to this page and download the library: Download particle-academy/prism-harness 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/ */

    

particle-academy / prism-harness example snippets


$session = PrismHarness::for($user)->session('support');

$session->usingMode('plan')->usingModel('claude-sonnet-4-5');

$session->lock(function (Session $session) {
    // whatever must not happen twice
});

$tools = app(\Prism\Harness\Tools\ToolRegistry::class)->forAgent('support');
$tools->register((new \Prism\Prism\Tool)->as('lookup')->for('Look up an item')
    ->using(fn (): string => 'found'), 'app.support');
app(\Prism\Harness\Modes\ModeRegistry::class)->forAgent('support')
    ->register('reply', ['tools' => ['lookup']], 'app.support')->setDefault('reply');
$support = app(\Prism\Harness\PrismHarness::class)->forAgent('support');
$descriptors = $support->effectiveTools('reply', $user, 'case:42');
$session = $support->for($user)->session('case:42');

'stores' => [
    'ephemeral' => 'redis',      // recommended in production
    'durable'   => 'database',
],

'drivers' => [
    'redis' => [
        // An assertion about your infrastructure, not a preference.
        'durable' => true,
    ],
],

use Prism\Harness\Models\Thread;

$thread = Thread::forParticipant($user, 'support');

$response = Prism::text()
    ->using(Provider::Anthropic, 'claude-sonnet-4-5')
    ->withThread($thread)              // everything said so far
    ->withPrompt('And after that?')    // the turn being taken now
    ->asText();

$thread->record($response->messages);  // the full exchange, tool steps 

// config/prism-harness.php — the shipped strategy, deterministic and no model call
'context' => ['keep_recent' => 200],

// or your own
class KeepWhatMatters implements Prism\Harness\Contracts\CompactionStrategy
{
    public function compact(array $messages): CompactionOutcome
    {
        return new CompactionOutcome(kept: /* ... */, evicted: /* ... */);
    }
}

$this->app->singleton(CompactionStrategy::class, KeepWhatMatters::class);

'context' => ['summarise_with' => 'claude-haiku-4-5-20251001', 'keep_recent' => 20],

$this->app->bind(SummaryBudget::class, fn () => new TruncateTo);

// May this tool be OFFERED to this run at all?
Gate::define('harness.tool', fn ($user, Session $s, Tool $t) => $user->can('use', $t->name()));

// May THIS call proceed, with THESE arguments?
Gate::define('harness.tool.call', fn ($user, Session $s, Tool $t, array $args) =>
    str_starts_with($args['path'] ?? '', '/tmp/'));

foreach ($session->stream('Refactor the billing job') as $event) {
    // Prism's stream events, untouched — render them as you already do
}
// the turn is recorded and the run closed out when the stream ends

use Prism\Prism\Schema\{ArraySchema, ObjectSchema, StringSchema};

$schema = new ObjectSchema('plan', 'A proposed plan', [
    new StringSchema('title', 'What the plan is called'),
    new ArraySchema('steps', 'What to do', new StringSchema('step', 'One step')),
], 

use Prism\Harness\Exceptions\StructuredSchemaViolation;

try {
    $plan = $session->sendStructured($brief, $schema)->structured();
} catch (StructuredSchemaViolation $violation) {
    $violation->code();       // structured_schema_violation, or structured_unreadable
    $violation->problems();   // every way it missed, not the first
    $violation->document();   // what the model actually said
}

use Prism\Prism\ValueObjects\Media\Image;

$session->send('What is wrong with this layout?', null, [
    Image::fromBase64($request->string('screenshot'), 'image/png'),
]);

'modes' => [
    'overseer' => [
        'system_prompt' => '...',
        'provider_options' => [
            'thinking' => ['type' => 'adaptive'],
            'effort' => 'medium',
        ],
    ],
],

$reply = (new VoiceExchange)->exchange($session, Audio::fromBase64($base64, 'audio/webm'));

$reply->heard;   // the transcript — what the model was actually asked
$reply->text;    // the answer
$reply->audio;   // the answer spoken, or null when the turn produced no prose
$reply->empty;   // true when nothing was heard, and no turn was spent

$voice->transcribe(Audio::fromBase64($request->string('audio'), 'audio/webm'));  // fine
$voice->transcribe(Audio::fromLocalPath($request->string('path')));              // file read
$voice->transcribe(Audio::fromUrl($request->string('url')));                     // SSRF

new VoiceExchange(allowReferencedAudio: true);

'benchmark' => [
    'tools' => ['workspace_read', 'workspace_write', 'workspace_delete'],
    '

$response = $session->send('Clean up the failed run');

if ($response->awaitingApproval()) {
    $session->decide(array_map(
        fn (ToolApprovalRequest $pending) => new ToolApprovalResponse($pending->approvalId, approved: true),
        $response->pendingApprovals(),
    ));
}

'modes' => [
    'designer' => [
        'system_prompt' => 'You author and revise Compass Ops.',
        'tools' => ['read_op', 'write_op'],
        'max_steps' => 12,
        'subagents' => [
            'run_op' => [
                'description' => 'Test-run an Op and report what happened.',
                'mode' => 'op_runner',   // the child's authority, not the parent's
                'max_steps' => 4,
                'max_cost_usd' => 0.25,
                'max_output_tokens_per_call' => 2048,
            ],
        ],
    ],
    'op_runner' => [
        'system_prompt' => 'You run one Op and report the outcome.',
        'tools' => ['execute_op'],       // deliberately NOT the designer's tools
        'max_steps' => 4,
    ],
],

use Prism\Harness\Subagents\RunBudget;
use Prism\Harness\Subagents\RunContext;

// Your configured provider/model, not values selected by the model or browser.
$prices = [$provider => [$model => [
    'inputPerMTok' => 2.0,        // USD per million ordinary input tokens
    'outputPerMTok' => 10.0,
    'cacheWritePerMTok' => 2.5,   // optional; otherwise ordinary input price
    'cacheReadPerMTok' => 0.1,    // optional; otherwise ordinary input price
    'toolOverheadTokens' => 286, // configured provider-added tool system prompt
    'imageTokenBound' => 8000,   // your conservative bound per image, if images are allowed
]]];

$build = RunContext::root('build-'.$buildId, new RunBudget(
    maxSteps: 100,
    maxCostUsd: 10.0,
    maxOutputTokensPerCall: 4096,
), pricing: $prices);

// Create one child allowance per page, sharing the build's cumulative ledger.
$page = new RunContext(
    ledger: $build->ledger,
    budget: (new RunBudget(12, maxCostUsd: 1.0, maxOutputTokensPerCall: 2048))
        ->nestedWithin($build->budget, $build->ledger),
    pricing: $build->pricing,
    observer: $build->observer,
);
$session->send('Build this page', context: $page);
$session->sendStructured('Describe this page', $schema, context: $page);
foreach ($session->stream('Revise this page', context: $page) as $event) {
    // Consume the entire generator: each model call yields its original events.
}

'multiplier' => 1.1,
'tiers' => [[
    'aboveInputTokens' => 100000,
    'inputPerMTok' => 0.50, 'outputPerMTok' => 2.50,
    'cacheWritePerMTok' => 0.625, 'cacheReadPerMTok' => 0.05,
]],

use Prism\Harness\Contracts\CallCostObserver;
use Prism\Harness\Exceptions\CallRefused;
use Prism\Harness\Subagents\{CallReservation, CallSettlement, RunContext};

final class AccountCosts implements CallCostObserver
{
    public function reserving(CallReservation $call, RunContext $run): void
    {
        // Atomically reserve $call->worstCaseUsd in your account, keyed by $call->callId.
        // Throw new CallRefused('account_exhausted') if your account cannot admit it.
    }

    public function settled(CallSettlement $call, RunContext $run): void
    {
        // Replace that reservation with $call->chargedUsd, using the same callId.
    }
}

$run = RunContext::root('build-'.$buildId, $budget, pricing: $prices,
    observer: app(AccountCosts::class));
$session->send('Build this page', context: $run);

$tasks = $session->tasks();

$tasks->add('Draft the summary', 't-1');
$tasks->add('Check the figures', 't-2');

while ($tasks->pending() > 0) {
    $task = $tasks->claim($workerId);   // one atomic call

    if ($task === null) {
        break;                          // someone else holds what is left
    }

    $result = $session->send($task->instruction());

    $tasks->release($task, $workerId, TaskOutcome::Done);   // the APPLICATION decides
}

$session = PrismHarness::for($user)->session();   // rehydrated, not constructed

$session->mode('plan');                          // persisted on the thread
$response = $session->send('Refactor the billing job');

if ($response->awaitingApproval()) {
    $session->approve($response->pendingApprovals()[0]);
}

php artisan harness:doctor