跳转到主要内容

SessionEvent

来自 Copilot 的所有消息都是 Revolution\Copilot\Types\SessionEvent 类。 由于该类使用频率最高,因此加入了 Laravel 风格的便利功能。

content()

获取来自 AI 的最重要的响应消息。
$response = Copilot::run('1 + 1');
echo $response->content(); // '2'
// content() 可能会是 null
通过 __toString() 的隐式类型转换也返回消息内容。
echo (string) $response; // '2'
// 这个不会是 null

Event type 的判定

可以使用 isAssistantMessage()isUserMessage()isIdle()isAssistantMessageDelta()。 如果有经常使用的 Event type,将来可能还会加入更多辅助函数。 is() 可以判定任意 EventType
use Revolution\Copilot\Enums\SessionEventType;

if ($response->is(SessionEventType::HOOK_START)) {
    // 钩子开始事件时的处理
}
type() 返回 SessionEventType enum 的字符串值。
echo $response->type(); // 'assistant.message'

failed() / successful()

当事件类型为 SESSION_ERROR 时,failed() 为 true。 successful() 则相反。 为了与 Laravel 的命名保持一致,已从 isError() 改名。

throw()

与 Laravel 的 HTTP API 和 Process API 一样,会保留错误,并可以通过 throw() 抛出异常。 没有错误时不做任何事,因此可以这样写。
$content = $response->throw()->content();
事件类型为 SESSION_ERROR 时会抛出 Revolution\Copilot\Exceptions\SessionErrorException。 超时时会抛出 Revolution\Copilot\Exceptions\SessionTimeoutException JSON-RPC 的错误会抛出 Revolution\Copilot\Exceptions\JsonRpcException

Conditionable

可以使用 when()unless()
$response->when($response->isAssistantMessage(), function (SessionEvent $event) {
    // 助手消息时的处理
});

Dumpable

可以使用 dump()dd()
$response->dump();

Tappable

可以使用 tap()
return $response->tap(function (SessionEvent $event) {
    // 做些处理
    info($event->content());
});

InteractsWithData

此功能仅应用于 SessionEvent 的 $data 属性。 可以使用 all()has()only()collect() 等常见辅助函数。 详情请参考 InteractsWithData 由于 SessionEvent 的 $data 会因 EventType 而结构不同,因此便于按事件访问值。 content() 内部也使用 InteractsWithData。
return $this->data('content', $default);

// 指定 default 后 content() 就不会是 null
echo $response->content('');

toArray() / toJson()

可以将整个 SessionEvent 转换为数组或 JSON。
$array = $response->toArray();
$json = $response->toJson();
没有面向整个事件的 collect() 方法。 因为 $data 已有 InteractsWithData 的 collect()。 如果想对整个事件进行 collection 操作,请使用 Laravel 的 collect() 辅助函数。
$collect = collect($response->toArray());

broadcast() / broadcastNow()

可以以与 Laravel AI SDK 的 StreamEvent 相同的接口进行广播。 AI SDK 在流式输出时使用它,但在 SessionEvent 中可以用于任意 EventType
use Illuminate\Broadcasting\Channel;

$event->broadcast(new Channel('channel-name'));
broadcastNow() 不经过队列,立即广播。
$event->broadcastNow(new Channel('channel-name'));
流式输出时的使用示例:
use Illuminate\Broadcasting\Channel;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Types\SessionConfig;
use Revolution\Copilot\Types\SessionEvent;

Copilot::start(function (CopilotSession $session) {
    $session->on(function (SessionEvent $event): void {
        if ($event->isAssistantMessageDelta()) {
            $event->broadcastNow(new Channel('copilot'));
        }
    });

    $session->sendAndWait(prompt: 'Tell me something about Laravel.');
}, config: new SessionConfig(streaming: true));
最新信息请参考 GitHub 仓库
最后修改于 2026年7月13日