PHP code example of agentic-actions / laravel

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

    

agentic-actions / laravel example snippets




namespace App\Actions;

use AgenticActions\Action;
use AgenticActions\ActionContext;
use AgenticActions\Attributes\Expose;
use AgenticActions\Effect;
use AgenticActions\Refusal;
use App\Models\Post;
use App\Models\User;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Support\ValidatedInput;

#[Expose]
final class CreatePost extends Action
{
    protected string $description = 'Create a draft blog post. Publishing is a separate action.';

    protected ?Effect $effect = Effect::Write;

    protected array $touches = ['posts'];

    protected bool $tenantScoped = false; // Only matters once config('agentic-actions.tenant.model') is set.

    /**
     * The post's fields.
     */
    public function schema(JsonSchema $schema): array
    {
        return [
            'title' => $schema->string()->max(120)->ext->actor(User::class);

        if ($author->posts()->where('title', $input->string('title')->toString())->exists()) {
            throw Refusal::make(__('You already have a post with that title.'))->on('title');
        }

        return $author->posts()->create([...$input->all(), 'status' => 'draft']);
    }
}

use AgenticActions\Facades\Actions;

Route::middleware('auth')->group(fn () => Actions::routes());

use AgenticActions\Facades\Actions;

Route::middleware('auth:sanctum')->name('api.')->group(fn () => Actions::routes());

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title');
    $table->text('body');
    $table->string('excerpt')->nullable();
    $table->string('status');
    $table->timestamps();
});



namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title', 'body', 'excerpt', 'status'];
}

use Illuminate\Database\Eloquent\Relations\HasMany;

public function posts(): HasMany
{
    return $this->hasMany(Post::class);
}

$token = $user->createToken('importer', ['actions:read', 'actions:write'])->plainTextToken;

$post = Http::withToken($token)
    ->acceptJson()
    ->post('https://example.com/api/actions/create-post', [
        'title' => 'Hello',
        'body' => 'My first post.',
    ])
    ->throw()
    ->json();

public function handle(ActionContext $context, ValidatedInput $input): Post
{
    $author = $context->actor(User::class);
    $key = $context->call's post
    }

    if ($author->posts()->where('title', $input->string('title')->toString())->exists()) {
        throw Refusal::make(__('You already have a post with that title.'))->on('title');
    }

    return $author->posts()->create([...$input->all(), 'status' => 'draft', 'idempotency_key' => $key]);
}

$key = $context->idempotencyKey === null ? null : $context->mpotency_key', $key)->first();



namespace App\Livewire;

use AgenticActions\ActionContext;
use AgenticActions\Refusal;
use App\Actions\CreatePost;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

final class CreatePostForm extends Component
{
    public string $title = '';

    public string $body = '';

    public function save(): void
    {
        try {
            CreatePost::run(['title' => $this->title, 'body' => $this->body], ActionContext::http(Auth::user()));
        } catch (Refusal $r) {
            throw $r->toValidationException();
        }

        $this->redirectRoute('posts.index');
    }
}



namespace App\Ai;

use AgenticActions\ActionContext;
use AgenticActions\Ai\Concerns\InteractsWithActions;
use AgenticActions\Attributes\UseToolset;
use App\Models\User;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasTools;
use Laravel\Ai\Promptable;

#[UseToolset]
final class BlogAssistant implements Agent, HasTools
{
    use Promptable;
    use InteractsWithActions;

    public function __construct(public User $user) {}

    public function instructions(): string
    {
        return 'You help the signed-in author manage their blog posts.';
    }

    protected function actionContext(): ActionContext
    {
        return ActionContext::agent($this->user);
    }
}

$token = $user->createToken('Claude Code', ['actions:read', 'actions:write'], now()->addDays(90))->plainTextToken;

use AgenticActions\Streaming\ActionsProtocol;
use AgenticActions\Streaming\ChatRequest;

Route::middleware('auth')->post('/assistant', function (Request $request) {
    $chat = ChatRequest::from($request);

    if ($chat->isEmpty()) {
        return response()->json(['message' => __('agentic-actions::stream.empty', ['max' => config('agentic-actions.agents.max_message_length')])], 422);
    }

    return (new BlogAssistant($request->user()))
        ->continueLastConversation($request->user())
        ->stream($chat)
        ->usingProtocol(new ActionsProtocol);
});

$fake = Actions::fake([CreatePost::class => ['id' => 1, 'title' => 'Hello']]);

// ... the code under test calls CreatePost::run(), a route or an agent tool ...

$fake->assertRan(CreatePost::class, fn (array $input) => $input['title'] === 'Hello');
bash
composer actions:install
bash
php artisan actions:check --update
bash
php artisan migrate
php artisan db:seed
php artisan actions:run create-post title=Hello "body=My first post." --as=1
bash
php artisan tinker --execute 'echo App\Models\User::find(1)->createToken("importer", ["actions:read", "actions:write"])->plainTextToken;'
bash
php artisan actions:run create-post title=Hello "body=My first post." --as=1
php artisan actions:run create-post --input='{"title": "Hello", "body": "My first post."}' --as=1