asResponder method
Adapts this provider to AgentResponder, for ChatController's managed
send().
Tool calls are dropped in this mode — a Stream<String> cannot
represent them. Use sendMessage when the model may call tools.
Pass history (typically () => controller.messages) so the provider
sees prior turns.
Implementation
AgentResponder asResponder({List<ChatMessage> Function()? history}) {
return (userMessage) {
final base = history != null ? history() : const <ChatMessage>[];
// ChatController.send() calls beginAssistantMessage() -- which appends
// an *empty* streaming placeholder -- before invoking the responder, so
// `base` already ends with that placeholder by the time this closure
// runs. Strip empty assistant messages so the provider sees the user's
// message as the true last turn, not an empty stub.
final conversation = [
for (final m in base)
if (!(m.role == ChatRole.assistant && m.isEmpty)) m,
];
// Stream has no whereType() (that's an Iterable method) -- narrow with
// where()+cast() instead.
return streamEvents(conversation)
.where((event) => event is TextDelta)
.cast<TextDelta>()
.map((event) => event.text);
};
}