跳转到主要内容

Session send()on()

sendAndWait() 会立刻返回响应,简单直观,但只能获取 最后一条助手消息
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;

Copilot::start(function (CopilotSession $session) {
    $response = $session->sendAndWait(prompt: 'Tell me something about Laravel.');
    dump($response->content());
});
如果也想接收中间的消息,请使用 on() 注册事件监听器。
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionEvent;

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->isAssistantMessage()) {
            dump($event->content());
        } else {
            dump($event);
        }
    });

    $message_id = $session->send(prompt: 'Tell me something about Laravel.');

    // 用循环等待消息接收
    $session->wait(timeout: 60.0);
});
在 PHP 中这样写不太直观,因此推荐结合 on()sendAndWait()
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionEvent;

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->isAssistantMessage()) {
            dump($event->content());
        } else {
            dump($event);
        }
    });

    $response = $session->sendAndWait(prompt: 'Tell me something about Laravel.');

    // 循环等待的部分已经在 sendAndWait() 内部处理,此时已经收到了最后一条消息。
    // 中间的消息已经通过上面的 on() 接收。

    // 不需要 sendAndWait 返回的最后一条消息。
    // dump($response->content());
});

on() 中指定特定事件类型

SessionEventType enum 或字符串指定事件类型,就可以只订阅该事件。
use Revolution\Copilot\Enums\SessionEventType;
use Revolution\Copilot\Types\SessionEvent;

$session->on(SessionEventType::ASSISTANT_MESSAGE, function (SessionEvent $event): void {
    dump($event->content());
});

$session->on('assistant.message', function (SessionEvent $event): void {
    dump($event->content());
});

订阅所有事件类型

不指定事件类型时会订阅所有事件。
use Revolution\Copilot\Enums\SessionEventType;
use Revolution\Copilot\Types\SessionEvent;

$session->on(function (SessionEvent $event): void {
});

// 也可以用命名参数指定
$session->on(handler: function (SessionEvent $event): void {
});

// 允许 null 的动态类型指定也可以。
$type = null;
$session->on(type: $type, handler: function (SessionEvent $event): void {
});
最新信息请参考 GitHub 仓库
最后修改于 2026年7月13日