PHP code example of builtbyberry / laravel-swarm

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

    

builtbyberry / laravel-swarm example snippets


use App\Ai\Swarms\ContentPipeline;

$response = ContentPipeline::make()->prompt('Draft a launch post about Laravel queues.');

echo $response->output;



namespace App\Ai\Swarms;

use App\Ai\Agents\ArticleEditor;
use App\Ai\Agents\ArticlePlanner;
use App\Ai\Agents\ArticleWriter;
use BuiltByBerry\LaravelSwarm\Attributes\Topology;
use BuiltByBerry\LaravelSwarm\Concerns\Runnable;
use BuiltByBerry\LaravelSwarm\Contracts\Swarm;
use BuiltByBerry\LaravelSwarm\Enums\Topology as TopologyEnum;

#[Topology(TopologyEnum::Sequential)]
class ContentPipeline implements Swarm
{
    use Runnable;

    public function agents(): array
    {
        return [
            new ArticlePlanner,
            new ArticleWriter,
            new ArticleEditor,
        ];
    }
}

use App\Ai\Swarms\ContentPipeline;

$response = ContentPipeline::make()->prompt('Draft a launch post about Laravel queues.');

$response->output;
$response->steps;
$response->usage;
$response->artifacts;
$response->metadata;

$response = ContentPipeline::make()->prompt([
    'topic' => 'Laravel queues',
    'audience' => 'intermediate developers',
    'goal' => 'launch post',
]);

return response()->json($response);

use App\Ai\Swarms\ContentPipeline;

$response = ContentPipeline::make()
    ->queue([
        'topic' => 'Laravel queues',
        'audience' => 'intermediate developers',
    ])
    ->onConnection('redis')
    ->onQueue('ai');

$response->runId;

// Do this.
ContentPipeline::make()->queue(['draft_id' => $draft->id]);

// Do not rely on runtime constructor state crossing the queue boundary.
(new ContentPipeline($draft->id))->queue('Review the draft');

foreach (ContentPipeline::make()->stream(['topic' => 'Laravel queues']) as $event) {
    if ($event->type() === 'swarm_text_delta') {
        // $event->delta
    }
}

return ContentPipeline::make()->stream([
    'topic' => 'Laravel queues',
]);

use Illuminate\Broadcasting\PrivateChannel;

ContentPipeline::make()->broadcast(
    ['topic' => 'Laravel queues'],
    new PrivateChannel('swarm.content-pipeline'),
);

ContentPipeline::make()->broadcastNow(
    ['topic' => 'Laravel queues'],
    new PrivateChannel('swarm.content-pipeline'),
);

ContentPipeline::make()
    ->broadcastOnQueue(
        ['topic' => 'Laravel queues'],
        new PrivateChannel('swarm.content-pipeline'),
    )
    ->onQueue('ai-streams');

$stream = ContentPipeline::make()
    ->stream(['topic' => 'Laravel queues'])
    ->storeForReplay();

$runId = (string) Str::uuid();

ArticlePipeline::make()->stream(RunContext::from($task, $runId)); // abandoned mid-stream

// Resume on a fresh worker: same run id picks up where it left off.
return ArticlePipeline::make()->stream(RunContext::from($task, $runId));

$response = ContentPipeline::make()
    ->dispatchDurable([
        'topic' => 'Laravel queues',
        'audience' => 'intermediate developers',
    ])
    ->onQueue('swarm-durable');

$response->runId;

$response->inspect();
$response->pause();
$response->resume();
$response->cancel();
$response->signal('approval_received', ['approved' => true], idempotencyKey: 'approval-123');

use Illuminate\Support\Facades\Schedule;

Schedule::command('swarm:relay')->everyMinute();   // hedule::command('swarm:prune')->daily();         // retention: removes expired persistence rows

use BuiltByBerry\LaravelSwarm\Attributes\DurableStreaming;

#[DurableStreaming]
final class ClaimsReview implements Runnable { /* … */ }

use BuiltByBerry\LaravelSwarm\Contracts\SwarmMemory;
use BuiltByBerry\LaravelSwarm\Enums\MemoryScope;

$memory = app(SwarmMemory::class);
$memory->put(MemoryScope::Run, $runId, 'draft_approved', true);
$approved = $memory->get(MemoryScope::Run, $runId, 'draft_approved');

#[Topology(TopologyEnum::Sequential)]
class ContentPipeline implements Swarm
{
    use Runnable;

    public function agents(): array
    {
        return [new Planner, new Writer, new Editor];
    }
}

#[Topology(TopologyEnum::Parallel)]
class ResearchSwarm implements Swarm
{
    use Runnable;

    public function agents(): array
    {
        return [new MarketResearcher, new CompetitorResearcher, new SeoResearcher];
    }
}

#[Topology(TopologyEnum::Hierarchical)]
class SupportRoutingSwarm implements Swarm
{
    use Runnable;

    public function agents(): array
    {
        return [
            new SupportCoordinator,
            new PolicyAgent,
            new DraftAgent,
        ];
    }
}

#[Topology(TopologyEnum::StaticHierarchical)]
class ContentSwarm implements HasRoutePlan, Swarm
{
    use Runnable;

    public function agents(): array
    {
        return [new Researcher, new Writer, new Editor];
    }

    public function plan(): array
    {
        return [
            'start_at' => 'finish',
            'nodes' => [
                'finish' => ['type' => 'finish', 'output' => ''],
            ],
        ];
    }
}

use App\Ai\Swarms\ContentPipeline;

ContentPipeline::fake(['first response']);

expect((string) ContentPipeline::make()->prompt('Draft an intro'))->toBe('first response');

ContentPipeline::assertPrompted('Draft an intro');
ContentPipeline::assertNeverQueued();

ContentPipeline::assertQueued(['draft_id' => 42]);
ContentPipeline::assertStreamed('Draft an intro');
ContentPipeline::assertDispatchedDurably(['document_id' => 100]);

use BuiltByBerry\LaravelSwarm\Testing\InteractsWithSwarmEvents;

class ContentPipelineTest extends TestCase
{
    use InteractsWithSwarmEvents;
}

ContentPipeline::make()->run('Draft an intro');
ContentPipeline::assertEventFired(SwarmCompleted::class);
bash
composer swarm:install
php artisan make:swarm:swarm ContentPipeline
bash
php artisan swarm:health
php artisan swarm:health --durable
bash
php artisan make:swarm:swarm ContentPipeline