model method

  1. @override
Future<ModelResponse> model(
  1. ModelRequest request,
  2. ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx,
  3. Future<ModelResponse> next(
    1. ModelRequest request,
    2. ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx
    )
)

Middleware for the raw model call.

Wraps the call to the model action.

Implementation

@override
Future<ModelResponse> model(
  ModelRequest request,
  ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx,
  Future<ModelResponse> Function(
    ModelRequest request,
    ActionFnArg<ModelResponseChunk, ModelRequest, void> ctx,
  )
  next,
) async {
  // Resolve the catalog by id from the registry (falls back to the bundled
  // basic catalog for the default id).
  final catalog = resolveCatalog(_registry, _catalogId);

  _warnOnPreSpecClient(request);

  // Every A2UI message the client already holds. Blocks are checked against
  // the surfaces it leaves live, so one may update or replace them (see
  // A2uiStreamParser).
  // Only model messages: a user message carries actions, not surfaces, and
  // a surface in one would not be the agent's.
  final history = [
    for (final m in request.messages)
      if (m.role == Role.model) ...a2uiEnvelopesFromParts(m.content),
  ];

  // 0) Sanitize any inbound a2ui data parts (e.g. a surface action sent back
  //    as the next turn, or replayed history) into model-readable text, so
  //    the underlying model's converter never sees the a2ui mime type.
  final sanitized = _sanitizeInboundA2ui(request);

  // 1) Inject catalog instructions into the system prompt.
  final newRequest = _instructions == 'none'
      ? sanitized
      : _injectInstructions(sanitized, catalog);

  // 2) Wrap the streaming callback so streamed text is split into prose
  //    deltas + whole a2ui parts as blocks complete.
  var wrappedCtx = ctx;
  A2uiStreamParser? streamParser;
  // Sources of the blocks already sent on the stream, so the parts the final
  // message adds (a repaired block, or one that depended on it) can be sent
  // after it.
  final streamed = <String>[];
  // Whether the model streamed at all. If it did not (a provider or cache
  // that answers in one piece), the client reads the final message and gets
  // no catch-up chunk either.
  var sawChunks = false;
  if (ctx.streamingRequested) {
    streamParser = A2uiStreamParser.internal(
      catalog: catalog,
      // Never throw from here: this runs inside the provider's chunk
      // callback, where a throw fails (and retries) the whole model call.
      // A bad block is just left off the stream; the final message, after
      // any repair, applies the configured mode.
      validate: _validate == A2uiValidateMode.off
          ? A2uiValidateMode.off
          : A2uiValidateMode.warn,
      // The final parse sees these blocks again and reports them.
      quiet: true,
      history: history,
    );
    wrappedCtx = ctx.copyWith(
      sendChunk: (chunk) {
        sawChunks = true;
        final transformed = _transformChunk(chunk, streamParser!);
        if (transformed != null) {
          streamed.addAll(_sourcesOf(transformed.content));
          ctx.sendChunk(transformed);
        }
      },
    );
  }

  // 3) Run downstream model, then flush the stream parser so the last withheld
  //    prose tail (the parser holds back up to a partial opening tag) and any
  //    unterminated trailing block still reach the streaming consumer. Without
  //    this, clients that render purely from stream deltas would show truncated
  //    prose / miss a final block (the aggregated message recovers it, but the
  //    stream would not).
  final response = await next(newRequest, wrappedCtx);
  if (streamParser != null) {
    final tail = _partsFromSegments(streamParser.flush().segments);
    if (tail.isNotEmpty) {
      streamed.addAll(_sourcesOf(tail));
      ctx.sendChunk(ModelResponseChunk(role: Role.model, content: tail));
    }
  }

  // 4) Transform the final message. Surface ids are the model's own, so the
  //    final parse produces the same envelopes the stream did.
  final message = response.message;
  if (message == null) return response;
  // What the repair calls cost, reported with the turn's own usage.
  GenerationUsage? repairUsage;
  // A turn that did not finish normally (blocked, failed, ...) is not
  // repaired, just as Genkit skips output parsing for it.
  final repairs = _repair && !_isAbnormal(response.finishReason)
      ? await _repairFailedBlocks(
          message,
          catalog,
          history,
          ctx.cancel,
          // Repair reuses the model this hook already wraps, by calling
          // `next` with a one-shot request. That needs no extra
          // configuration and skips a2ui and anything before it in the
          // chain, which would re-inject the instructions and re-parse the
          // reply; middleware after it (retry, say) still applies.
          // Streaming is suppressed: a repair is an internal detail.
          //
          // The config is forwarded because it can carry what the call
          // needs to succeed at all (a per-request API key, for one). The
          // tradeoff: an output-shaping option (a JSON response type, a
          // forced function call) can defeat a plain-text repair, which then
          // fails, is logged, and leaves the block dropped as before.
          // Provider-side tools enabled in `config` stay on for the same
          // reason.
          (prompt, cancel) async {
            final reply = await next(
              ModelRequest(
                messages: [
                  Message(
                    role: Role.user,
                    content: [TextPart(text: prompt)],
                  ),
                ],
                config: request.config,
              ),
              ctx.copyWith(
                streamingRequested: false,
                sendChunk: (_) {},
                cancel: cancel,
              ),
            );
            repairUsage = _sumUsage(repairUsage, reply.usage);
            // A reply cut off by the token limit may still compile, as a
            // fragment; don't take it.
            if (reply.finishReason == FinishReason.length) return null;
            return reply.message?.content
                    .where((p) => p.isText)
                    .map((p) => p.text ?? '')
                    .join() ??
                '';
          },
        )
      : const <String, String>{};
  final result = _transformResponse(
    response,
    message,
    catalog,
    history,
    repairs,
    extraUsage: repairUsage,
    hadModelTurns: request.messages.any((m) => m.role == Role.model),
  );

  // 5) A block that failed on the stream and was repaired afterwards exists
  //    only in the final message. Send it (and any block that failed only
  //    because it depended on it) as one last chunk, so clients that render
  //    from the stream get the same surfaces the session history records.
  if (streamParser != null && sawChunks) {
    final catchUp = _catchUp(result.message?.content ?? [], streamed);
    if (catchUp.isNotEmpty) {
      ctx.sendChunk(ModelResponseChunk(role: Role.model, content: catchUp));
    }
  }
  return result;
}