使用者輸入請求
設定onUserInputRequest handler 後,agent 便可透過 ask_user 工具向使用者提問。
use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Types\UserInputRequest;
use Revolution\Copilot\Types\UserInputResponse;
Copilot::start(function (CopilotSession $session) {
$response = $session->sendAndWait(prompt: '請問使用者最喜歡的語言');
dump($response->content());
}, config: [
'model' => 'gpt-5',
'onUserInputRequest' => function (UserInputRequest $request): UserInputResponse {
// $request->question - 問題內容
// $request->choices - 多選項的陣列(選填)
// $request->allowFreeform - 是否允許自由輸入(預設:true)
dump("Question from agent: {$request->question}");
if ($request->choices) {
dump('Choices: '.implode(', ', $request->choices));
}
// 回傳使用者的回答
return new UserInputResponse(
answer: 'PHP',
wasFreeform: true, // 是否為自由輸入(非從選項中選擇)
);
},
]);
UserInputRequest 類別
代表來自 agent 的使用者輸入請求。| 屬性 | 型別 | 說明 |
|---|---|---|
question | string | 要詢問使用者的問題 |
choices | ?array | 多選時的選項(選填) |
allowFreeform | ?bool | 是否允許自由輸入(預設:true) |
UserInputResponse 類別
對使用者輸入請求的回應。| 屬性 | 型別 | 說明 |
|---|---|---|
answer | string | 使用者的回答 |
wasFreeform | bool | 回答是否為自由輸入(非從選項)時為 true |
實務範例
在互動式指令中使用的情境。use Revolution\Copilot\Facades\Copilot;
use Revolution\Copilot\Contracts\CopilotSession;
use Revolution\Copilot\Types\UserInputRequest;
use Revolution\Copilot\Types\UserInputResponse;
// 在 Artisan 指令中
Copilot::start(function (CopilotSession $session) use ($command) {
$response = $session->sendAndWait(prompt: '進行專案設定');
$command->info($response->content());
}, config: [
'onUserInputRequest' => function (UserInputRequest $request) use ($command): UserInputResponse {
if ($request->choices) {
// 若有選項則使用 choice 方法
$answer = $command->choice(
$request->question,
$request->choices,
$request->choices[0] ?? null
);
return new UserInputResponse(answer: $answer, wasFreeform: false);
}
// 自由輸入
$answer = $command->ask($request->question);
return new UserInputResponse(answer: $answer, wasFreeform: true);
},
]);
最新資訊請參考 GitHub 儲存庫。