【Laravel Prompts】v0.3.15で追加された関数諸々

Laravel

Laravel13リリースに向けての機能追加と思われますが、日本時間2026/03/17深夜(Laravel13リリース直前)にリリースされたLaravel Prompts v0.3.15にいくつかの新しい関数が追加されました。(Title/Stream/Task/Autocomplete/Notify)ひとつひとつ使い方を見ていきます。

Release v0.3.15 ?? laravel/prompts
Title Prompt by @joetannenbaum in #221Stream Prompt by @joetannenbaum in #222Task Prompt by @joetannenbaum in #223PHPSta...

この記事で確認する機能

  • Stream Prompt
  • Task Prompt
  • Autocomplete Prompt
  • Notify Prompt

※Title Promptは別記事で書いたので、当記事では省きます。

Stream Prompt

Stream Prompt は、AIチャットのストリーミングレスポンスのような演出をするプロンプトです。

Stream Prompt by joetannenbaum ツキ Pull Request #222 ツキ laravel/prompts
This PR introduces a new stream prompt for streaming responses out to the terminal. It automatically handles word wrappi...

プルリク内のサンプルコードでは、チャットボットで受け取ったストリーミングレスポンスのtext_deltaイベントについてループを回すイメージを表現しています。

このプロンプトは、渡す文字列を用意できさえすれば使えます。

例として、ChatGPTの回答を「response.txt」として保存して、PHP側で読み込んで使ってみることにします。

▼「response.txt」(質問内容:得意技教えて。コンパクトに。)

こんな感じでコンパクトに👇

---

### 🧠 技術解説・整理

* 複雑な内容をわかりやすく説明
* 違いや本質を実務目線で整理

### 💻 開発サポート

* 設計相談やエラー原因の切り分け
* 要望を実装レベルに落とし込む

### 📊 要約・構造化

* 長文を短く整理
* 抽象↔具体の変換が得意

---

ざっくり「技術を理解しやすくして、実装まで持っていく」のが強みです 👍

▼Stream Promptの使用例:「stream.php」

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use function Laravel\Prompts\stream;

// 文章全体を文字列変数へ格納して
$responseText = file_get_contents(__DIR__ . '/response.txt');

// マルチバイトで分割して配列に格納
$deltas = mb_str_split($responseText);

$stream = stream();
foreach ($deltas as $delta) {
    $stream->append($delta);
    usleep(7000);   // 7ミリ秒の待ち・・・好みで調整
}
$stream->close();

▼実行結果

Task Prompt

Task Prompt は、実行中のタスクを表示するのに使えるプロンプトです。

docker composeのコンテナビルド中のタスク表示のような感じです。

と言っただけでは伝わらないと思うので、分解してみていきます。

まずはプルリクの内容から。

Task Prompt by joetannenbaum ツキ Pull Request #223 ツキ laravel/prompts
This PR introduces a new task prompt which allows you to display the output from an actively running task. Features:hand...

このPRでは、アクティブなタスクの出力を表示する新しいタスクプロンプトが導入されます。特徴:

🔵出力時にANSIエスケープシーケンスを正しく処理
🔵スピナーラベルをリアルタイムで更新
🔵タスク実行時に出力する「stable」メッセージを追加
🔵表示ログライン数の調整制限
🔵部分行のサポート(ログをワードごとに追加)

▼Task Prompt の関数定義(vendor/larabel/prompts/src/helpers.php)

    /**
     * Display a task with a spinner and live output.
     *
     * @template TReturn of mixed
     *
     * @param  Closure(Support\Logger): TReturn  $callback
     * @return TReturn
     */
    function task(string $label, Closure $callback, ?int $limit = null): mixed
    {
        return (new Task($label, $limit ?? 10))->run($callback);
    }

※第二引数のコールバックには、実行時に引数として「Larave\Prompts\Support\Logger」が渡されます。

※第三引数の $limit は、何行以上でスクロールさせるかの数値です。(デフォルト10)

※コールバック内ではLoggerクラスを使って出力指示をします。

▼「Laravel\Prompts\Support\Logger」内のpublicメソッド

publicメソッド処理内容
line(string $message): void1行出力(末尾PHP_EOLで改行される)
partial(string $chunk): void現在の出力の末尾に追加出力(改行無し)
commitPartial(): void改行無し追加出力終了(改行)
success(string $message): void完了メッセージ出力
warning(string $message): void警告メッセージ出力
error(string $message): voidエラーメッセージ出力
label(string $message): voidラベル出力(固定表示、スピナー付き)

では、実際のコードを作って実行してみましょう。

Loggerのメソッドを一通り使ってみます。

▼Task Promptの使用例:「task.php」

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use Laravel\Prompts\Support\Logger;

use function Laravel\Prompts\task;

$responseText = file_get_contents(__DIR__.'/response.txt');
$deltas = mb_str_split($responseText);  // ストリーム用テキスト配列

task(
    label: 'ラベル1',
    callback: function (Logger $logger) use ($deltas) {
        usleep(500_000);

        $logger->label('ラベル2'); // ラベルは最上部固定(上書き出力)

        for ($i = 0; $i < 8; $i++) {    // 8行出力(6行目からスクロール)
            $logger->line("Line {$i}");
            usleep(200_000);
        }

        $logger->warning("警告!");
        $logger->error("エラー!");
        sleep(1);

        $logger->label("ストリーム開始");   // ラベル上書き
        foreach ($deltas as $delta) {
            $logger->partial($delta);
            usleep(5000);
        }
        $logger->commitPartial();
        $logger->success("完了!");
        sleep(1);
    },
    limit: 5,   // 5行を超えたらスクロール
);

▼実行結果

終了後に消えてしまうのは。。残せないものか。。

あと、コールバック内で他のプロンプトはうまく機能しないので使わない方が良いでしょう。

Autocomplete Prompt

Autocomplete Prompt は、選択肢を配列(またはCollection、クロージャー)で渡すと、入力に前方一致したものを候補として表示し、TAB押下で入力補完してくれるプロンプトです。上下矢印キーで候補の切り替えができます。

Autocomplete Prompt by joetannenbaum ツキ Pull Request #226 ツキ laravel/prompts
This PR introduces a new autocomplete prompt, allowing the user to get hints about which values are available while stil...

▼プルリクの内容

このPRでは新しいオートコンプリートプロンプトが導入され、ユーザーは利用可能な値のヒントを受け取りつつ、最終プロンプトの編集も可能です。

配列/コレクションベースのオプション、または現在の値を受け取り提案オプションを返すクロージャーの両方をサポートします。

▼関数定義の確認(vendor/laravel/prompts/src/helpers.php)

    /**
     * Prompt the user for text input with auto-completion.
     *
     * @param  array<string>|Collection<int, string>|Closure(string): (array<string>|Collection<int, string>)  $options
     */
    function autocomplete(
        string $label,
        array|Collection|Closure $options = [],
        string $placeholder = '',
        string $default = '',
        bool|string $required = false,
        mixed $validate = null,
        string $hint = '',
        ?Closure $transform = null,
    ): string {
        return (new AutoCompletePrompt(...get_defined_vars()))->prompt();
    }

▼Autocomplete Promptの使用例1(配列版):「autocomplete_array.php」

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use function Laravel\Prompts\autocomplete;

$files = [
    'app/Http/Controllers/UserController.php',
    'app/Http/Controllers/PostController.php',
    'app/Models/User.php',
    'app/Models/Post.php',
    'config/app.php',
    'config/database.php',
    'resources/views/welcome.blade.php',
    'resources/views/layouts/app.blade.php',
    'routes/web.php',
    'routes/api.php',
];

$path = autocomplete(
    label: 'ファイルを指定してください',
    options: $files,
    placeholder: '例: app/Models/User.php',
    required: 'ファイル指定は必須です',
    //validate: fn(string $file) => is_readable($file) ? null : 'ファイルが見つかりません',
    hint: 'Tabキーで入力補完、上下キーで候補を移動',
);

var_dump($path);

▼実行結果1

▼Autocomplete Promptの使用例2(クロージャー版):「autocomplete_closure.php」

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use function Laravel\Prompts\autocomplete;

$files = [
    'app/Http/Controllers/UserController.php',
    'app/Http/Controllers/PostController.php',
    'app/Models/User.php',
    'app/Models/Post.php',
    'config/app.php',
    'config/database.php',
    'resources/views/welcome.blade.php',
    'resources/views/layouts/app.blade.php',
    'routes/web.php',
    'routes/api.php',
];

$path = autocomplete(
    label: 'ファイルを指定してください',
    options: function (string $value) use ($files): array {
        return array_filter(
            $files,
            fn ($file) => str_starts_with(strtolower($file), strtolower($value)),
        );
    },
    placeholder: '例: app/Models/User.php',
    required: 'ファイル指定は必須です',
    //validate: fn(string $file) => is_readable($file) ? null : 'ファイルが見つかりません',
    hint: 'Tabキーで入力補完、上下キーで候補を移動',
);

var_dump($path);

▼実行結果2

Notify Prompt

Notify Prompt は、Mac OSとLinux向けのデスクトップ通知をするプロンプトです。

Notify Prompt by joetannenbaum ツキ Pull Request #228 ツキ laravel/prompts
This PR adds a new notify prompt that sends native desktop notifications from the terminal.Supports macOS (via osascript...

▼プルリクの内容

このPRは、端末からネイティブデスクトップ通知を送信する新しい通知プロンプトを追加します。

macOS(osascript経由)およびLinux(kdialogフォールバック付きnotify-send経由)をサポートしています
macOSは字幕と音声オプションをサポートし、Linuxはアイコンをサポートしています

▼関数定義の確認

    /**
     * Send a notification to the user. (macOS and Linux only)
     *
     * The icon option is Linux only. The subtitle and sound options are macOS only.
     *
     * @param  string  $subtitle  macOS only
     * @param  string  $sound  macOS only
     * @param  string  $icon  Linux only
     */
    function notify(string $title, string $body = '', string $subtitle = '', string $sound = '', string $icon = ''): void
    {
        (new NotifyPrompt(...get_defined_vars()))->display();
    }

※第3引数 $subtitle、第4引数 $sound は macOSのみ対応

※第5引数 $icon はLinuxのみ対応

▼Notify Promptの使用例:「notify.php」

<?php

use function Laravel\Prompts\confirm;
use function Laravel\Prompts\notify;

require __DIR__.'/../vendor/autoload.php';

notify('Basic Notification', 'Just a title and body');

confirm('Next: with a subtitle');

notify(
    title: 'With Subtitle',
    body: 'This one has a subtitle',
    //subtitle: 'Extra context here',
);

confirm('Next: with a sound');

notify(
    title: 'With Sound',
    body: 'You should hear Glass',
    sound: 'Glass',
);

confirm('Next: with everything');

notify(
    title: 'Full Notification',
    body: 'All the options at once',
    subtitle: 'Laravel Prompts',
    sound: 'Frog',
);

confirm('Next: title only');

notify('Title Only');

※リポジトリのplayground内にあるコードをそのまま貼り付けました。

筆者の環境 Ubuntu24.04.3 LTS (WSL2 on Windows11) 上では全く機能しませんでした。。

純粋にインストールしたデスクトップ版Linuxしか機能しないんだろうな。。

ちなみに、

composer require laravel/prompts

のみでインストールした状態から実行すると、Exceptionを吐いて動きません。

$ php playground/notify.php 
PHP Fatal error:  Uncaught Error: Class "Symfony\Component\Process\ExecutableFinder" not found in /home/macocci7/php/using-laravel-prompts-v0.3.15/vendor/laravel/prompts/src/NotifyPrompt.php:59
Stack trace:
#0 /home/macocci7/php/using-laravel-prompts-v0.3.15/vendor/laravel/prompts/src/NotifyPrompt.php(30): Laravel\Prompts\NotifyPrompt->sendLinux()
#1 /home/macocci7/php/using-laravel-prompts-v0.3.15/vendor/laravel/prompts/src/NotifyPrompt.php(129): Laravel\Prompts\NotifyPrompt->prompt()
#2 /home/macocci7/php/using-laravel-prompts-v0.3.15/vendor/laravel/prompts/src/helpers.php(335): Laravel\Prompts\NotifyPrompt->display()
#3 /home/macocci7/php/using-laravel-prompts-v0.3.15/playground/notify.php(8): Laravel\Prompts\notify()
#4 {main}
  thrown in /home/macocci7/php/using-laravel-prompts-v0.3.15/vendor/laravel/prompts/src/NotifyPrompt.php on line 59

symfony/process を追加することで動くようになります。

composer require symfony/process

Issueに登録するのも面倒なので放置することにします。。

(Laravel使うのが前提だとか言われると面倒)

まあ、でもここまで環境選ぶ機能は使わないなあ。。

まとめ

Agent Ready Frameworkを謳うLaravel13に向けて機能追加したという感じです。

Laravelチームのメンバーが多忙なのか、Laravel13リリース直前にJoeさんがバタバタと追加して、他のメンバーがよく吟味しないまま機能追加したという印象ですね。

・環境を選ぶもの:Title Prompt / Notify Prompt

・AIツールを意識したと思われるもの:Stream Prompt / Task Prompt

Autocomplete Prompt は筆者の File Selector Prompt を潰すために送り込まれた刺客かもしれません。(自意識過剰)

GitHub - macocci7/file-selector-prompt: An Additional File Selector Prompt for your Laravel/Prompts Applications.
An Additional File Selector Prompt for your Laravel/Prompts Applications. - macocci7/file-selector-prompt

最近、ダウンロード数が増えてきたところですが、まあ、なるようになるということで。

  • 0
  • 0
  • 0
  • 0

コメント

Copied title and URL