send method

Future<String> send(
  1. String prompt, {
  2. void onText(
    1. String text
    )?,
  3. CancellationToken? cancel,
})

Sends prompt and returns the model's final text.

onText receives response text as it streams in. The conversation is only extended when the request completes, so a failed or cancelled request leaves the history as it was.

Implementation

Future<String> send(
  String prompt, {
  void Function(String text)? onText,
  CancellationToken? cancel,
}) async {
  final result = await ai.generate(
    model: model,
    system: systemPrompt,
    messages: List<Message>.of(_history),
    prompt: prompt,
    tools: tools,
    maxTurns: maxTurns,
    cancel: cancel,
    onChunk: onText == null ? null : (chunk) => onText(chunk.text),
  );
  // Genkit ends a cancelled generation with an aborted result instead of
  // throwing, so the cancellation is surfaced here.
  cancel?.throwIfCancelled();
  // Providers report API errors (bad key, rate limit, refusal) as a finish
  // reason rather than throwing.
  if (result.finishReason == FinishReason.failed || result.finishReason == FinishReason.blocked) {
    throw CodingAgentException(result.finishMessage ?? 'The model request ${result.finishReason.value}.');
  }
  _history
    ..clear()
    ..addAll(result.messages.where((message) => message.role != Role.system));
  return result.text;
}